repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mediathekview/MediathekView | src/main/java/mediathek/tool/FileDialogs.kt | 1 | 5005 | package mediathek.tool
import org.apache.commons.lang3.SystemUtils
import java.awt.FileDialog
import java.awt.Frame
import java.io.File
import javax.swing.JFileChooser
class FileDialogs {
companion object {
@JvmStatic
fun chooseDirectoryLocation(parent: Frame, title: String, initialFile: String): File? {
var resultFile: File? = null
if (SystemUtils.IS_OS_MAC_OSX) {
//we want to select a directory only, so temporarily change properties
val chooser = FileDialog(parent, title)
System.setProperty("apple.awt.fileDialogForDirectories", "true")
chooser.mode = FileDialog.LOAD
chooser.isMultipleMode = false
if (initialFile.isNotEmpty()) {
chooser.directory = initialFile
}
chooser.isVisible = true
if (chooser.file != null) {
val files = chooser.files
if (files.isNotEmpty()) {
resultFile = files[0]
}
}
System.setProperty("apple.awt.fileDialogForDirectories", "false")
} else {
val chooser = JFileChooser()
if (initialFile.isNotEmpty()) {
chooser.currentDirectory = File(initialFile)
}
chooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
chooser.dialogTitle = title
chooser.isFileHidingEnabled = true
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
resultFile = File(chooser.selectedFile.absolutePath)
}
}
return resultFile
}
@JvmStatic
fun chooseLoadFileLocation(parent: Frame, title: String, initialFile: String): File? {
var resultFile: File? = null
if (SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_WINDOWS) {
val chooser = FileDialog(parent, title)
chooser.mode = FileDialog.LOAD
chooser.isMultipleMode = false
if (initialFile.isNotEmpty()) {
chooser.directory = initialFile
}
chooser.isVisible = true
if (chooser.file != null) {
val files = chooser.files
if (files.isNotEmpty()) {
resultFile = files[0]
}
}
} else {
val chooser = JFileChooser()
if (initialFile.isNotEmpty()) {
chooser.currentDirectory = File(initialFile)
}
chooser.fileSelectionMode = JFileChooser.FILES_ONLY
chooser.dialogTitle = title
chooser.isFileHidingEnabled = true
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
resultFile = File(chooser.selectedFile.absolutePath)
}
}
return resultFile
}
/**
* Show a native file dialog where possible, otherwise use the crappy swing file dialog.
* @param parent the parent for the dialog. Used only for native dialogs
* @param title Title of the shown dialog
* @param initialFile path info for initial directory/file display.
* @return the selected file or null if action was cancelled.
*/
@JvmStatic
fun chooseSaveFileLocation(parent: Frame, title: String, initialFile: String): File? {
var resultFile: File? = null
if (SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_WINDOWS) {
val chooser = FileDialog(parent, title)
chooser.mode = FileDialog.SAVE
chooser.isMultipleMode = false
if (initialFile.isNotEmpty()) {
chooser.directory = initialFile
}
chooser.isVisible = true
if (chooser.file != null) {
val files = chooser.files
if (files.isNotEmpty()) {
resultFile = files[0]
}
}
} else {
//Linux HiDPI does not work with either AWT FileDialog or JavaFX FileChooser as of JFX 14.0.1
val chooser = JFileChooser()
if (initialFile.isNotEmpty()) {
chooser.currentDirectory = File(initialFile)
}
chooser.fileSelectionMode = JFileChooser.FILES_ONLY
chooser.dialogTitle = title
chooser.isFileHidingEnabled = true
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
resultFile = File(chooser.selectedFile.absolutePath)
}
}
return resultFile
}
}
} | gpl-3.0 | c79976299b9f2e4099bc676af8fe2f80 | 40.371901 | 109 | 0.528272 | 5.446137 | false | false | false | false |
googleapis/gapic-generator-kotlin | generator/src/test/kotlin/com/google/api/kotlin/util/FlatteningTest.kt | 1 | 4406 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin.util
import com.google.api.kotlin.GeneratorContext
import com.google.api.kotlin.MockedProtoUtil
import com.google.api.kotlin.asNormalizedString
import com.google.api.kotlin.config.FlattenedMethod
import com.google.api.kotlin.config.asPropertyPath
import com.google.common.truth.Truth.assertThat
import com.google.protobuf.DescriptorProtos
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.whenever
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import kotlin.test.BeforeTest
import kotlin.test.Test
internal class FlatteningTest {
val context: GeneratorContext = mock()
val proto: DescriptorProtos.FileDescriptorProto = mock()
lateinit var mocked: MockedProtoUtil.BasicMockedProto
@BeforeTest
fun before() {
reset(context, proto)
mocked = MockedProtoUtil.getBasicMockedProto()
whenever(context.typeMap).doReturn(mocked.typeMap)
whenever(context.proto).doReturn(proto)
}
@Test
fun `can get parameters of flatten a method`() {
val method = DescriptorProtos.MethodDescriptorProto.newBuilder()
.setInputType(".test.the.input")
.build()
val config = FlattenedMethod(
listOf(
"foo.bar".asPropertyPath(),
"str".asPropertyPath(),
"pam".asPropertyPath()
)
)
val params = Flattening.getFlattenedParameters(context, method, config)
assertThat(params.config).isEqualTo(config)
assertThat(params.parameters).hasSize(3)
val bar = params.parameters.first { it.spec.name == "bar" }
assertThat(bar.spec.name).isEqualTo("bar")
assertThat(bar.spec.type).isEqualTo(Boolean::class.asTypeName())
assertThat(bar.flattenedPath).isEqualTo("foo.bar".asPropertyPath())
assertThat(bar.flattenedFieldInfo?.kotlinType).isEqualTo(Boolean::class.asTypeName())
assertThat(bar.flattenedFieldInfo?.file).isEqualTo(proto)
assertThat(bar.flattenedFieldInfo?.field).isEqualTo(mocked.fieldBar)
val str = params.parameters.first { it.spec.name == "str" }
assertThat(str.spec.name).isEqualTo("str")
assertThat(str.spec.type).isEqualTo(String::class.asTypeName())
assertThat(str.flattenedPath).isEqualTo("str".asPropertyPath())
assertThat(str.flattenedFieldInfo?.kotlinType).isEqualTo(String::class.asTypeName())
assertThat(str.flattenedFieldInfo?.file).isEqualTo(proto)
assertThat(str.flattenedFieldInfo?.field).isEqualTo(mocked.fieldStr)
val pam = params.parameters.first { it.spec.name == "pam" }
assertThat(pam.spec.name).isEqualTo("pam")
assertThat(pam.spec.type).isEqualTo(
Map::class.asClassName().parameterizedBy(
String::class.asTypeName(), String::class.asTypeName()
)
)
assertThat(pam.flattenedPath).isEqualTo("pam".asPropertyPath())
assertThat(pam.flattenedFieldInfo?.kotlinType).isEqualTo(ClassName("test.my", "Map"))
assertThat(pam.flattenedFieldInfo?.file).isEqualTo(proto)
assertThat(pam.flattenedFieldInfo?.field).isEqualTo(mocked.fieldMap)
assertThat(params.requestObject.asNormalizedString()).isEqualTo(
"""
|test.the.input {
| this.str = str
| this.pam = pam
| this.foo = test.bar {
| this.bar = bar
| }
|}
""".trimIndent().asNormalizedString()
)
}
} | apache-2.0 | c1fb78e3acb8704b68d55f558c52823f | 38.702703 | 93 | 0.689287 | 4.446014 | false | true | false | false |
cronokirby/FlashKi | src/com/cronokirby/flashki/models/Category.kt | 1 | 684 | package com.cronokirby.flashki.models
class Category(vararg strings: String) {
val paths = strings.toList()
fun nextCategory(): Category? {
val nextPaths = paths.drop(1)
return if (nextPaths.isEmpty()) null else Category(*nextPaths.toTypedArray())
}
override fun toString(): String {
return paths.joinToString("/")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Category
if (paths != other.paths) return false
return true
}
override fun hashCode(): Int {
return paths.hashCode()
}
} | mit | 43b4184eb05f22e7cb8670c28678daef | 22.62069 | 85 | 0.618421 | 4.470588 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/data/CrashDatabase.kt | 1 | 1259 | package six.ca.crashcases.fragment.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import six.ca.crashcases.fragment.data.cache.CacheDao
import six.ca.crashcases.fragment.data.cache.CacheEntity
import six.ca.crashcases.fragment.data.profile.ProfileDao
/**
* @author hellenxu
* @date 2021-01-26
* Copyright 2021 Six. All rights reserved.
*/
@Database(
entities = [
CacheEntity::class
],
version = 1
)
abstract class CrashDatabase : RoomDatabase() {
abstract fun cacheDao(): CacheDao
companion object {
private const val DB_NAME = "crash.db"
@Volatile
private var INSTANCE: CrashDatabase? = null
fun getInstance(appCtx: Context): CrashDatabase {
return INSTANCE ?: synchronized(CrashDatabase::class.java) {
INSTANCE ?: Room.databaseBuilder(appCtx, CrashDatabase::class.java, DB_NAME).build()
}
}
}
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
TODO("Not yet implemented")
}
}
} | apache-2.0 | c85a4798a5ed084e995e41b24ab3b475 | 25.808511 | 100 | 0.687847 | 4.253378 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/animalfarm/AnimalFarmEntity.kt | 1 | 10823 | package net.ndrei.teslapoweredthingies.machines.animalfarm
import net.minecraft.entity.item.EntityItem
import net.minecraft.entity.passive.EntityAnimal
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.nbt.NBTTagFloat
import net.minecraft.nbt.NBTTagInt
import net.minecraft.nbt.NBTTagString
import net.minecraftforge.items.ItemHandlerHelper
import net.ndrei.teslacorelib.compatibility.ItemStackUtil
import net.ndrei.teslapoweredthingies.TeslaThingiesMod
import net.ndrei.teslapoweredthingies.common.IAnimalAgeFilterAcceptor
import net.ndrei.teslapoweredthingies.integrations.getUnlocalizedName
import net.ndrei.teslapoweredthingies.items.AnimalPackageItem
import net.ndrei.teslapoweredthingies.items.BaseAnimalFilterItem
import net.ndrei.teslapoweredthingies.machines.ANIMAL_FARM_WORK_AREA_COLOR
import net.ndrei.teslapoweredthingies.machines.BaseXPCollectingMachine
/**
* Created by CF on 2017-07-06.
*/
class AnimalFarmEntity
: BaseXPCollectingMachine(AnimalFarmEntity::class.java.name.hashCode()), IAnimalAgeFilterAcceptor {
private val ENERGY_PACKAGE = .9f
private val ENERGY_FEED = .1f
private val ENERGY_SHEAR = .3f
private val ENERGY_MILK = .3f
override fun acceptsInputStack(slot: Int, stack: ItemStack): Boolean {
if (stack.isEmpty)
return true
// test for animal package
if (stack.item.registryName == AnimalPackageItem.registryName) {
return !AnimalPackageItem.hasAnimal(stack)
}
return AnimalFarmEntity.foodItems.contains(stack.item)
}
override fun getWorkAreaColor(): Int = ANIMAL_FARM_WORK_AREA_COLOR
override fun performWorkInternal(): Float {
var result = 0.0f
val toProcess = mutableListOf<IAnimalWrapper>()
var animalToPackage: IAnimalWrapper? = null
//region find animals
val facing = super.facing
val cube = this.getWorkArea(facing.opposite, 1)
val aabb = cube.boundingBox
// find animal
val animals = this.getWorld().getEntitiesWithinAABB(EntityAnimal::class.java, aabb)
val filter = super.getAddon(BaseAnimalFilterItem::class.java)
if (animals.size > 0) {
for (i in animals.indices) {
val thingy = AnimalWrapperFactory.getAnimalWrapper(animals[i])
if ((animalToPackage == null) && ((filter == null) || filter.canProcess(this, i, thingy.animal))) {
animalToPackage = thingy
} else if (thingy.breedable()) {
toProcess.add(thingy)
}
}
}
//endregion
//region process package
if (animalToPackage != null) {
var packageStack: ItemStack? = null
var packageSlot = 0
for (ti in 0 until this.inStackHandler!!.slots) {
packageStack = this.inStackHandler!!.extractItem(ti, 1, true)
if (!packageStack.isEmpty && packageStack.item is AnimalPackageItem && !AnimalPackageItem.hasAnimal(packageStack)) {
packageSlot = ti
break
}
packageStack = null
}
if ((packageStack != null) && !packageStack.isEmpty) {
val animal = animalToPackage.animal
val stackCopy = AnimalFarmEntity.packageAnimal(packageStack, animal)
if (!stackCopy.isEmpty && super.outputItems(stackCopy)) {
this.getWorld().removeEntity(animalToPackage.animal)
this.inStackHandler!!.extractItem(packageSlot, 1, false)
animalToPackage = null
result += ENERGY_PACKAGE
}
}
}
if (animalToPackage != null) {
toProcess.add(animalToPackage)
}
//endregion
val minEnergy = Math.min(ENERGY_FEED, Math.min(ENERGY_MILK, ENERGY_SHEAR))
if (toProcess.size >= 2 && 1.0f - result >= minEnergy) {
for (i in toProcess.indices) {
val wrapper = toProcess[i]
if (wrapper.breedable() && 1.0f - result >= ENERGY_FEED) {
//region breed this thing
val potentialFood = ItemStackUtil.getCombinedInventory(this.inStackHandler!!)
val foodStack: ItemStack? = potentialFood.indices
.map { potentialFood[it] }
.firstOrNull { wrapper.isFood(it) }
if ((foodStack != null) && !foodStack.isEmpty) {
for (j in i + 1 until toProcess.size) {
val toMateWith = toProcess[j]
if (toMateWith.breedable() && toMateWith.isFood(foodStack) && wrapper.canMateWith(toMateWith)) {
val foodUsed = wrapper.mate(TeslaThingiesMod.getFakePlayer(this.getWorld())!!, foodStack, toMateWith)
if (foodUsed > 0 && foodUsed <= foodStack.count) {
ItemStackUtil.extractFromCombinedInventory(this.inStackHandler!!, foodStack, foodUsed)
foodStack.shrink(foodUsed)
result += ENERGY_FEED
break
}
}
}
}
//endregion
}
if (wrapper.shearable() && 1.0f - result >= ENERGY_SHEAR) {
//region shear this unfortunate animal
val shearsSlot = (0 until this.inStackHandler!!.slots)
.firstOrNull { wrapper.canBeShearedWith(this.inStackHandler!!.getStackInSlot(it)) }
?: -1
if (shearsSlot >= 0) {
val shears = this.inStackHandler!!.getStackInSlot(shearsSlot)
val loot = wrapper.shear(shears, 0)
if (loot.isNotEmpty()) {
super.outputItems(loot) // TODO: test if successful
// TODO: only damage shears if at least 1 item was output
if (shears.attemptDamageItem(1, this.getWorld().rand, TeslaThingiesMod.getFakePlayer(this.getWorld())!!)) {
this.inStackHandler!!.setStackInSlot(shearsSlot, ItemStack.EMPTY)
}
result += ENERGY_SHEAR
}
}
//endregion
}
if (wrapper.canBeMilked() && 1.0f - result >= ENERGY_MILK) {
//region no milk left behind!
for (b in 0 until this.inStackHandler!!.slots) {
val stack = this.inStackHandler!!.extractItem(b, 1, true)
if (stack.count == 1 && stack.item === Items.BUCKET) {
val milk = wrapper.milk()
if (super.outputItems(milk)) {
this.inStackHandler!!.extractItem(b, 1, false)
result += ENERGY_MILK
break
}
}
}
//endregion
}
//region mushroom stew best stew
if (wrapper.canBeBowled() && 1.0f - result >= ENERGY_MILK) {
for (b in 0 until this.inStackHandler!!.slots) {
val stack = this.inStackHandler!!.extractItem(b, 1, true)
if (stack.count == 1 && stack.item === Items.BOWL) {
val stew = wrapper.bowl()
if (!stew.isEmpty && super.outputItems(stew)) {
this.inStackHandler!!.extractItem(b, 1, false)
result += ENERGY_MILK
break
}
}
}
}
//endregion
if (1.0f - result < minEnergy) {
break // no more energy
}
}
}
//region collect loot
if (result <= .9f) {
val items = this.getWorld().getEntitiesWithinAABB(EntityItem::class.java, aabb)
if (!items.isEmpty()) {
for (item in items) {
val original = item.item
// TODO: add a method for picking up EntityItems at super class
val remaining = ItemHandlerHelper.insertItem(this.outStackHandler, original, false)
var pickedUpLoot = false
if (remaining.isEmpty) {
this.getWorld().removeEntity(item)
pickedUpLoot = true
} else if (remaining.count != original.count) {
item.item = remaining
pickedUpLoot = true
}
if (pickedUpLoot) {
result += 1.0f
if (result > .9f) {
break
}
}
}
}
}
//endregion
return result
}
override fun acceptsFilter(item: BaseAnimalFilterItem): Boolean {
return !super.hasAddon(BaseAnimalFilterItem::class.java)
}
companion object {
private val foodItems = mutableListOf<Item>()
init {
AnimalFarmEntity.foodItems.add(Items.SHEARS)
AnimalFarmEntity.foodItems.add(Items.BUCKET)
AnimalFarmEntity.foodItems.add(Items.BOWL)
// ^^ not really food :D
AnimalWrapperFactory.populateFoodItems(AnimalFarmEntity.foodItems)
}
internal fun packageAnimal(packageStack: ItemStack?, animal: EntityAnimal): ItemStack {
val stackCopy = if (packageStack == null) ItemStack(AnimalPackageItem) else packageStack.copy()
stackCopy.setTagInfo("hasAnimal", NBTTagInt(1))
val animalCompound = NBTTagCompound()
animal.writeEntityToNBT(animalCompound)
stackCopy.setTagInfo("animal", animalCompound)
stackCopy.setTagInfo("animalClass", NBTTagString(animal.javaClass.name))
stackCopy.setTagInfo("animalHealth", NBTTagFloat(animal.health))
stackCopy.setTagInfo("animalName", NBTTagString(animal.getUnlocalizedName()))
return stackCopy
}
}
}
| mit | 0bd32d98d24e39cd2d7f16be0b64e19a | 39.996212 | 135 | 0.533678 | 4.957856 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/view/VerticalSeekBar.kt | 1 | 3036 | package org.videolan.vlc.gui.view
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.content.ContextCompat
import org.videolan.vlc.R
class VerticalSeekBar : AppCompatSeekBar {
private var listener: OnSeekBarChangeListener? = null
var fromUser = false
constructor(context: Context) : super(context) {
initialize()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initialize()
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
initialize()
}
private fun initialize() {
//The custom drawable looks not great for kitkat. So we use the default one to mitigate the issue
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressDrawable = ContextCompat.getDrawable(context, R.drawable.po_seekbar)
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val handled = super.onTouchEvent(event)
if (handled) {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
parent?.requestDisallowInterceptTouchEvent(true)
fromUser = true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
parent?.requestDisallowInterceptTouchEvent(false)
fromUser = false
}
}
}
return handled
}
override fun setOnSeekBarChangeListener(l: OnSeekBarChangeListener?) {
listener = l
super.setOnSeekBarChangeListener(l)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (isEnabled) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) return false
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
fromUser = true
//to allow snaping to save current state when modifying a band from DPAD
listener?.onStartTrackingTouch(this)
val direction = if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) -1 else 1
var currentProgress = progress + (direction * keyProgressIncrement)
if (currentProgress > max) {
currentProgress = max
} else if (currentProgress < 0) {
currentProgress = 0
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) setProgress(currentProgress, true) else progress = currentProgress
return true
}
}
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
fromUser = false
return super.onKeyUp(keyCode, event)
}
} | gpl-2.0 | 072672fe1e7d7fa47539d0d282692aab | 30.309278 | 134 | 0.615613 | 5.06 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/widget/ShortcutConfigActivity.kt | 1 | 5833 | package org.tasks.widget
import android.app.Activity
import android.content.Intent
import android.content.Intent.ShortcutIconResource
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import com.google.android.material.textfield.TextInputEditText
import com.todoroo.astrid.api.Filter
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.Strings.isNullOrEmpty
import org.tasks.databinding.ActivityWidgetShortcutLayoutBinding
import org.tasks.dialogs.ColorPalettePicker
import org.tasks.dialogs.ColorPalettePicker.Companion.newColorPalette
import org.tasks.dialogs.ColorPickerAdapter.Palette
import org.tasks.dialogs.FilterPicker.Companion.newFilterPicker
import org.tasks.dialogs.FilterPicker.Companion.setFilterPickerResultListener
import org.tasks.injection.ThemedInjectingAppCompatActivity
import org.tasks.intents.TaskIntents
import org.tasks.preferences.DefaultFilterProvider
import org.tasks.themes.DrawableUtil
import org.tasks.themes.ThemeColor
import javax.inject.Inject
@AndroidEntryPoint
class ShortcutConfigActivity : ThemedInjectingAppCompatActivity(), ColorPalettePicker.ColorPickedCallback {
@Inject lateinit var defaultFilterProvider: DefaultFilterProvider
private lateinit var toolbar: Toolbar
private lateinit var shortcutList: TextInputEditText
private lateinit var shortcutName: TextInputEditText
private lateinit var colorIcon: TextView
private lateinit var clear: View
private var selectedFilter: Filter? = null
private var selectedTheme = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityWidgetShortcutLayoutBinding.inflate(layoutInflater)
binding.let {
toolbar = it.toolbar.toolbar
shortcutList = it.body.shortcutList.apply {
setOnClickListener { showListPicker() }
setOnFocusChangeListener { _, hasFocus -> onListFocusChange(hasFocus) }
}
shortcutName = it.body.shortcutName
colorIcon = it.body.color.color
clear = it.body.color.clear.clear
it.body.color.colorRow.setOnClickListener { showThemePicker() }
}
setContentView(binding.root)
toolbar.setTitle(R.string.FSA_label)
toolbar.navigationIcon = getDrawable(R.drawable.ic_outline_save_24px)
toolbar.setNavigationOnClickListener { save() }
if (savedInstanceState == null) {
selectedFilter = defaultFilterProvider.startupFilter
selectedTheme = 7
} else {
selectedFilter = savedInstanceState.getParcelable(EXTRA_FILTER)
selectedTheme = savedInstanceState.getInt(EXTRA_THEME)
}
updateFilterAndTheme()
supportFragmentManager.setFilterPickerResultListener(this) {
if (selectedFilter != null && selectedFilter!!.listingTitle == getShortcutName()) {
shortcutName.text = null
}
selectedFilter = it
updateFilterAndTheme()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(EXTRA_FILTER, selectedFilter)
outState.putInt(EXTRA_THEME, selectedTheme)
}
private fun onListFocusChange(focused: Boolean) {
if (focused) {
shortcutList.clearFocus()
showListPicker()
}
}
private fun showListPicker() {
newFilterPicker(selectedFilter)
.show(supportFragmentManager, FRAG_TAG_FILTER_PICKER)
}
private fun showThemePicker() {
newColorPalette(null, 0, Palette.LAUNCHERS)
.show(supportFragmentManager, FRAG_TAG_COLOR_PICKER)
}
private fun updateFilterAndTheme() {
if (isNullOrEmpty(getShortcutName()) && selectedFilter != null) {
shortcutName.setText(selectedFilter!!.listingTitle)
}
if (selectedFilter != null) {
shortcutList.setText(selectedFilter!!.listingTitle)
}
updateTheme()
}
private fun updateTheme() {
clear.visibility = View.GONE
val color = ThemeColor.getLauncherColor(this, themeIndex)
DrawableUtil.setLeftDrawable(this, colorIcon, R.drawable.color_picker)
DrawableUtil.setTint(DrawableUtil.getLeftDrawable(colorIcon), color.primaryColor)
color.applyToNavigationBar(this)
}
private val themeIndex: Int
get() = if (selectedTheme >= 0 && selectedTheme < ThemeColor.LAUNCHER_COLORS.size) selectedTheme else 7
private fun getShortcutName(): String = shortcutName.text.toString().trim { it <= ' ' }
private fun save() {
val filterId = defaultFilterProvider.getFilterPreferenceValue(selectedFilter!!)
val shortcutIntent = TaskIntents.getTaskListByIdIntent(this, filterId)
val icon: Parcelable = ShortcutIconResource.fromContext(this, ThemeColor.ICONS[themeIndex])
val intent = Intent("com.android.launcher.action.INSTALL_SHORTCUT")
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent)
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getShortcutName())
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon)
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onColorPicked(index: Int) {
selectedTheme = index
updateTheme()
}
companion object {
private const val EXTRA_FILTER = "extra_filter"
private const val EXTRA_THEME = "extra_theme"
private const val FRAG_TAG_COLOR_PICKER = "frag_tag_color_picker"
private const val FRAG_TAG_FILTER_PICKER = "frag_tag_filter_picker"
}
} | gpl-3.0 | 4f74ec3f3f01b4741aa34d574faba3da | 38.418919 | 111 | 0.711298 | 4.804778 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/observer/LoadTimeObserver.kt | 1 | 2833 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.observer
import android.os.SystemClock
import androidx.fragment.app.Fragment
import android.util.Log
import mozilla.components.browser.session.Session
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.UrlUtils
object LoadTimeObserver {
private const val MIN_LOAD_TIME: Long = 40
private const val MAX_PROGRESS = 99
private const val LOG_TAG: String = "LoadTimeObserver"
@JvmStatic
fun addObservers(session: Session, fragment: Fragment) {
var startLoadTime: Long = 0
var urlLoading: String? = null
session.register(object : Session.Observer {
override fun onUrlChanged(session: Session, url: String) {
if ((urlLoading != null && urlLoading != url) || urlLoading == null) {
startLoadTime = SystemClock.elapsedRealtime()
Log.i(LOG_TAG, "zerdatime $startLoadTime - url changed to $url, new page load start")
urlLoading = url
}
}
override fun onLoadingStateChanged(session: Session, loading: Boolean) {
if (loading) {
if ((urlLoading != null && urlLoading != session.url) || urlLoading == null) {
urlLoading = session.url
startLoadTime = SystemClock.elapsedRealtime()
Log.i(LOG_TAG, "zerdatime $startLoadTime - page load start")
}
} else {
// Progress of 99 means the page completed loading and wasn't interrupted.
if (urlLoading != null &&
session.url == urlLoading &&
session.progress == MAX_PROGRESS) {
Log.i(LOG_TAG, "Loaded page at $session.url.value")
val endTime = SystemClock.elapsedRealtime()
Log.i(LOG_TAG, "zerdatime $endTime - page load stop")
val elapsedLoad = endTime - startLoadTime
Log.i(LOG_TAG, "$elapsedLoad - elapsed load")
// Even internal pages take longer than 40 ms to load, let's not send any loads faster than this
if (elapsedLoad > MIN_LOAD_TIME && !UrlUtils.isLocalizedContent(urlLoading)) {
Log.i(LOG_TAG, "Sent load to histogram")
TelemetryWrapper.addLoadToHistogram(session.url, elapsedLoad)
}
}
}
}
}, owner = fragment)
}
}
| mpl-2.0 | d30b927573228e730e8ac7285161d916 | 46.216667 | 120 | 0.563713 | 4.785473 | false | false | false | false |
googlecodelabs/kotlin-coroutines | ktx-library-codelab/step-06/myktxlibrary/src/main/java/com/example/android/myktxlibrary/LocationUtils.kt | 1 | 2898 | /*
* 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.example.android.myktxlibrary
import android.annotation.SuppressLint
import android.location.Location
import android.os.Looper
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
fun createLocationRequest() = LocationRequest.create().apply {
interval = 3000
fastestInterval = 2000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
fun Location.asString(format: Int = Location.FORMAT_DEGREES): String {
val latitude = Location.convert(latitude, format)
val longitude = Location.convert(longitude, format)
return "Location is: $latitude, $longitude"
}
@SuppressLint("MissingPermission")
suspend fun FusedLocationProviderClient.awaitLastLocation(): Location =
suspendCancellableCoroutine<Location> { continuation ->
lastLocation.addOnSuccessListener { location ->
continuation.resume(location)
}.addOnFailureListener { e ->
continuation.resumeWithException(e)
}
}
@SuppressLint("MissingPermission")
fun FusedLocationProviderClient.locationFlow() = callbackFlow<Location> {
val callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) {
result ?: return
for (location in result.locations) {
try {
offer(location) // emit location into the Flow using ProducerScope.offer
} catch (e: Exception) {
// nothing to do
// Channel was probably already closed by the time offer was called
}
}
}
}
requestLocationUpdates(
createLocationRequest(),
callback,
Looper.getMainLooper()
).addOnFailureListener { e ->
close(e) // in case of exception, close the Flow
}
awaitClose {
removeLocationUpdates(callback) // clean up when Flow collection ends
}
}
| apache-2.0 | 439e9b65d6505c0ee50f15b4733d30fd | 34.777778 | 92 | 0.71118 | 5.02253 | false | false | false | false |
coconautti/sequel | src/test/kotlin/coconautti/sql/UpdateSpec.kt | 1 | 1748 | package coconautti.sql
import io.kotlintest.matchers.shouldEqual
import io.kotlintest.specs.BehaviorSpec
class UpdateSpec : BehaviorSpec() {
init {
given("an update statement with two columns") {
val stmt = Database.update("users") {
set("firstName", "Peter")
set("age", 42)
}
`when`("extracting SQL") {
val sql = stmt.toString()
then("it should match expectation") {
sql.shouldEqual("UPDATE users SET firstName = ?, age = ?")
}
}
}
given("an update statement with two columns and where clause") {
val stmt = Database.update("users") {
set("firstName", "Peter")
set("age", 42)
where("email".eq("[email protected]"))
}
`when`("extracting SQL") {
val sql = stmt.toString()
then("it should match expectation") {
sql.shouldEqual("UPDATE users SET firstName = ?, age = ? WHERE email = ?")
}
}
}
given("an update statement with two columns and complex where clause") {
val stmt = Database.update("users") {
set("firstName", "Peter")
set("age", 42)
where(("email" eq "[email protected]") and ("lastName" eq "Piper" ))
}
`when`("extracting SQL") {
val sql = stmt.toString()
then("it should match expectation") {
sql.shouldEqual("UPDATE users SET firstName = ?, age = ? WHERE email = ? AND lastName = ?")
}
}
}
}
}
| apache-2.0 | e7ea9096da504753c7b1aa92af5fbc3b | 34.673469 | 111 | 0.478833 | 4.923944 | false | false | false | false |
Karumi/Shot | shot-consumer/app2/src/main/java/com/karumi/ui/view/SuperHeroDetailActivity.kt | 3 | 2347 | package com.karumi.ui.view
import android.app.Activity
import android.content.Intent
import androidx.appcompat.widget.Toolbar
import android.view.View
import com.github.salomonbrys.kodein.Kodein.Module
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.instance
import com.github.salomonbrys.kodein.provider
import com.karumi.R
import com.karumi.domain.model.SuperHero
import com.karumi.domain.usecase.GetSuperHeroByName
import com.karumi.ui.presenter.SuperHeroDetailPresenter
import com.karumi.ui.utils.setImageBackground
import kotlinx.android.synthetic.main.super_hero_detail_activity.*
class SuperHeroDetailActivity : BaseActivity(), SuperHeroDetailPresenter.View {
companion object {
private const val SUPER_HERO_NAME_KEY = "super_hero_name_key"
fun open(activity: Activity, superHeroName: String) {
val intent = Intent(activity, SuperHeroDetailActivity::class.java)
intent.putExtra(SUPER_HERO_NAME_KEY, superHeroName)
activity.startActivity(intent)
}
}
override val presenter: SuperHeroDetailPresenter by injector.instance()
override val layoutId: Int = R.layout.super_hero_detail_activity
override val toolbarView: Toolbar
get() = toolbar
override fun preparePresenter(intent: Intent?) {
val superHeroName = intent?.extras?.getString(SUPER_HERO_NAME_KEY)
title = superHeroName
presenter.preparePresenter(superHeroName)
}
override fun close() = finish()
override fun showLoading() {
progress_bar.visibility = View.VISIBLE
}
override fun hideLoading() {
progress_bar.visibility = View.GONE
}
override fun showSuperHero(superHero: SuperHero) {
tv_super_hero_name.text = superHero.name
tv_super_hero_description.text = superHero.description
iv_avengers_badge.visibility =
if (superHero.isAvenger) View.VISIBLE else View.GONE
iv_super_hero_photo.setImageBackground(superHero.photo)
}
override val activityModules = Module(allowSilentOverride = true) {
bind<SuperHeroDetailPresenter>() with provider {
SuperHeroDetailPresenter(this@SuperHeroDetailActivity, instance())
}
bind<GetSuperHeroByName>() with provider { GetSuperHeroByName(instance()) }
}
} | apache-2.0 | 8f218914338e38f1078873088c2ccab0 | 34.575758 | 83 | 0.727311 | 4.275046 | false | false | false | false |
kotlin-graphics/imgui | core/src/main/kotlin/imgui/internal/api/widgets.kt | 1 | 22926 | package imgui.internal.api
import glm_.func.common.max
import glm_.i
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.buttonBehavior
import imgui.ImGui.calcItemSize
import imgui.ImGui.calcTextSize
import imgui.ImGui.calcWrapWidthForPos
import imgui.ImGui.checkboxFlagsT
import imgui.ImGui.currentWindow
import imgui.ImGui.frameHeight
import imgui.ImGui.getColorU32
import imgui.ImGui.hoveredId
import imgui.ImGui.io
import imgui.ImGui.isClippedEx
import imgui.ImGui.isItemActive
import imgui.ImGui.isMouseDragging
import imgui.ImGui.itemAdd
import imgui.ImGui.itemSize
import imgui.ImGui.keepAliveID
import imgui.ImGui.logRenderedText
import imgui.ImGui.logRenderedTextNewLine
import imgui.ImGui.logText
import imgui.ImGui.popColumnsBackground
import imgui.ImGui.pushColumnsBackground
import imgui.ImGui.renderFrame
import imgui.ImGui.renderNavHighlight
import imgui.ImGui.renderText
import imgui.ImGui.renderTextClipped
import imgui.ImGui.renderTextWrapped
import imgui.ImGui.style
import imgui.api.g
import imgui.internal.*
import imgui.internal.classes.Rect
import imgui.internal.sections.*
import uno.kotlin.getValue
import uno.kotlin.setValue
import unsigned.Ulong
import kotlin.math.max
import kotlin.reflect.KMutableProperty0
/** Widgets */
internal interface widgets {
/** Raw text without formatting. Roughly equivalent to text("%s", text) but:
* A) doesn't require null terminated string if 'textEnd' is specified
* B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. */
fun textEx(text: String, textEnd: Int = -1, flag: TextFlag = TextFlag.None) {
val bytes = text.toByteArray()
textEx(bytes, if (textEnd != -1) textEnd else bytes.strlen())
}
/** Raw text without formatting. Roughly equivalent to text("%s", text) but:
* A) doesn't require null terminated string if 'textEnd' is specified
* B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. */
fun textEx(text: ByteArray, textEnd: Int = text.strlen(), flags: TextFlags = TextFlag.None.i) {
val window = currentWindow
if (window.skipItems) return
val textPos = Vec2(window.dc.cursorPos.x, window.dc.cursorPos.y + window.dc.currLineTextBaseOffset)
val wrapPosX = window.dc.textWrapPos
val wrapEnabled = wrapPosX >= 0f
if (textEnd > 2000 && !wrapEnabled) {
// Long text!
// Perform manual coarse clipping to optimize for long multi-line text
// - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
// - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
// - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
var line = 0
val lineHeight = ImGui.textLineHeight
val textSize = Vec2()
// Lines to skip (can't skip when logging text)
val pos = Vec2(textPos)
if (!g.logEnabled) {
val linesSkippable = ((window.clipRect.min.y - textPos.y) / lineHeight).i
if (linesSkippable > 0) {
var linesSkipped = 0
while (line < textEnd && linesSkipped < linesSkippable) {
var lineEnd = text.memchr(line, '\n', textEnd - line)
if (lineEnd == -1)
lineEnd = textEnd
if (flags hasnt TextFlag.NoWidthForLargeClippedText)
textSize.x = textSize.x max calcTextSize(text, line, lineEnd).x
line = lineEnd + 1
linesSkipped++
}
pos.y += linesSkipped * lineHeight
}
}
// Lines to render
if (line < textEnd) {
val lineRect = Rect(pos, pos + Vec2(Float.MAX_VALUE, lineHeight))
while (line < textEnd) {
if (isClippedEx(lineRect, 0, false))
break
var lineEnd = text.memchr(line, '\n', textEnd - line)
if (lineEnd == -1)
lineEnd = textEnd
textSize.x = textSize.x max calcTextSize(text, line, lineEnd).x
renderText(pos, text, line, lineEnd, false)
line = lineEnd + 1
lineRect.min.y += lineHeight
lineRect.max.y += lineHeight
pos.y += lineHeight
}
// Count remaining lines
var linesSkipped = 0
while (line < textEnd) {
var lineEnd = text.memchr(line, '\n', textEnd - line)
if (lineEnd == -1)
lineEnd = textEnd
if (flags hasnt TextFlag.NoWidthForLargeClippedText)
textSize.x = textSize.x max calcTextSize(text, line, lineEnd).x
line = lineEnd + 1
linesSkipped++
}
pos.y += linesSkipped * lineHeight
}
textSize.y = pos.y - textPos.y
val bb = Rect(textPos, textPos + textSize)
itemSize(textSize, 0f)
itemAdd(bb, 0)
} else {
val wrapWidth = if (wrapEnabled) calcWrapWidthForPos(window.dc.cursorPos, wrapPosX) else 0f
val textSize = calcTextSize(text, 0, textEnd, false, wrapWidth)
val bb = Rect(textPos, textPos + textSize)
itemSize(textSize, 0f)
if (!itemAdd(bb, 0)) return
// Render (we don't hide text after ## in this end-user function)
renderTextWrapped(bb.min, text, textEnd, wrapWidth)
}
}
fun String.memchr(startIdx: Int, c: Char): Int? {
val res = indexOf(c, startIdx)
return if (res >= 0) res else null
}
fun buttonEx(label: String, sizeArg: Vec2 = Vec2(), flags_: Int = 0): Boolean {
val window = currentWindow
if (window.skipItems) return false
val id = window.getID(label)
val labelSize = calcTextSize(label, hideTextAfterDoubleHash = true)
val pos = Vec2(window.dc.cursorPos)
/* Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky,
since it shouldn't be a flag) */
if (flags_ has ButtonFlag.AlignTextBaseLine && style.framePadding.y < window.dc.currLineTextBaseOffset)
pos.y += window.dc.currLineTextBaseOffset - style.framePadding.y
val size = calcItemSize(sizeArg, labelSize.x + style.framePadding.x * 2f, labelSize.y + style.framePadding.y * 2f)
val bb = Rect(pos, pos + size)
itemSize(size, style.framePadding.y)
if (!itemAdd(bb, id)) return false
var flags = flags_
if (window.dc.itemFlags has ItemFlag.ButtonRepeat) flags = flags or ButtonFlag.Repeat
val (pressed, hovered, held) = buttonBehavior(bb, id, flags)
// Render
val col = if (hovered && held) Col.ButtonActive else if (hovered) Col.ButtonHovered else Col.Button
renderNavHighlight(bb, id)
renderFrame(bb.min, bb.max, col.u32, true, style.frameRounding)
val renderTextPos = Rect(bb.min + style.framePadding, bb.max - style.framePadding);
if (g.logEnabled)
logRenderedText(renderTextPos.min, "[")
renderTextClipped(renderTextPos.min, renderTextPos.max, label, labelSize, style.buttonTextAlign, bb)
if (g.logEnabled)
logRenderedText(renderTextPos.min, "]")
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window.dc.lastItemStatusFlags)
return pressed
}
/* Button to close a window */
fun closeButton(id: ID, pos: Vec2): Boolean {
val window = currentWindow
/* We intentionally allow interaction when clipped so that a mechanical Alt, Right, Validate sequence close
a window. (this isn't the regular behavior of buttons, but it doesn't affect the user much because
navigation tends to keep items visible). */
val bb = Rect(pos, pos + g.fontSize + style.framePadding * 2f)
val isClipped = !itemAdd(bb, id)
val (pressed, hovered, held) = buttonBehavior(bb, id)
if (isClipped) return pressed
// Render
val center = Vec2(bb.center)
if (hovered) {
val col = if (held) Col.ButtonActive else Col.ButtonHovered
window.drawList.addCircleFilled(center, 2f max (g.fontSize * 0.5f + 1f), col.u32, 12)
}
val crossExtent = g.fontSize * 0.5f * 0.7071f - 1f
val crossCol = Col.Text.u32
center -= 0.5f
window.drawList.addLine(center + crossExtent, center - crossExtent, crossCol, 1f)
window.drawList.addLine(center + Vec2(crossExtent, -crossExtent), center + Vec2(-crossExtent, crossExtent), crossCol, 1f)
return pressed
}
fun collapseButton(id: ID, pos: Vec2): Boolean {
val window = g.currentWindow!!
val bb = Rect(pos, pos + g.fontSize + style.framePadding * 2f)
itemAdd(bb, id)
val (pressed, hovered, held) = buttonBehavior(bb, id, ButtonFlag.None)
// Render
val bgCol = if (held && hovered) Col.ButtonActive else if (hovered) Col.ButtonHovered else Col.Button
val textCol = Col.Text
val center = bb.center
if (hovered || held)
window.drawList.addCircleFilled(center/* + Vec2(0.0f, -0.5f)*/, g.fontSize * 0.5f + 1f, bgCol.u32, 12)
window.drawList.renderArrow(bb.min + style.framePadding, textCol.u32, if (window.collapsed) Dir.Right else Dir.Down, 1f)
// Switch to moving the window after mouse is moved beyond the initial drag threshold
if (isItemActive && isMouseDragging(MouseButton.Left))
window.startMouseMoving()
return pressed
}
/** square button with an arrow shape */
fun arrowButtonEx(strId: String, dir: Dir, size: Vec2, flags_: ButtonFlags = ButtonFlag.None.i): Boolean {
var flags = flags_
val window = currentWindow
if (window.skipItems) return false
val id = window.getID(strId)
val bb = Rect(window.dc.cursorPos, window.dc.cursorPos + size)
val defaultSize = frameHeight
itemSize(size, if (size.y >= defaultSize) style.framePadding.y else -1f)
if (!itemAdd(bb, id)) return false
if (window.dc.itemFlags has ItemFlag.ButtonRepeat)
flags = flags or ButtonFlag.Repeat
val (pressed, hovered, held) = buttonBehavior(bb, id, flags)
// Render
val bgCol = if (held && hovered) Col.ButtonActive else if (hovered) Col.ButtonHovered else Col.Button
val textCol = Col.Text
renderNavHighlight(bb, id)
renderFrame(bb.min, bb.max, bgCol.u32, true, g.style.frameRounding)
window.drawList.renderArrow(bb.min + Vec2(max(0f, (size.x - g.fontSize) * 0.5f), max(0f, (size.y - g.fontSize) * 0.5f)), textCol.u32, dir)
return pressed
}
/** Vertical scrollbar
* The entire piece of code below is rather confusing because:
* - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when
* clicking inside the grab)
* - We store values as normalized ratio and in a form that allows the window content to change while we are holding on
* a scrollbar
* - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. */
infix fun scrollbar(axis: Axis) {
val window = g.currentWindow!!
val id = window getScrollbarID axis
keepAliveID(id)
// Calculate scrollbar bounding box
val bb = window getScrollbarRect axis
var roundingCorners = DrawCornerFlag.None.i
if (axis == Axis.X) {
roundingCorners = roundingCorners or DrawCornerFlag.BotLeft
if (!window.scrollbar.y)
roundingCorners = roundingCorners or DrawCornerFlag.BotRight
} else {
if (window.flags has WindowFlag.NoTitleBar && window.flags hasnt WindowFlag.MenuBar)
roundingCorners = roundingCorners or DrawCornerFlag.TopRight
if (!window.scrollbar.x)
roundingCorners = roundingCorners or DrawCornerFlag.BotRight
}
val sizeAvail = window.innerRect.max[axis] - window.innerRect.min[axis]
val sizeContents = window.contentSize[axis] + window.windowPadding[axis] * 2f
scrollbarEx(bb, id, axis, if (axis == Axis.X) window.scroll::x else window.scroll::y, sizeAvail, sizeContents, roundingCorners)
}
/** Vertical/Horizontal scrollbar
* The entire piece of code below is rather confusing because:
* - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
* - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
* - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
* Still, the code should probably be made simpler.. */
fun scrollbarEx(bbFrame: Rect, id: ID, axis: Axis, pScrollV: KMutableProperty0<Float>, sizeAvailV: Float, sizeContentsV: Float, roundingCorners: DrawCornerFlags): Boolean {
var scrollV by pScrollV
val window = g.currentWindow!!
if (window.skipItems)
return false
val bbFrameWidth = bbFrame.width
val bbFrameHeight = bbFrame.height
if (bbFrameWidth <= 0f || bbFrameHeight <= 0f)
return false
// When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab)
var alpha = 1f
if (axis == Axis.Y && bbFrameHeight < g.fontSize + style.framePadding.y * 2f)
alpha = saturate((bbFrameHeight - g.fontSize) / (style.framePadding.y * 2f))
if (alpha <= 0f)
return false
val allowInteraction = alpha >= 1f
val bb = Rect(bbFrame)
bb.expand(Vec2(-clamp(floor((bbFrameWidth - 2f) * 0.5f), 0f, 3f), -clamp(floor((bbFrameHeight - 2f) * 0.5f), 0f, 3f)))
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
val scrollbarSizeV = if (axis == Axis.X) bb.width else bb.height
// Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
assert(max(sizeContentsV, sizeAvailV) > 0f) { "Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers." }
val winSizeV = max(sizeContentsV max sizeAvailV, 1f)
val grabHPixels = clamp(scrollbarSizeV * (sizeAvailV / winSizeV), style.grabMinSize, scrollbarSizeV)
val grabHNorm = grabHPixels / scrollbarSizeV
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
val (_, hovered, held) = buttonBehavior(bb, id, ButtonFlag.NoNavFocus)
val scrollMax = max(1f, sizeContentsV - sizeAvailV)
var scrollRatio = saturate(scrollV / scrollMax)
var grabVNorm = scrollRatio * (scrollbarSizeV - grabHPixels) / scrollbarSizeV // Grab position in normalized space
if (held && allowInteraction && grabHNorm < 1f) {
val scrollbarPosV = bb.min[axis]
val mousePosV = io.mousePos[axis]
// Click position in scrollbar normalized space (0.0f->1.0f)
val clickedVNorm = saturate((mousePosV - scrollbarPosV) / scrollbarSizeV)
hoveredId = id
var seekAbsolute = false
if (g.activeIdIsJustActivated) {
// On initial click calculate the distance between mouse and the center of the grab
seekAbsolute = (clickedVNorm < grabVNorm || clickedVNorm > grabVNorm + grabHNorm)
g.scrollbarClickDeltaToGrabCenter = when {
seekAbsolute -> 0f
else -> clickedVNorm - grabVNorm - grabHNorm * 0.5f
}
}
// Apply scroll (p_scroll_v will generally point on one member of window->Scroll)
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position
val scrollVNorm = saturate((clickedVNorm - g.scrollbarClickDeltaToGrabCenter - grabHNorm * 0.5f) / (1f - grabHNorm))
scrollV = round(scrollVNorm * scrollMax) //(win_size_contents_v - win_size_v));
// Update values for rendering
scrollRatio = saturate(scrollV / scrollMax)
grabVNorm = scrollRatio * (scrollbarSizeV - grabHPixels) / scrollbarSizeV
// Update distance to grab now that we have seeked and saturated
if (seekAbsolute)
g.scrollbarClickDeltaToGrabCenter = clickedVNorm - grabVNorm - grabHNorm * 0.5f
}
// Render
val bgCol = Col.ScrollbarBg.u32
val grabCol = getColorU32(when {
held -> Col.ScrollbarGrabActive
hovered -> Col.ScrollbarGrabHovered
else -> Col.ScrollbarGrab
}, alpha)
window.drawList.addRectFilled(bbFrame.min, bbFrame.max, bgCol, window.windowRounding, roundingCorners)
val grabRect = when (axis) {
Axis.X -> Rect(lerp(bb.min.x, bb.max.x, grabVNorm), bb.min.y, lerp(bb.min.x, bb.max.x, grabVNorm) + grabHPixels, bb.max.y)
else -> Rect(bb.min.x, lerp(bb.min.y, bb.max.y, grabVNorm), bb.max.x, lerp(bb.min.y, bb.max.y, grabVNorm) + grabHPixels)
}
window.drawList.addRectFilled(grabRect.min, grabRect.max, grabCol, style.scrollbarRounding)
return held
}
/** ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390)
* We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API. */
fun imageButtonEx(
id: ID, textureId: TextureID, size: Vec2, uv0: Vec2, uv1: Vec2, padding: Vec2, bgCol: Vec4, tintCol: Vec4,
): Boolean {
val window = currentWindow
if (window.skipItems)
return false
val bb = Rect(window.dc.cursorPos, window.dc.cursorPos + size + padding * 2)
itemSize(bb)
if (!itemAdd(bb, id))
return false
val (pressed, hovered, held) = buttonBehavior(bb, id)
// Render
val col = getColorU32(if(held && hovered) Col.ButtonActive else if(hovered) Col.ButtonHovered else Col.Button)
renderNavHighlight(bb, id)
renderFrame(bb.min, bb.max, col, true, clamp(min(padding.x, padding.y), 0f, style.frameRounding))
if (bgCol.w > 0f)
window.drawList.addRectFilled(bb.min + padding, bb.max - padding, bgCol.u32)
window.drawList.addImage(textureId, bb.min + padding, bb.max - padding, uv0, uv1, tintCol.u32)
return pressed
}
// GetWindowScrollbarRect -> Window class
// GetWindowScrollbarID -> Window class
/** Horizontal/vertical separating line
* Separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. */
fun separatorEx(flags: SeparatorFlags) {
val window = currentWindow
if (window.skipItems) return
assert((flags and (SeparatorFlag.Horizontal or SeparatorFlag.Vertical)).isPowerOfTwo) { "Check that only 1 option is selected" }
val thicknessDraw = 1f
val thicknessLayout = 0f
if (flags has SeparatorFlag.Vertical) {
// Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout.
val y1 = window.dc.cursorPos.y
val y2 = window.dc.cursorPos.y + window.dc.currLineSize.y
val bb = Rect(Vec2(window.dc.cursorPos.x, y1), Vec2(window.dc.cursorPos.x + thicknessDraw, y2))
itemSize(Vec2(thicknessLayout, 0f))
if (!itemAdd(bb, 0))
return
// Draw
window.drawList.addLine(Vec2(bb.min.x, bb.min.y), Vec2(bb.min.x, bb.max.y), Col.Separator.u32)
if (g.logEnabled)
logText(" |")
} else if (flags has SeparatorFlag.Horizontal) {
// Horizontal Separator
var x1 = window.pos.x
val x2 = window.pos.x + window.size.x
// FIXME-WORKRECT: old hack (#205) until we decide of consistent behavior with WorkRect/Indent and Separator
if (g.groupStack.isNotEmpty() && g.groupStack.last().windowID == window.id)
x1 += window.dc.indent
val columns = window.dc.currentColumns.takeIf { flags has SeparatorFlag.SpanAllColumns }
if (columns != null)
pushColumnsBackground()
// We don't provide our width to the layout so that it doesn't get feed back into AutoFit
val bb = Rect(Vec2(x1, window.dc.cursorPos.y), Vec2(x2, window.dc.cursorPos.y + thicknessDraw))
itemSize(Vec2(0f, thicknessLayout))
val itemVisible = itemAdd(bb, 0)
if (itemVisible) {
// Draw
window.drawList.addLine(bb.min, Vec2(bb.max.x, bb.min.y), Col.Separator.u32)
if (g.logEnabled) {
logRenderedText(bb.min, "--------------------------------")
logRenderedTextNewLine() // Separator isn't tall enough to trigger a new line automatically in LogRenderText
}
}
columns?.let {
popColumnsBackground()
it.lineMinY = window.dc.cursorPos.y
}
}
}
fun checkboxFlags(label: String, flags: KMutableProperty0<Long>, flagsValue: Long): Boolean =
checkboxFlagsT(label, flags, flagsValue)
fun checkboxFlags(label: String, flags: KMutableProperty0<Ulong>, flagsValue: Ulong): Boolean =
checkboxFlagsT(label, flags, flagsValue)
} | mit | 4d18a24ebc2e82c49d9f87c32c70827a | 45.599593 | 176 | 0.629242 | 4.152509 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/onthisday/OnThisDayPagesViewHolder.kt | 1 | 5450 | package org.wikipedia.feed.onthisday
import android.app.Activity
import android.app.ActivityOptions
import android.net.Uri
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.PageActivity
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.readinglist.LongPressMenu
import org.wikipedia.readinglist.MoveToReadingListDialog
import org.wikipedia.readinglist.ReadingListBehaviorsUtil
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.util.*
import org.wikipedia.views.FaceAndColorDetectImageView
class OnThisDayPagesViewHolder(
private val activity: Activity,
private val fragmentManager: FragmentManager,
v: View,
private val wiki: WikiSite
) : RecyclerView.ViewHolder(v) {
private val imageContainer: FrameLayout
private val image: FaceAndColorDetectImageView
private var selectedPage: PageSummary? = null
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
init {
DeviceUtil.setContextClickAsLongClick(v)
this.itemView.setOnClickListener { onBaseViewClicked() }
this.itemView.setOnLongClickListener { showOverflowMenu(it) }
imageContainer = this.itemView.findViewById(R.id.image_container)
image = this.itemView.findViewById(R.id.image)
}
fun setFields(page: PageSummary) {
val description = this.itemView.findViewById<TextView>(R.id.description)
val title = this.itemView.findViewById<TextView>(R.id.title)
selectedPage = page
description.text = page.description
description.visibility = if (page.description.isNullOrEmpty()) View.GONE else View.VISIBLE
title.maxLines = if (page.description.isNullOrEmpty()) 2 else 1
title.text = StringUtil.fromHtml(page.displayTitle)
setImage(page.thumbnailUrl)
}
private fun setImage(url: String?) {
if (url.isNullOrEmpty()) {
imageContainer.visibility = View.GONE
} else {
imageContainer.visibility = View.VISIBLE
image.loadImage(Uri.parse(url))
}
}
private fun onBaseViewClicked() {
val entry = HistoryEntry(
selectedPage!!.getPageTitle(wiki),
HistoryEntry.SOURCE_ON_THIS_DAY_ACTIVITY
)
val sharedElements = TransitionUtil.getSharedElements(activity, image)
val options = ActivityOptions.makeSceneTransitionAnimation(activity, *sharedElements)
val intent = PageActivity.newIntentForNewTab(activity, entry, entry.title)
if (sharedElements.isNotEmpty()) {
intent.putExtra(Constants.INTENT_EXTRA_HAS_TRANSITION_ANIM, true)
}
activity.startActivity(
intent,
if (DimenUtil.isLandscape(activity) || sharedElements.isEmpty()) null else options.toBundle()
)
}
private fun showOverflowMenu(anchorView: View?): Boolean {
val entry = HistoryEntry(
selectedPage!!.getPageTitle(wiki),
HistoryEntry.SOURCE_ON_THIS_DAY_ACTIVITY
)
LongPressMenu(anchorView!!, true, object : LongPressMenu.Callback {
override fun onOpenLink(entry: HistoryEntry) {
PageActivity.newIntentForNewTab(activity, entry, entry.title)
}
override fun onOpenInNewTab(entry: HistoryEntry) {
TabUtil.openInNewBackgroundTab(entry)
FeedbackUtil.showMessage(activity, R.string.article_opened_in_background_tab)
}
override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) {
if (addToDefault) {
ReadingListBehaviorsUtil.addToDefaultList(
activity, entry.title, InvokeSource.NEWS_ACTIVITY
) { readingListId ->
bottomSheetPresenter.show(
fragmentManager,
MoveToReadingListDialog.newInstance(
readingListId,
entry.title,
InvokeSource.ON_THIS_DAY_ACTIVITY
)
)
}
} else {
bottomSheetPresenter.show(
fragmentManager,
AddToReadingListDialog.newInstance(
entry.title,
InvokeSource.ON_THIS_DAY_ACTIVITY
)
)
}
}
override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) {
bottomSheetPresenter.show(
fragmentManager,
MoveToReadingListDialog.newInstance(
page!!.listId,
entry.title,
InvokeSource.ON_THIS_DAY_ACTIVITY
)
)
}
}).show(entry)
return true
}
}
| apache-2.0 | 6a8eca1b2be83a78b5cbd7714e3d6598 | 38.208633 | 105 | 0.633761 | 5.417495 | false | false | false | false |
AlexLandau/semlang | kotlin/semlang-transforms/src/main/kotlin/simplifyExpressions.kt | 1 | 11972 | package net.semlang.transforms
import net.semlang.api.*
import net.semlang.api.Function
typealias ExpressionPredicate = (Expression) -> Boolean
// TODO: Better document
fun simplifyAllExpressions(context: RawContext): RawContext {
return ExpressionHoister(context, {true}).apply()
}
fun hoistMatchingExpressions(context: RawContext, shouldHoist: ExpressionPredicate): RawContext {
return ExpressionHoister(context, shouldHoist).apply()
}
private class ExpressionHoister(val originalContext: RawContext, val shouldHoist: ExpressionPredicate) {
fun apply(): RawContext {
val functions = originalContext.functions.map(this::simplifyFunctionExpressions)
val structs = originalContext.structs.map(this::applyToRequiresBlock)
val unions = originalContext.unions
return RawContext(functions, structs, unions)
}
private fun applyToRequiresBlock(oldStruct: UnvalidatedStruct): UnvalidatedStruct {
val requires = oldStruct.requires
return oldStruct.copy(requires = if (requires == null) {
null
} else {
hoistExpressionsInBlock(requires, oldStruct.members.map(UnvalidatedMember::name), shouldHoist)
})
}
private fun simplifyFunctionExpressions(function: Function): Function {
val varsInScope = function.arguments.map(UnvalidatedArgument::name)
val newBlock = hoistExpressionsInBlock(function.block, varsInScope, shouldHoist)
return Function(function.id, function.typeParameters, function.arguments, function.returnType, newBlock, function.annotations)
}
}
private fun hoistExpressionsInBlock(block: Block, varsAlreadyInScope: Collection<String>, shouldHoist: ExpressionPredicate): Block {
return ExpressionsInBlockHoister(block, varsAlreadyInScope, shouldHoist).apply()
}
private class ExpressionsInBlockHoister(val block: Block, varsAlreadyInScope: Collection<String>, val shouldHoist: ExpressionPredicate) {
val varNamesInScope = HashSet<String>(varsAlreadyInScope)
val varNamesToPreserve = HashSet<String>(varsAlreadyInScope + getAllDeclaredVarNames(block))
val newStatements = ArrayList<Statement>()
fun apply(): Block {
for (statement in block.statements.dropLast(1)) {
val unused = when (statement) {
is Statement.Assignment -> {
val splitResult = trySplitting(statement.expression)
newStatements.add(Statement.Assignment(statement.name, statement.type, splitResult))
}
is Statement.Bare -> {
val splitResult = trySplitting(statement.expression)
newStatements.add(Statement.Bare(splitResult))
}
}
}
val newLastStatement = when (val statement = block.statements.last()) {
is Statement.Assignment -> {
// This is probably an error case
val splitResult = trySplitting(statement.expression)
Statement.Assignment(statement.name, statement.type, splitResult)
}
is Statement.Bare -> {
val expression = tryMakingIntoVar(statement.expression)
Statement.Bare(expression)
}
}
return Block(newStatements + newLastStatement)
}
/**
* Returns an expression of the same expression type, with this transformation applied. As a side effect, adds any
* additional needed assignments to [newStatements].
*
* Note that expressions containing blocks (namely if-then expressions) will have their blocks simplified, but will
* not have their contents flattened (i.e. moved outside of the blocks).
*/
private fun trySplitting(expression: Expression): Expression {
return when (expression) {
is Expression.Variable -> {
expression
}
is Expression.Literal -> {
expression
}
is Expression.ListLiteral -> {
val newContents = expression.contents.map { item ->
val result = tryMakingIntoVar(item)
result
}
Expression.ListLiteral(newContents, expression.chosenParameter)
}
is Expression.Follow -> {
val result = tryMakingIntoVar(expression.structureExpression)
Expression.Follow(result, expression.name)
}
is Expression.IfThen -> {
val conditionResult = tryMakingIntoVar(expression.condition)
val simplifiedThenBlock = hoistExpressionsInBlock(expression.thenBlock, varNamesInScope, shouldHoist)
val simplifiedElseBlock = hoistExpressionsInBlock(expression.elseBlock, varNamesInScope, shouldHoist)
Expression.IfThen(
conditionResult,
simplifiedThenBlock,
simplifiedElseBlock)
}
is Expression.ExpressionFunctionCall -> {
val newArguments = expression.arguments.map { argument ->
val result = tryMakingIntoVar(argument)
result
}
val result = tryMakingIntoVar(expression.functionExpression)
Expression.ExpressionFunctionCall(result, newArguments, expression.chosenParameters)
}
is Expression.NamedFunctionCall -> {
val newArguments = expression.arguments.map { argument ->
val result = tryMakingIntoVar(argument)
result
}
Expression.NamedFunctionCall(expression.functionRef, newArguments, expression.chosenParameters)
}
is Expression.ExpressionFunctionBinding -> {
val newBindings = expression.bindings.map { binding ->
if (binding == null) {
null
} else {
val result = tryMakingIntoVar(binding)
result
}
}
val result = tryMakingIntoVar(expression.functionExpression)
Expression.ExpressionFunctionBinding(result, newBindings, expression.chosenParameters)
}
is Expression.NamedFunctionBinding -> {
val newBindings = expression.bindings.map { binding ->
if (binding == null) {
null
} else {
val result = tryMakingIntoVar(binding)
result
}
}
Expression.NamedFunctionBinding(expression.functionRef, newBindings, expression.chosenParameters)
}
is Expression.InlineFunction -> {
val block = hoistExpressionsInBlock(expression.block, varNamesInScope, shouldHoist)
Expression.InlineFunction(expression.arguments, expression.returnType, block)
}
}
}
/**
* Returns a transformed version of the expression or a variable. This transformation will also be applied to any
* components of the expression. As a side effect, adds any additional assignments needed to define any newly
* required variables to [newStatements]. The assignments will give the new expression the same value as the given
* expression.
*/
private fun tryMakingIntoVar(expression: Expression): Expression {
if (expression is Expression.Variable) {
return expression
}
val expressionWithNewContents = when (expression) {
is Expression.Variable -> {
error("This case should already have been handled")
}
is Expression.Follow -> {
val subresult = tryMakingIntoVar(expression.structureExpression)
Expression.Follow(subresult, expression.name)
}
is Expression.Literal -> {
expression
}
is Expression.ListLiteral -> {
val newContents = expression.contents.map { item ->
val subresult = tryMakingIntoVar(item)
subresult
}
Expression.ListLiteral(newContents, expression.chosenParameter)
}
is Expression.IfThen -> {
val subresult = tryMakingIntoVar(expression.condition)
val simplifiedThenBlock = hoistExpressionsInBlock(expression.thenBlock, varNamesInScope, shouldHoist)
val simplifiedElseBlock = hoistExpressionsInBlock(expression.elseBlock, varNamesInScope, shouldHoist)
Expression.IfThen(
subresult,
simplifiedThenBlock,
simplifiedElseBlock)
}
is Expression.ExpressionFunctionCall -> {
val newArguments = expression.arguments.map { argument ->
val subresult = tryMakingIntoVar(argument)
subresult
}
val subresult = tryMakingIntoVar(expression.functionExpression)
Expression.ExpressionFunctionCall(subresult, newArguments, expression.chosenParameters)
}
is Expression.NamedFunctionCall -> {
val newArguments = expression.arguments.map { argument ->
val subresult = tryMakingIntoVar(argument)
subresult
}
Expression.NamedFunctionCall(expression.functionRef, newArguments, expression.chosenParameters)
}
is Expression.ExpressionFunctionBinding -> {
val newBindings = expression.bindings.map { binding ->
if (binding == null) {
null
} else {
val subresult = tryMakingIntoVar(binding)
subresult
}
}
val subresult = tryMakingIntoVar(expression.functionExpression)
Expression.ExpressionFunctionBinding(subresult, newBindings, expression.chosenParameters)
}
is Expression.NamedFunctionBinding -> {
val newBindings = expression.bindings.map { binding ->
if (binding == null) {
null
} else {
val subresult = tryMakingIntoVar(binding)
subresult
}
}
Expression.NamedFunctionBinding(expression.functionRef, newBindings, expression.chosenParameters)
}
is Expression.InlineFunction -> {
val block = hoistExpressionsInBlock(expression.block, varNamesInScope, shouldHoist)
Expression.InlineFunction(expression.arguments, expression.returnType, block)
}
}
return if (shouldHoist(expressionWithNewContents)) {
val replacementName = createAndRecordNewVarName()
newStatements.add(Statement.Assignment(replacementName, null, expressionWithNewContents))
Expression.Variable(replacementName)
} else {
expressionWithNewContents
}
}
private fun createAndRecordNewVarName(): String {
val replacementName = getNewVarName()
varNamesToPreserve.add(replacementName)
varNamesInScope.add(replacementName)
return replacementName
}
// TODO: Use better approaches than this to come up with names
private fun getNewVarName(): String {
var i = 1
while (true) {
val name = "temp_" + i
if (!varNamesToPreserve.contains(name)) {
return name
}
i++
}
}
}
| apache-2.0 | 083e63a2a408d444c0429bc4a36ee4da | 40.86014 | 137 | 0.597895 | 5.641847 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/commands/DropCommands.kt | 1 | 11542 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 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.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandCompletion
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Conditions
import co.aikar.commands.annotation.Default
import co.aikar.commands.annotation.Dependency
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.Split
import co.aikar.commands.annotation.Subcommand
import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItem
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGenerationReason
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGem
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier
import com.tealcube.minecraft.bukkit.mythicdrops.identification.IdentityTome
import com.tealcube.minecraft.bukkit.mythicdrops.identification.UnidentifiedItem
import com.tealcube.minecraft.bukkit.mythicdrops.items.builders.MythicDropBuilder
import com.tealcube.minecraft.bukkit.mythicdrops.sendMythicMessage
import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketExtender
import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketItem
import com.tealcube.minecraft.bukkit.mythicdrops.utils.GemUtil
import io.pixeloutlaw.minecraft.spigot.bandsaw.JulLoggerFactory
import io.pixeloutlaw.minecraft.spigot.mythicdrops.getMaterials
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.command.CommandSender
@CommandAlias("mythicdrops|md")
class DropCommands : BaseCommand() {
companion object {
private val logger = JulLoggerFactory.getLogger(DropCommands::class)
}
@Subcommand("drop")
class NestedDropCommands(parent: BaseCommand) : BaseCommand() {
@field:Dependency
lateinit var mythicDrops: MythicDrops
@Subcommand("custom")
@CommandCompletion("@customItems @worlds * * * *")
@Description("Spawns a tiered item in the player's inventory. Use \"*\" to drop any custom item.")
@CommandPermission("mythicdrops.command.drop.custom")
fun dropCustomItemCommand(
sender: CommandSender,
customItem: CustomItem?,
world: World,
@Default("0") x: Int,
@Default("0") y: Int,
@Default("0") z: Int,
@Conditions("limits:min=0") @Default("1") amount: Int
) {
var amountGiven = 0
repeat(amount) {
val itemStack =
customItem?.toItemStack(mythicDrops.customEnchantmentRegistry)
?: mythicDrops.customItemManager.randomByWeight()
?.toItemStack(mythicDrops.customEnchantmentRegistry)
if (itemStack != null) {
world.dropItem(Location(world, x.toDouble(), y.toDouble(), z.toDouble()), itemStack)
amountGiven++
}
}
sender.sendMythicMessage(
mythicDrops.settingsManager.languageSettings.command.dropCustom.success,
"%amount%" to amountGiven.toString()
)
}
@Subcommand("extender")
@CommandCompletion("@worlds * * * *")
@Description("Spawns a Socket Extender in the player's inventory.")
@CommandPermission("mythicdrops.command.drop.extender")
fun dropSocketExtenderCommand(
sender: CommandSender,
world: World,
@Default("0") x: Int,
@Default("0") y: Int,
@Default("0") z: Int,
@Conditions("limits:min=0") @Default("1") amount: Int
) {
var amountGiven = 0
repeat(amount) {
mythicDrops.settingsManager.socketingSettings.options.socketExtenderMaterialIds.randomOrNull()?.let {
val socketExtender =
SocketExtender(it, mythicDrops.settingsManager.socketingSettings.items.socketExtender)
world.dropItem(Location(world, x.toDouble(), y.toDouble(), z.toDouble()), socketExtender)
amountGiven++
}
}
sender.sendMythicMessage(
mythicDrops.settingsManager.languageSettings.command.dropExtender.success,
"%amount%" to amountGiven.toString()
)
}
@Subcommand("gem")
@CommandCompletion("@socketGems @worlds * * * *")
@Description("Spawns a Socket Gem in the player's inventory. Use \"*\" to drop any Socket Gem.")
@CommandPermission("mythicdrops.command.drop.gem")
fun dropSocketGemCommand(
sender: CommandSender,
socketGem: SocketGem?,
world: World,
@Default("0") x: Int,
@Default("0") y: Int,
@Default("0") z: Int,
@Conditions("limits:min=0") @Default("1") amount: Int
) {
var amountGiven = 0
repeat(amount) {
val chosenSocketGem = socketGem ?: mythicDrops.socketGemManager.randomByWeight() ?: return@repeat
GemUtil.getRandomSocketGemMaterial()?.let {
val itemStack = SocketItem(
it,
chosenSocketGem,
mythicDrops.settingsManager.socketingSettings.items.socketGem
)
world.dropItem(Location(world, x.toDouble(), y.toDouble(), z.toDouble()), itemStack)
amountGiven++
}
}
sender.sendMythicMessage(
mythicDrops.settingsManager.languageSettings.command.dropGem.success,
"%amount%" to amountGiven.toString()
)
}
@Subcommand("tier")
@CommandCompletion("@tiers @worlds * * * *")
@Description("Spawns a tiered item in the player's inventory. Use \"*\" to drop any tier.")
@CommandPermission("mythicdrops.command.drop.tier")
fun dropTierCommand(
sender: CommandSender,
tier: Tier?,
world: World,
@Default("0") x: Int,
@Default("0") y: Int,
@Default("0") z: Int,
@Conditions("limits:min=0") @Default("1") amount: Int
) {
var amountGiven = 0
val dropBuilder = MythicDropBuilder(mythicDrops)
repeat(amount) {
val chosenTier = tier ?: mythicDrops.tierManager.randomByWeight() ?: return@repeat
val itemStack = dropBuilder.withItemGenerationReason(ItemGenerationReason.COMMAND)
.withTier(chosenTier).build()
if (itemStack != null) {
world.dropItem(Location(world, x.toDouble(), y.toDouble(), z.toDouble()), itemStack)
amountGiven++
}
}
sender.sendMythicMessage(
mythicDrops.settingsManager.languageSettings.command.dropRandom.success,
"%amount%" to amountGiven.toString()
)
}
@Subcommand("tome")
@CommandCompletion("@worlds * * * *")
@Description("Spawns an Identity Tome in the player's inventory.")
@CommandPermission("mythicdrops.command.drop.tome")
fun dropIdentityTomeCommand(
sender: CommandSender,
world: World,
@Default("0") x: Int,
@Default("0") y: Int,
@Default("0") z: Int,
@Conditions("limits:min=0") @Default("1") amount: Int
) {
var amountGiven = 0
repeat(amount) {
val itemStack = IdentityTome(mythicDrops.settingsManager.identifyingSettings.items.identityTome)
world.dropItem(Location(world, x.toDouble(), y.toDouble(), z.toDouble()), itemStack)
amountGiven++
}
sender.sendMythicMessage(
mythicDrops.settingsManager.languageSettings.command.dropTome.success,
"%amount%" to amountGiven.toString()
)
}
@Subcommand("unidentified")
@Description("Spawns an Unidentified Item in the player's inventory.")
@CommandCompletion("@worlds * * * * *")
@CommandPermission("mythicdrops.command.drop.unidentified")
fun dropUnidentifiedItem(
sender: CommandSender,
world: World,
@Default("0") x: Int,
@Default("0") y: Int,
@Default("0") z: Int,
@Conditions("limits:min=0") @Default("1") amount: Int,
@Default("") @Split(",") allowableTiers: Array<String>
) {
val allowableTierList = allowableTiers.mapNotNull { mythicDrops.tierManager.getByName(it) }
var amountGiven = 0
repeat(amount) {
val randomAllowableTier = if (allowableTierList.isEmpty()) {
null
} else {
allowableTierList.random()
}
val randomTierFromManager = mythicDrops.tierManager.randomByWeight()
val tier = randomAllowableTier ?: randomTierFromManager
// intentionally not folded for readability
if (tier == null) {
return@repeat
}
val materials = tier.getMaterials()
if (materials.isEmpty()) {
return@repeat
}
val material = materials.random()
val itemStack =
UnidentifiedItem(
material,
mythicDrops.settingsManager.identifyingSettings.items.unidentifiedItem,
mythicDrops.settingsManager.languageSettings.displayNames,
allowableTierList
)
world.dropItem(Location(world, x.toDouble(), y.toDouble(), z.toDouble()), itemStack)
amountGiven += 1
}
sender.sendMythicMessage(
mythicDrops.settingsManager.languageSettings.command.dropUnidentified.success,
"%amount%" to amountGiven.toString()
)
}
}
}
| mit | 1979411915dcc8da2f8ab9275c3b8a3e | 44.440945 | 117 | 0.611506 | 4.886537 | false | false | false | false |
exponent/exponent | packages/expo-constants/android/src/main/java/expo/modules/constants/ConstantsService.kt | 2 | 4259 | package expo.modules.constants
import org.apache.commons.io.IOUtils
import com.facebook.device.yearclass.YearClass
import expo.modules.core.interfaces.InternalModule
import expo.modules.interfaces.constants.ConstantsInterface
import android.os.Build
import android.util.Log
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import java.io.FileNotFoundException
import java.lang.Exception
import java.nio.charset.StandardCharsets
import java.util.*
private val TAG = ConstantsService::class.java.simpleName
private const val CONFIG_FILE_NAME = "app.config"
open class ConstantsService(private val context: Context) : InternalModule, ConstantsInterface {
var statusBarHeightInternal = context.resources.getIdentifier("status_bar_height", "dimen", "android")
.takeIf { it > 0 }
?.let { (context.resources::getDimensionPixelSize)(it) }
?.let { pixels -> convertPixelsToDp(pixels.toFloat(), context) }
?: 0
private val sessionId = UUID.randomUUID().toString()
private val exponentInstallationId: ExponentInstallationId = ExponentInstallationId(context)
enum class ExecutionEnvironment(val string: String) {
BARE("bare"),
STANDALONE("standalone"),
STORE_CLIENT("storeClient");
}
override fun getExportedInterfaces(): List<Class<*>> = listOf(ConstantsInterface::class.java)
override fun getConstants(): Map<String, Any?> {
val constants = mutableMapOf(
"sessionId" to sessionId,
"executionEnvironment" to ExecutionEnvironment.BARE.string,
"statusBarHeight" to statusBarHeightInternal,
"deviceYearClass" to deviceYearClass,
"deviceName" to deviceName,
"isDevice" to isDevice,
"systemFonts" to systemFonts,
"systemVersion" to systemVersion,
"installationId" to getOrCreateInstallationId(),
"manifest" to appConfig,
"platform" to mapOf("android" to emptyMap<String, Any>())
)
try {
val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
constants["nativeAppVersion"] = pInfo.versionName
val versionCode = getLongVersionCode(pInfo).toInt()
constants["nativeBuildVersion"] = versionCode.toString()
} catch (e: PackageManager.NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
}
return constants
}
// Just use package name in vanilla React Native apps.
override fun getAppScopeKey(): String? = context.packageName
override fun getAppOwnership() = "guest"
override fun getDeviceName(): String = Build.MODEL
override fun getDeviceYearClass() = YearClass.get(context)
override fun getIsDevice() = !isRunningOnGenymotion && !isRunningOnStockEmulator
override fun getStatusBarHeight() = statusBarHeightInternal
override fun getSystemVersion(): String = Build.VERSION.RELEASE
open fun getOrCreateInstallationId(): String = exponentInstallationId.getOrCreateUUID()
// From https://github.com/dabit3/react-native-fonts
override fun getSystemFonts() = listOf(
"normal",
"notoserif",
"sans-serif",
"sans-serif-light",
"sans-serif-thin",
"sans-serif-condensed",
"sans-serif-medium",
"serif",
"Roboto",
"monospace"
)
private val appConfig: String?
get() {
try {
context.assets.open(CONFIG_FILE_NAME).use {
stream ->
return IOUtils.toString(stream, StandardCharsets.UTF_8)
}
} catch (e: FileNotFoundException) {
// do nothing, expected in managed apps
} catch (e: Exception) {
Log.e(TAG, "Error reading embedded app config", e)
}
return null
}
companion object {
private fun convertPixelsToDp(px: Float, context: Context): Int {
val resources = context.resources
val metrics = resources.displayMetrics
val dp = px / (metrics.densityDpi / 160f)
return dp.toInt()
}
private val isRunningOnGenymotion: Boolean
get() = Build.FINGERPRINT.contains("vbox")
private val isRunningOnStockEmulator: Boolean
get() = Build.FINGERPRINT.contains("generic")
private fun getLongVersionCode(info: PackageInfo) =
if (Build.VERSION.SDK_INT >= 28) info.longVersionCode
else info.versionCode.toLong()
}
}
| bsd-3-clause | 124c0db96ba66db8f20ffc460b182f41 | 30.783582 | 104 | 0.711669 | 4.36373 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/toolchain/impl/RustcVersion.kt | 2 | 1961 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain.impl
import com.google.common.annotations.VisibleForTesting
import com.intellij.util.text.SemVer
import org.rust.cargo.toolchain.RustChannel
import org.rust.cargo.toolchain.RustChannel.Companion.fromPreRelease
import java.time.LocalDate
import java.time.format.DateTimeParseException
data class RustcVersion(
val semver: SemVer,
val host: String,
val channel: RustChannel,
val commitHash: String? = null,
val commitDate: LocalDate? = null
)
@VisibleForTesting
fun parseRustcVersion(lines: List<String>): RustcVersion? {
// We want to parse following
//
// ```
// rustc 1.8.0-beta.1 (facbfdd71 2016-03-02)
// binary: rustc
// commit-hash: facbfdd71cb6ed0aeaeb06b6b8428f333de4072b
// commit-date: 2016-03-02
// host: x86_64-unknown-linux-gnu
// release: 1.8.0-beta.1
// ```
val releaseRe = """release: (\d+\.\d+\.\d+.*)""".toRegex()
val hostRe = "host: (.*)".toRegex()
val commitHashRe = "commit-hash: ([A-Fa-f0-9]{40})".toRegex()
val commitDateRe = """commit-date: (\d{4}-\d{2}-\d{2})""".toRegex()
val find = { re: Regex -> lines.firstNotNullOfOrNull { re.matchEntire(it) } }
val releaseMatch = find(releaseRe) ?: return null
val hostText = find(hostRe)?.groups?.get(1)?.value ?: return null
val versionText = releaseMatch.groups[1]?.value ?: return null
val commitHash = find(commitHashRe)?.groups?.get(1)?.value
val commitDate = try {
find(commitDateRe)?.groups?.get(1)?.value?.let(LocalDate::parse)
} catch (e: DateTimeParseException) {
null
}
val semVer = SemVer.parseFromText(versionText) ?: return null
val preRelease = semVer.preRelease.orEmpty()
val channel = fromPreRelease(preRelease)
return RustcVersion(semVer, hostText, channel, commitHash, commitDate)
}
| mit | 007d844052a9127aba09679b6cc27b2e | 34.654545 | 81 | 0.680265 | 3.520646 | false | false | false | false |
google/dokka | core/src/main/kotlin/Kotlin/ContentBuilder.kt | 2 | 8617 | package org.jetbrains.dokka
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.html.entities.EntityConverter
import org.intellij.markdown.parser.LinkMap
import java.util.*
class LinkResolver(private val linkMap: LinkMap, private val contentFactory: (String) -> ContentBlock) {
fun getLinkInfo(refLabel: String) = linkMap.getLinkInfo(refLabel)
fun resolve(href: String): ContentBlock = contentFactory(href)
}
fun buildContent(tree: MarkdownNode, linkResolver: LinkResolver, inline: Boolean = false): MutableContent {
val result = MutableContent()
if (inline) {
buildInlineContentTo(tree, result, linkResolver)
} else {
buildContentTo(tree, result, linkResolver)
}
return result
}
fun buildContentTo(tree: MarkdownNode, target: ContentBlock, linkResolver: LinkResolver) {
// println(tree.toTestString())
val nodeStack = ArrayDeque<ContentBlock>()
nodeStack.push(target)
tree.visit { node, processChildren ->
val parent = nodeStack.peek()
fun appendNodeWithChildren(content: ContentBlock) {
nodeStack.push(content)
processChildren()
parent.append(nodeStack.pop())
}
when (node.type) {
MarkdownElementTypes.ATX_1 -> appendNodeWithChildren(ContentHeading(1))
MarkdownElementTypes.ATX_2 -> appendNodeWithChildren(ContentHeading(2))
MarkdownElementTypes.ATX_3 -> appendNodeWithChildren(ContentHeading(3))
MarkdownElementTypes.ATX_4 -> appendNodeWithChildren(ContentHeading(4))
MarkdownElementTypes.ATX_5 -> appendNodeWithChildren(ContentHeading(5))
MarkdownElementTypes.ATX_6 -> appendNodeWithChildren(ContentHeading(6))
MarkdownElementTypes.UNORDERED_LIST -> appendNodeWithChildren(ContentUnorderedList())
MarkdownElementTypes.ORDERED_LIST -> appendNodeWithChildren(ContentOrderedList())
MarkdownElementTypes.LIST_ITEM -> appendNodeWithChildren(ContentListItem())
MarkdownElementTypes.EMPH -> appendNodeWithChildren(ContentEmphasis())
MarkdownElementTypes.STRONG -> appendNodeWithChildren(ContentStrong())
MarkdownElementTypes.CODE_SPAN -> {
val startDelimiter = node.child(MarkdownTokenTypes.BACKTICK)?.text
if (startDelimiter != null) {
val text = node.text.substring(startDelimiter.length).removeSuffix(startDelimiter)
val codeSpan = ContentCode().apply { append(ContentText(text)) }
parent.append(codeSpan)
}
}
MarkdownElementTypes.CODE_BLOCK,
MarkdownElementTypes.CODE_FENCE -> {
val language = node.child(MarkdownTokenTypes.FENCE_LANG)?.text?.trim() ?: ""
appendNodeWithChildren(ContentBlockCode(language))
}
MarkdownElementTypes.PARAGRAPH -> appendNodeWithChildren(ContentParagraph())
MarkdownElementTypes.INLINE_LINK -> {
val linkTextNode = node.child(MarkdownElementTypes.LINK_TEXT)
val destination = node.child(MarkdownElementTypes.LINK_DESTINATION)
if (linkTextNode != null) {
if (destination != null) {
val link = ContentExternalLink(destination.text)
renderLinkTextTo(linkTextNode, link, linkResolver)
parent.append(link)
} else {
val link = ContentExternalLink(linkTextNode.getLabelText())
renderLinkTextTo(linkTextNode, link, linkResolver)
parent.append(link)
}
}
}
MarkdownElementTypes.SHORT_REFERENCE_LINK,
MarkdownElementTypes.FULL_REFERENCE_LINK -> {
val labelElement = node.child(MarkdownElementTypes.LINK_LABEL)
if (labelElement != null) {
val linkInfo = linkResolver.getLinkInfo(labelElement.text)
val labelText = labelElement.getLabelText()
val link = linkInfo?.let { linkResolver.resolve(it.destination.toString()) } ?: linkResolver.resolve(labelText)
val linkText = node.child(MarkdownElementTypes.LINK_TEXT)
if (linkText != null) {
renderLinkTextTo(linkText, link, linkResolver)
} else {
link.append(ContentText(labelText))
}
parent.append(link)
}
}
MarkdownTokenTypes.WHITE_SPACE -> {
// Don't append first space if start of header (it is added during formatting later)
// v
// #### Some Heading
if (nodeStack.peek() !is ContentHeading || node.parent?.children?.first() != node) {
parent.append(ContentText(node.text))
}
}
MarkdownTokenTypes.EOL -> {
if ((keepEol(nodeStack.peek()) && node.parent?.children?.last() != node) ||
// Keep extra blank lines when processing lists (affects Markdown formatting)
(processingList(nodeStack.peek()) && node.previous?.type == MarkdownTokenTypes.EOL)) {
parent.append(ContentText(node.text))
}
}
MarkdownTokenTypes.CODE_LINE -> {
val content = ContentText(node.text)
if (parent is ContentBlockCode) {
parent.append(content)
} else {
parent.append(ContentBlockCode().apply { append(content) })
}
}
MarkdownTokenTypes.TEXT -> {
fun createEntityOrText(text: String): ContentNode {
if (text == "&" || text == """ || text == "<" || text == ">") {
return ContentEntity(text)
}
if (text == "&") {
return ContentEntity("&")
}
val decodedText = EntityConverter.replaceEntities(text, true, true)
if (decodedText != text) {
return ContentEntity(text)
}
return ContentText(text)
}
parent.append(createEntityOrText(node.text))
}
MarkdownTokenTypes.EMPH -> {
val parentNodeType = node.parent?.type
if (parentNodeType != MarkdownElementTypes.EMPH && parentNodeType != MarkdownElementTypes.STRONG) {
parent.append(ContentText(node.text))
}
}
MarkdownTokenTypes.COLON,
MarkdownTokenTypes.SINGLE_QUOTE,
MarkdownTokenTypes.DOUBLE_QUOTE,
MarkdownTokenTypes.LT,
MarkdownTokenTypes.GT,
MarkdownTokenTypes.LPAREN,
MarkdownTokenTypes.RPAREN,
MarkdownTokenTypes.LBRACKET,
MarkdownTokenTypes.RBRACKET,
MarkdownTokenTypes.EXCLAMATION_MARK,
MarkdownTokenTypes.BACKTICK,
MarkdownTokenTypes.CODE_FENCE_CONTENT -> {
parent.append(ContentText(node.text))
}
MarkdownElementTypes.LINK_DEFINITION -> {
}
else -> {
processChildren()
}
}
}
}
private fun MarkdownNode.getLabelText() = children.filter { it.type == MarkdownTokenTypes.TEXT || it.type == MarkdownTokenTypes.EMPH }.joinToString("") { it.text }
private fun keepEol(node: ContentNode) = node is ContentParagraph || node is ContentSection || node is ContentBlockCode
private fun processingList(node: ContentNode) = node is ContentOrderedList || node is ContentUnorderedList
fun buildInlineContentTo(tree: MarkdownNode, target: ContentBlock, linkResolver: LinkResolver) {
val inlineContent = tree.children.singleOrNull { it.type == MarkdownElementTypes.PARAGRAPH }?.children ?: listOf(tree)
inlineContent.forEach {
buildContentTo(it, target, linkResolver)
}
}
fun renderLinkTextTo(tree: MarkdownNode, target: ContentBlock, linkResolver: LinkResolver) {
val linkTextNodes = tree.children.drop(1).dropLast(1)
linkTextNodes.forEach {
buildContentTo(it, target, linkResolver)
}
}
| apache-2.0 | 471706096cf99eb10da7622d57023250 | 44.835106 | 163 | 0.591621 | 5.276791 | false | false | false | false |
kamerok/Orny | app/src/main/kotlin/com/kamer/orny/data/room/entity/AuthorEntity.kt | 1 | 500 | package com.kamer.orny.data.room.entity
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import com.kamer.orny.data.domain.model.Author
@Entity(tableName = "authors")
data class AuthorEntity(
@PrimaryKey val id: String,
val position: Int,
val name: String,
val color: String
) {
fun toAuthor() = Author(
id = id,
position = position,
name = name,
color = color
)
} | apache-2.0 | 704b84643419507131db3eb0c40520a5 | 20.782609 | 47 | 0.624 | 3.968254 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/platform/ApplySpanStyleTest.kt | 3 | 12127 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.platform
import android.graphics.Typeface
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontSynthesis
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.platform.extensions.applySpanStyle
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextGeometricTransform
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class ApplySpanStyleTest {
private val context = InstrumentationRegistry.getInstrumentation().targetContext!!
private val density = Density(context)
private val resolveTypeface: (FontFamily?, FontWeight, FontStyle, FontSynthesis) -> Typeface =
{ _, _, _, _ ->
Typeface.DEFAULT
}
@Test
fun fontSizeSp_shouldBeAppliedTo_textSize() {
val fontSize = 24.sp
val spanStyle = SpanStyle(fontSize = fontSize)
val tp = AndroidTextPaint(0, density.density)
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.textSize).isEqualTo(with(density) { fontSize.toPx() })
assertThat(notApplied.fontSize).isEqualTo(TextUnit.Unspecified)
}
@Test
fun fontSizeEm_shouldBeAppliedTo_textSize() {
val fontSize = 2.em
val spanStyle = SpanStyle(fontSize = fontSize)
val tp = AndroidTextPaint(0, density.density)
tp.textSize = 30f
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.textSize).isEqualTo(60f)
assertThat(notApplied.fontSize).isEqualTo(TextUnit.Unspecified)
}
@Test
fun textGeometricTransform_shouldBeAppliedTo_scaleSkew() {
val textGeometricTransform = TextGeometricTransform(
scaleX = 1.5f,
skewX = 1f
)
val spanStyle = SpanStyle(textGeometricTransform = textGeometricTransform)
val tp = AndroidTextPaint(0, density.density)
val originalSkew = tp.textSkewX
val originalScale = tp.textScaleX
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.textSkewX).isEqualTo(originalSkew + textGeometricTransform.skewX)
assertThat(tp.textScaleX).isEqualTo(originalScale * textGeometricTransform.scaleX)
assertThat(notApplied.textGeometricTransform).isNull()
}
@Test
fun letterSpacingSp_shouldBeLeftAsSpan() {
val letterSpacing = 10.sp
val spanStyle = SpanStyle(letterSpacing = letterSpacing)
val tp = AndroidTextPaint(0, density.density)
tp.letterSpacing = 4f
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.letterSpacing).isEqualTo(4f)
assertThat(notApplied.letterSpacing).isEqualTo(letterSpacing)
}
@Test
fun letterSpacingEm_shouldBeAppliedTo_letterSpacing() {
val letterSpacing = 1.5.em
val spanStyle = SpanStyle(letterSpacing = letterSpacing)
val tp = AndroidTextPaint(0, density.density)
tp.letterSpacing = 4f
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.letterSpacing).isEqualTo(1.5f)
assertThat(notApplied.letterSpacing).isEqualTo(TextUnit.Unspecified)
}
@Test
fun letterSpacingUnspecified_shouldBeNoOp() {
val letterSpacing = TextUnit.Unspecified
val spanStyle = SpanStyle(letterSpacing = letterSpacing)
val tp = AndroidTextPaint(0, density.density)
tp.letterSpacing = 4f
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.letterSpacing).isEqualTo(4f)
assertThat(notApplied.letterSpacing).isEqualTo(TextUnit.Unspecified)
}
@Test
fun nonEmptyFontFeatureSettings_shouldBeAppliedTo_fontFeatureSettings() {
val fontFeatureSettings = "\"kern\" 0"
val spanStyle = SpanStyle(fontFeatureSettings = fontFeatureSettings)
val tp = AndroidTextPaint(0, density.density)
tp.fontFeatureSettings = ""
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.fontFeatureSettings).isEqualTo(fontFeatureSettings)
assertThat(notApplied.fontFeatureSettings).isNull()
}
@Test
fun emptyFontFeatureSettings_shouldBeNotAppliedTo_fontFeatureSettings() {
val fontFeatureSettings = ""
val spanStyle = SpanStyle(fontFeatureSettings = fontFeatureSettings)
val tp = AndroidTextPaint(0, density.density)
tp.fontFeatureSettings = "\"kern\" 0"
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.fontFeatureSettings).isEqualTo("\"kern\" 0")
assertThat(notApplied.fontFeatureSettings).isNull()
}
@Test
fun fontSettings_shouldBeAppliedTo_typeface() {
val fontFamily = FontFamily.Cursive
val fontWeight = FontWeight.W800
val fontStyle = FontStyle.Italic
val fontSynthesis = FontSynthesis.Style
val spanStyle = SpanStyle(
fontFamily = fontFamily,
fontWeight = fontWeight,
fontStyle = fontStyle,
fontSynthesis = fontSynthesis
)
val tp = AndroidTextPaint(0, density.density)
tp.typeface = Typeface.DEFAULT
var calledFontFamily: FontFamily? = null
var calledFontWeight: FontWeight? = null
var calledFontStyle: FontStyle? = null
var calledFontSynthesis: FontSynthesis? = null
val notApplied = tp.applySpanStyle(
spanStyle,
{ family, weight, style, synthesis ->
calledFontFamily = family
calledFontWeight = weight
calledFontStyle = style
calledFontSynthesis = synthesis
Typeface.MONOSPACE
},
density
)
assertThat(tp.typeface).isEqualTo(Typeface.MONOSPACE)
assertThat(calledFontFamily).isEqualTo(fontFamily)
assertThat(calledFontWeight).isEqualTo(fontWeight)
assertThat(calledFontStyle).isEqualTo(fontStyle)
assertThat(calledFontSynthesis).isEqualTo(fontSynthesis)
assertThat(notApplied.fontFamily).isNull()
assertThat(notApplied.fontWeight).isNull()
assertThat(notApplied.fontStyle).isNull()
assertThat(notApplied.fontSynthesis).isNull()
}
@Test
fun baselineShift_shouldBeLeftAsSpan() {
val baselineShift = BaselineShift(0.8f)
val spanStyle = SpanStyle(baselineShift = baselineShift)
val tp = AndroidTextPaint(0, density.density)
tp.baselineShift = 0
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.baselineShift).isEqualTo(0)
assertThat(notApplied.baselineShift).isEqualTo(baselineShift)
}
@Test
fun baselineShiftNone_shouldNotBeLeftAsSpan() {
val baselineShift = BaselineShift.None
val spanStyle = SpanStyle(baselineShift = baselineShift)
val tp = AndroidTextPaint(0, density.density)
tp.baselineShift = 0
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.baselineShift).isEqualTo(0)
assertThat(notApplied.baselineShift).isNull()
}
@Test
fun background_shouldBeLeftAsSpan() {
val background = Color.Red
val spanStyle = SpanStyle(background = background)
val tp = AndroidTextPaint(0, density.density)
tp.color = Color.Black.toArgb()
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.color).isEqualTo(Color.Black.toArgb())
assertThat(notApplied.background).isEqualTo(background)
}
@Test
fun backgroundTransparent_shouldNotBeLeftAsSpan() {
val background = Color.Transparent
val spanStyle = SpanStyle(background = background)
val tp = AndroidTextPaint(0, density.density)
tp.color = Color.Black.toArgb()
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.color).isEqualTo(Color.Black.toArgb())
assertThat(notApplied.background).isEqualTo(Color.Unspecified)
}
@Test
fun textDecorationUnderline_shouldBeAppliedToPaint() {
val textDecoration = TextDecoration.Underline
val spanStyle = SpanStyle(textDecoration = textDecoration)
val tp = AndroidTextPaint(0, density.density)
tp.isUnderlineText = false
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.isUnderlineText).isEqualTo(true)
assertThat(notApplied.textDecoration).isEqualTo(null)
}
@Test
fun textDecorationLineThrough_shouldBeAppliedToPaint() {
val textDecoration = TextDecoration.LineThrough
val spanStyle = SpanStyle(textDecoration = textDecoration)
val tp = AndroidTextPaint(0, density.density)
tp.isStrikeThruText = false
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.isStrikeThruText).isEqualTo(true)
assertThat(notApplied.textDecoration).isEqualTo(null)
}
@Test
fun textDecorationCombined_shouldBeAppliedToPaint() {
val textDecoration =
TextDecoration.combine(listOf(TextDecoration.LineThrough, TextDecoration.Underline))
val spanStyle = SpanStyle(textDecoration = textDecoration)
val tp = AndroidTextPaint(0, density.density)
tp.isUnderlineText = false
tp.isStrikeThruText = false
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.isUnderlineText).isEqualTo(true)
assertThat(tp.isStrikeThruText).isEqualTo(true)
assertThat(notApplied.textDecoration).isEqualTo(null)
}
@Test
fun shadow_shouldBeAppliedTo_shadowLayer() {
val shadow = Shadow(Color.Red, Offset(4f, 4f), blurRadius = 8f)
val spanStyle = SpanStyle(shadow = shadow)
val tp = AndroidTextPaint(0, density.density)
tp.clearShadowLayer()
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.shadow).isEqualTo(shadow)
assertThat(notApplied.shadow).isNull()
}
@Test
fun color_shouldBeAppliedTo_color() {
val color = Color.Red
val spanStyle = SpanStyle(color = color)
val tp = AndroidTextPaint(0, density.density)
tp.color = Color.Black.toArgb()
val notApplied = tp.applySpanStyle(spanStyle, resolveTypeface, density)
assertThat(tp.color).isEqualTo(Color.Red.toArgb())
assertThat(notApplied.color).isEqualTo(Color.Unspecified)
}
} | apache-2.0 | 1c24324981e78ac8f16da3cf1138ff7b | 35.97561 | 98 | 0.703637 | 4.630393 | false | true | false | false |
klazuka/intellij-elm | src/test/kotlin/org/elm/lang/core/completion/ElmRecordCompletionTest.kt | 1 | 2074 | package org.elm.lang.core.completion
class ElmRecordCompletionTest : ElmCompletionTestBase() {
fun `test access name field from one letter`() = doSingleCompletion(
"""
type alias Foo = { name : String }
f : Foo -> String
f foo =
foo.n{-caret-}
""", """
type alias Foo = { name : String }
f : Foo -> String
f foo =
foo.name{-caret-}
""")
fun `test access name field from blank`() = doSingleCompletion(
"""
type alias Foo = { name : String }
f : Foo -> String
f foo =
foo.{-caret-}
""", """
type alias Foo = { name : String }
f : Foo -> String
f foo =
foo.name{-caret-}
""")
fun `test chained field access`() = doSingleCompletion(
"""
type alias Foo = { name : { first: String } }
f : Foo -> String
f foo =
foo.name.fir{-caret-}
""", """
type alias Foo = { name : { first: String } }
f : Foo -> String
f foo =
foo.name.first{-caret-}
""")
// partial program tests
fun `test incomplete case expression`() = doSingleCompletion(
"""
type alias Foo = { name : String }
f : Foo -> String
f r =
case r.{-caret-}
""", """
type alias Foo = { name : String }
f : Foo -> String
f r =
case r.name{-caret-}
""")
fun `test unresolved reference`() = doSingleCompletion(
"""
type alias Foo = { name : String }
f : Foo -> String
f r =
foo r.{-caret-}
""", """
type alias Foo = { name : String }
f : Foo -> String
f r =
foo r.name{-caret-}
""")
fun `test too many arguments`() = doSingleCompletion(
"""
type alias Foo = { name : String }
f : Foo -> Int
f r = 1
g : Foo -> Int
g r = f 1 r.{-caret-}
""", """
type alias Foo = { name : String }
f : Foo -> Int
f r = 1
g : Foo -> Int
g r = f 1 r.name{-caret-}
""")
fun `test incomplete case expression with chained access`() = doSingleCompletion(
"""
type alias Foo = { name : { first: String } }
f : Foo -> String
f r =
case r.name.fir{-caret-}
""", """
type alias Foo = { name : { first: String } }
f : Foo -> String
f r =
case r.name.first{-caret-}
""")
}
| mit | 726126a0fd02fb5ee1a3e634ea4810b9 | 17.192982 | 85 | 0.550145 | 3.445183 | false | true | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/PdfPrototype.kt | 1 | 7742 | package me.proxer.app.ui.view.bbcode.prototype
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.TextView
import androidx.core.view.doOnLayout
import androidx.core.view.updateLayoutParams
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.sizeDp
import com.uber.autodispose.android.ViewScopeProvider
import com.uber.autodispose.autoDisposable
import de.number42.subsampling_pdf_decoder.PDFDecoder
import de.number42.subsampling_pdf_decoder.PDFRegionDecoder
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.ui.view.bbcode.BBUtils
import me.proxer.app.ui.view.bbcode.prototype.BBPrototype.Companion.REGEX_OPTIONS
import me.proxer.app.util.extension.events
import me.proxer.app.util.extension.iconColor
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import me.proxer.app.util.rx.SubsamplingScaleImageViewEventObservable
import me.proxer.app.util.wrapper.OriginalSizeGlideTarget
import me.proxer.app.util.wrapper.SimpleGlideRequestListener
import okhttp3.HttpUrl
import java.io.File
/**
* @author Ruben Gees
*/
object PdfPrototype : AutoClosingPrototype {
private const val WIDTH_ARGUMENT = "width"
private val widthAttributeRegex = Regex("(?:size)? *= *(.+?)( |\$)", REGEX_OPTIONS)
override val startRegex = Regex(" *pdf *=? *\"?.*?\"?( .*?)?", REGEX_OPTIONS)
override val endRegex = Regex("/ *pdf *", REGEX_OPTIONS)
override fun construct(code: String, parent: BBTree): BBTree {
val width = BBUtils.cutAttribute(code, widthAttributeRegex)?.toIntOrNull()
return BBTree(this, parent, args = BBArgs(custom = *arrayOf(WIDTH_ARGUMENT to width)))
}
override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> {
val childViews = children.flatMap { it.makeViews(parent, args) }
return when {
childViews.isEmpty() -> childViews
else -> listOf(SubsamplingScaleImageView(parent.context).also { view: SubsamplingScaleImageView ->
val url = (childViews.firstOrNull() as? TextView)?.text.toString().trim()
val parsedUrl = url.toPrefixedUrlOrNull()
@Suppress("UNCHECKED_CAST")
val heightMap = args[ImagePrototype.HEIGHT_MAP_ARGUMENT] as MutableMap<String, Int>?
val width = args[WIDTH_ARGUMENT] as Int? ?: MATCH_PARENT
val height = parsedUrl?.let { heightMap?.get(it.toString()) } ?: WRAP_CONTENT
view.layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, height)
view.setDoubleTapZoomDuration(view.context.resources.getInteger(android.R.integer.config_shortAnimTime))
view.setMinimumTileDpi(196)
args.glide?.let { loadImage(it, view, parsedUrl, heightMap) }
view.clicks()
.filter { view.getTag(R.id.error_tag) == true }
.autoDisposable(ViewScopeProvider.from(parent))
.subscribe {
view.tag = null
args.glide?.let { loadImage(it, view, parsedUrl, heightMap) }
}
view.doOnLayout {
if (width < view.width) {
view.updateLayoutParams {
this.width = width
}
view.requestLayout()
}
}
})
}
}
private fun loadImage(
glide: GlideRequests,
view: SubsamplingScaleImageView,
url: HttpUrl?,
heightMap: MutableMap<String, Int>?
) = glide
.download(url.toString())
.listener(object : SimpleGlideRequestListener<File?> {
override fun onResourceReady(
resource: File?,
model: Any?,
target: Target<File?>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
(target as? GlidePdfTarget)?.view?.also { view ->
if (view.layoutParams.height <= 0) {
findHost(view)?.heightChanges?.onNext(Unit)
}
}
return false
}
})
.into(GlidePdfTarget(view, url.toString(), heightMap))
private fun handleLoadError(view: SubsamplingScaleImageView) {
view.setTag(R.id.error_tag, true)
view.setImage(
ImageSource.bitmap(
IconicsDrawable(view.context, CommunityMaterial.Icon.cmd_refresh)
.iconColor(view.context)
.sizeDp(32)
.toBitmap()
)
)
}
private fun findHost(view: View): BBCodeView? {
var current = view.parent
while (current !is BBCodeView && current is ViewGroup) {
current = current.parent
}
return current as? BBCodeView
}
private class GlidePdfTarget(
view: SubsamplingScaleImageView,
private val model: String,
private val dimensionMap: MutableMap<String, Int>?
) : OriginalSizeGlideTarget<File>() {
var view: SubsamplingScaleImageView? = view
private set
private var regionDecoder: PDFRegionDecoder? = null
init {
view.doOnLayout {
view.events()
.publish()
.autoConnect(2)
.also { observable ->
observable.filter { it is SubsamplingScaleImageViewEventObservable.Event.Error }
.autoDisposable(ViewScopeProvider.from(view))
.subscribe { handleLoadError(view) }
observable.filter { it is SubsamplingScaleImageViewEventObservable.Event.Loaded }
.autoDisposable(ViewScopeProvider.from(view))
.subscribe {
view.setDoubleTapZoomScale(view.scale * 2.5f)
view.maxScale = view.scale * 2.5f
dimensionMap?.put(model, view.height)
}
}
}
}
override fun onResourceReady(resource: File, transition: Transition<in File>?) {
view?.also { safeView ->
regionDecoder = PDFRegionDecoder(0, resource, 8f).also {
safeView.setRegionDecoderFactory { it }
}
safeView.setBitmapDecoderFactory { PDFDecoder(0, resource, 8f) }
safeView.setImage(ImageSource.uri(resource.absolutePath))
}
}
override fun onLoadFailed(errorDrawable: Drawable?) {
view?.also { handleLoadError(it) }
}
override fun onLoadCleared(placeholder: Drawable?) {
regionDecoder?.recycle()
regionDecoder = null
view = null
}
}
}
| gpl-3.0 | 0f6d2af72cd1ebbb9cb5f9c091bc58de | 36.400966 | 120 | 0.607595 | 4.841776 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/reference/MethodReference.kt | 1 | 2307 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.reference
import com.demonwav.mcdev.platform.mixin.handlers.InjectorAnnotationHandler
import com.demonwav.mcdev.platform.mixin.handlers.MixinAnnotationHandler
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.insideAnnotationAttribute
import com.intellij.openapi.project.Project
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PsiJavaPatterns
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLiteral
import com.intellij.util.ProcessingContext
object MethodReference : AbstractMethodReference() {
val ELEMENT_PATTERN: ElementPattern<PsiLiteral> =
PsiJavaPatterns.psiLiteral(StandardPatterns.string()).insideAnnotationAttribute(
PsiJavaPatterns.psiAnnotation().with(
object : PatternCondition<PsiAnnotation>("injector") {
override fun accepts(t: PsiAnnotation, context: ProcessingContext?): Boolean {
val qName = t.qualifiedName ?: return false
return MixinAnnotationHandler.forMixinAnnotation(qName, t.project) is InjectorAnnotationHandler
}
}
),
"method"
)
override val description = "method '%s' in target class"
override fun isValidAnnotation(name: String, project: Project) =
MixinAnnotationHandler.forMixinAnnotation(name, project) is InjectorAnnotationHandler
override fun parseSelector(context: PsiElement): MixinSelector? {
return parseMixinSelector(context)
}
override fun parseSelector(stringValue: String, context: PsiElement): MixinSelector? {
return parseMixinSelector(stringValue, context)
}
override fun isUnresolved(context: PsiElement): Boolean {
return if (super.isUnresolved(context)) {
val stringValue = context.constantStringValue ?: return true
!isMiscDynamicSelector(context.project, stringValue)
} else {
false
}
}
}
| mit | 25be6bdc25f950eea70e552cc5217552 | 36.209677 | 119 | 0.718249 | 5.138085 | false | false | false | false |
devromik/black-and-white | sources/src/test/kotlin/net/devromik/bw/bz/InnerTreeNodeResultTest.kt | 1 | 4628 | package net.devromik.bw.bz
import net.devromik.bw.FixedRootColorMaxWhiteMap
import net.devromik.tree.IndexedTreeInfo
import net.devromik.tree.Tree
import net.devromik.tree.TreeNode
import net.devromik.tree.root
import org.junit.Assert.*
import org.junit.Test
/**
* @author Shulnyaev Roman
*/
class InnerTreeNodeResultTest {
@Test fun isFusionStack() {
val node = TreeNode<String>()
val result = InnerTreeNodeResult(node, 1)
val fusion_1 = SingleChildFusion(FixedRootColorMaxWhiteMap.forSingleNode())
val fusion_2 = SingleChildFusion(FixedRootColorMaxWhiteMap.forSingleNode())
val fusion_3 = SingleChildFusion(FixedRootColorMaxWhiteMap.forSingleNode())
result.pushFusion(fusion_1)
assertEquals(fusion_1, result.topFusion())
result.pushFusion(fusion_2)
assertEquals(fusion_2, result.topFusion())
result.pushFusion(fusion_3)
assertEquals(fusion_3, result.topFusion())
}
@Test fun canBeReduced() {
val tree: Tree<String> = Tree(
root("root") {
child("child_1") {
child("child_1_1")
}
child("child_2") {
child("child_2_1")
}
}
)
tree.index()
val treeResult = IndexedTreeInfo<String, TreeNodeResult<String>>(tree)
val root = tree.root
val rootResult = InnerTreeNodeResult(root, 5)
assertEquals(5, rootResult.initSubtreeSize())
assertEquals(5, rootResult.subtreeSize())
treeResult[root] = rootResult
val child_1 = root.childAt(0)
val child_1_Result = InnerTreeNodeResult(child_1, 2)
assertEquals(2, child_1_Result.initSubtreeSize())
assertEquals(2, child_1_Result.subtreeSize())
treeResult[child_1] = child_1_Result
val child_1_1 = child_1.childAt(0)
val child_1_1_Result = LeafTreeNodeResult(child_1_1)
assertEquals(1, child_1_1_Result.initSubtreeSize())
assertEquals(1, child_1_1_Result.subtreeSize())
treeResult[child_1_1] = child_1_1_Result
val child_2 = root.childAt(1)
val child_2_Result = InnerTreeNodeResult(child_2, 2)
assertEquals(2, child_2_Result.initSubtreeSize())
assertEquals(2, child_2_Result.subtreeSize())
treeResult[child_2] = child_2_Result
val child_2_1 = child_2.childAt(0)
val child_2_1_Result = LeafTreeNodeResult(child_2_1)
assertEquals(1, child_2_1_Result.initSubtreeSize())
assertEquals(1, child_2_1_Result.subtreeSize())
treeResult[child_2_1] = child_2_1_Result
// ****************************** //
child_1_Result.reduce(treeResult)
assertEquals(5, rootResult.initSubtreeSize())
assertEquals(4, rootResult.subtreeSize())
assertEquals(2, child_1_Result.initSubtreeSize())
assertEquals(1, child_1_Result.subtreeSize())
assertEquals(1, child_1_1_Result.initSubtreeSize())
assertEquals(1, child_1_1_Result.subtreeSize())
assertEquals(2, child_2_Result.initSubtreeSize())
assertEquals(2, child_2_Result.subtreeSize())
assertEquals(1, child_2_1_Result.initSubtreeSize())
assertEquals(1, child_2_1_Result.subtreeSize())
// ****************************** //
child_2_Result.reduce(treeResult)
assertEquals(5, rootResult.initSubtreeSize())
assertEquals(3, rootResult.subtreeSize())
assertEquals(2, child_1_Result.initSubtreeSize())
assertEquals(1, child_1_Result.subtreeSize())
assertEquals(1, child_1_1_Result.initSubtreeSize())
assertEquals(1, child_1_1_Result.subtreeSize())
assertEquals(2, child_2_Result.initSubtreeSize())
assertEquals(1, child_2_Result.subtreeSize())
assertEquals(1, child_2_1_Result.initSubtreeSize())
assertEquals(1, child_2_1_Result.subtreeSize())
// ****************************** //
rootResult.reduce(treeResult)
assertEquals(5, rootResult.initSubtreeSize())
assertEquals(1, rootResult.subtreeSize())
assertEquals(2, child_1_Result.initSubtreeSize())
assertEquals(1, child_1_Result.subtreeSize())
assertEquals(1, child_1_1_Result.initSubtreeSize())
assertEquals(1, child_1_1_Result.subtreeSize())
assertEquals(2, child_2_Result.initSubtreeSize())
assertEquals(1, child_2_Result.subtreeSize())
assertEquals(1, child_2_1_Result.initSubtreeSize())
assertEquals(1, child_2_1_Result.subtreeSize())
}
} | mit | 6fc0a93e2c7bc002d233c365f8d9c46e | 33.036765 | 83 | 0.630078 | 3.876047 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/NavigationMenuEntriesGenerator.kt | 1 | 2627 | package nerd.tuxmobil.fahrplan.congress.schedule
import info.metadude.android.eventfahrplan.commons.logging.Logging
import info.metadude.android.eventfahrplan.commons.temporal.Moment
import nerd.tuxmobil.fahrplan.congress.models.DateInfo
import nerd.tuxmobil.fahrplan.congress.models.DateInfos
internal class NavigationMenuEntriesGenerator @JvmOverloads constructor(
/**
* The word "Day" in the language of choice.
*/
private val dayString: String,
/**
* The word "Today" in the language of choice.
*/
private val todayString: String,
private val logging: Logging = Logging.get()
) {
private companion object {
const val LOG_TAG = "NavigationMenuEntriesGenerator"
}
/**
* Returns a [String] array of day menu entries.
*
* If the [currentDate] matches a date in [dateInfos] then the corresponding day will be suffixed
* with the given [todayString]. Example: ["Day 1", "Day 2 - Today", "Day 3"]
* An [IllegalArgumentException] is thrown the parameter restrictions are not met.
*
* @param numDays Number of days. Must be 1 or more.
* @param dateInfos A [list of DateInfo objects][DateInfos]. The [dayIndex][DateInfo.dayIndex]
* of the first object must be 1 as defined in the schedule XML. The list cannot be null nor empty.
* @param currentDate A moment instance representing the day of interest.
*/
fun getDayMenuEntries(
numDays: Int,
dateInfos: DateInfos?,
currentDate: Moment = Moment.now().startOfDay()
): List<String> {
if (numDays < 1) {
throw IllegalArgumentException("Invalid number of days: $numDays")
}
if (dateInfos == null || dateInfos.isEmpty()) {
throw IllegalArgumentException("Invalid date info list: $dateInfos")
}
if (numDays < dateInfos.size) {
throw IllegalArgumentException("Too small number of days: $numDays, date info list contains ${dateInfos.size} items")
}
logging.d(LOG_TAG, "Today is " + currentDate.toUtcDateTime().toLocalDate())
val entries = mutableListOf<String>()
for (dayIndex in 0 until numDays) {
var entry = "$dayString ${dayIndex + 1}"
for (dateInfo in dateInfos) {
if (dateInfo.dayIndex == dayIndex + 1) {
if (currentDate == dateInfo.date) {
entry += " - $todayString"
}
break
}
}
entries.add(dayIndex, entry)
}
return entries.toList()
}
}
| apache-2.0 | b67abaac5db3b2828b3fe0806153e8df | 36.528571 | 129 | 0.62619 | 4.537133 | false | false | false | false |
esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/ui/formatter/PrettyDateHistoryFieldFormat.kt | 3 | 2075 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin.ui.formatter
import com.hp.gagawa.java.elements.Span
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.core.utils.DateTimeUtils
import com.mycollab.core.utils.StringUtils
import com.mycollab.core.utils.TimezoneVal
import com.mycollab.module.user.domain.SimpleUser
import com.mycollab.vaadin.UserUIContext
/**
* @author MyCollab Ltd
* @since 5.3.4
*/
class PrettyDateHistoryFieldFormat : HistoryFieldFormat {
override fun toString(value: String): String =
toString(UserUIContext.getUser(), value, true, UserUIContext.getMessage(GenericI18Enum.FORM_EMPTY))
override fun toString(currentViewUser: SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String =
when {
StringUtils.isNotBlank(value) -> {
val formatDate = DateTimeUtils.parseDateTimeWithMilisByW3C(value)
if (displayAsHtml) {
val lbl = Span().appendText(DateTimeUtils.getPrettyDateValue(formatDate, TimezoneVal.valueOf(currentViewUser.timezone), currentViewUser.locale))
lbl.title = value
lbl.write()
} else {
UserUIContext.formatDate(formatDate)
}
}
else -> msgIfBlank
}
}
| agpl-3.0 | 5ef7e05bce6998e35898605494d75300 | 40.48 | 168 | 0.68081 | 4.538293 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/breakpoints/SelectBreakPropertiesPanel.kt | 1 | 4777 | package org.jetbrains.haskell.debugger.breakpoints
import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import com.intellij.xdebugger.breakpoints.XBreakpointProperties
import javax.swing.JComponent
import com.intellij.openapi.ui.ComboBox
import javax.swing.DefaultComboBoxModel
import javax.swing.JPanel
import javax.swing.JLabel
import javax. swing.SpringLayout.Constraints
import java.awt.GridLayout
import com.intellij.openapi.util.Key
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.Condition
import org.jetbrains.haskell.debugger.parser.HsFilePosition
import java.util.ArrayList
//import org.jetbrains.haskell.debugger.protocol.BreakListForLineCommand
import org.jetbrains.haskell.debugger.utils.SyncObject
import com.intellij.xdebugger.XDebuggerManager
import org.jetbrains.haskell.debugger.utils.HaskellUtils
import org.jetbrains.haskell.debugger.parser.BreakInfo
import org.jetbrains.haskell.debugger.utils.UIUtils
/**
* Panel with additional breakpoint settings (make right click on breakpoint to see it)
*
* @author Habibullin Marat
*/
public class SelectBreakPropertiesPanel : XBreakpointCustomPropertiesPanel<XLineBreakpoint<XBreakpointProperties<out Any?>>>() {
private val PANEL_LABEL: String = "Select breakpoint:"
private val DEBUG_NOT_STARTED_ITEM: String = "start debug process to enable"
private val breaksComboBox: ComboBox = ComboBox(DefaultComboBoxModel(arrayOf(DEBUG_NOT_STARTED_ITEM)))
private val mainPanel: JPanel = JPanel(GridLayout(1, 0))
init {
UIUtils.addLabeledControl(mainPanel, 0, PANEL_LABEL, breaksComboBox)
breaksComboBox.setEnabled(false)
}
private var debugManager: XDebuggerManager? = null
private var debugProcess: HaskellDebugProcess? = null
private var breaksList: ArrayList<BreakInfo>? = ArrayList()
private var lastSelectedIndex: Int? = null
override fun getComponent(): JComponent = mainPanel
/**
* Called when one press 'Done' button in breakpoint's context menu. Saves user selection and resets breakpoint if needed
*/
override fun saveTo(breakpoint: XLineBreakpoint<XBreakpointProperties<out Any?>>) {
if(debuggingInProgress()) {
val selectedIndex = breaksComboBox.getSelectedIndex()
if (selectedIndex != lastSelectedIndex && debugProcess != null) {
breakpoint.putUserData(HaskellLineBreakpointHandler.INDEX_IN_BREAKS_LIST_KEY, selectedIndex)
val moduleName = HaskellUtils.getModuleName(debugManager!!.getCurrentSession()!!.getProject(), breakpoint.getSourcePosition()!!.getFile())
debugProcess?.removeBreakpoint(moduleName, HaskellUtils.zeroBasedToHaskellLineNumber(breakpoint.getLine()))
debugProcess?.addBreakpointByIndex(moduleName, breaksList!!.get(selectedIndex).breakIndex, breakpoint)
}
}
}
/**
* Called on every right click on breakpoint. Fills combo box with available breaks info
*/
override fun loadFrom(breakpoint: XLineBreakpoint<XBreakpointProperties<out Any?>>) {
getUserData(breakpoint)
fillComboBox()
}
private fun getUserData(breakpoint: XLineBreakpoint<XBreakpointProperties<out Any?>>) {
val project = breakpoint.getUserData(HaskellLineBreakpointHandler.PROJECT_KEY)
if(project != null) {
debugManager = XDebuggerManager.getInstance(project)
val justDebugProcess = debugManager?.getCurrentSession()?.getDebugProcess()
if(justDebugProcess != null) {
debugProcess = justDebugProcess as HaskellDebugProcess
} else {
debugProcess = null
}
}
breaksList = breakpoint.getUserData(HaskellLineBreakpointHandler.BREAKS_LIST_KEY)
lastSelectedIndex = breakpoint.getUserData(HaskellLineBreakpointHandler.INDEX_IN_BREAKS_LIST_KEY)
}
private fun fillComboBox() {
breaksComboBox.removeAllItems()
if(debuggingInProgress() && (breaksList as ArrayList<BreakInfo>).isNotEmpty()) {
for (breakEntry in breaksList as ArrayList<BreakInfo>) {
breaksComboBox.addItem(breakEntry.srcSpan.spanToString())
}
breaksComboBox.setSelectedIndex(lastSelectedIndex as Int)
breaksComboBox.setEnabled(true)
} else {
breaksComboBox.addItem(DEBUG_NOT_STARTED_ITEM)
breaksComboBox.setEnabled(false)
}
}
private fun debuggingInProgress(): Boolean {
return debugManager?.getCurrentSession() != null
}
} | apache-2.0 | e923d53a89d91ca64a8dd11918ab00c4 | 44.504762 | 154 | 0.734771 | 5.007338 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/ContentListActivityModel.kt | 1 | 8216 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.viewmodel
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.ItemAnimator
import androidx.recyclerview.widget.RecyclerView.LayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import net.mm2d.dmsexplorer.Const
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.Repository
import net.mm2d.dmsexplorer.domain.entity.ContentEntity
import net.mm2d.dmsexplorer.domain.model.ExploreListener
import net.mm2d.dmsexplorer.domain.model.MediaServerModel
import net.mm2d.dmsexplorer.settings.Settings
import net.mm2d.dmsexplorer.util.AttrUtils
import net.mm2d.dmsexplorer.util.FeatureUtils
import net.mm2d.dmsexplorer.view.adapter.ContentListAdapter
import net.mm2d.dmsexplorer.view.animator.CustomItemAnimator
import net.mm2d.dmsexplorer.view.dialog.SortDialog
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class ContentListActivityModel(
private val activity: FragmentActivity,
repository: Repository,
private val cdsSelectListener: CdsSelectListener,
private val twoPane: Boolean
) : BaseObservable(), ExploreListener {
val refreshColors =
intArrayOf(R.color.progress1, R.color.progress2, R.color.progress3, R.color.progress4)
val progressBackground: Int =
AttrUtils.resolveColor(activity, R.attr.themeProgressBackground, Color.BLACK)
val distanceToTriggerSync: Int =
activity.resources.getDimensionPixelOffset(R.dimen.distance_to_trigger_sync)
val onRefreshListener: OnRefreshListener
val itemAnimator: ItemAnimator
val cdsListLayoutManager: LayoutManager
val title: String
val toolbarBackground: Int
val focusable: Boolean
val contentListAdapter: ContentListAdapter
@get:Bindable
var subtitle = ""
set(subtitle) {
field = subtitle
notifyPropertyChanged(BR.subtitle)
}
@get:Bindable
var isRefreshing: Boolean = false
set(refreshing) {
field = refreshing
notifyPropertyChanged(BR.refreshing)
}
private var _scrollPosition = INVALID_POSITION
private val handler = Handler(Looper.getMainLooper())
private val mediaServerModel: MediaServerModel
private val settings: Settings = Settings.get()
val isItemSelected: Boolean
get() {
return mediaServerModel.selectedEntity?.type?.isPlayable == true
}
// 選択項目を中央に表示させる処理
// FIXME: DataBindingを使ったことで返って複雑化してしまっている
var scrollPosition: Int
@Bindable
get() = _scrollPosition
set(position) {
_scrollPosition = position
notifyPropertyChanged(BR.scrollPosition)
}
interface CdsSelectListener {
fun onSelect(
v: View,
entity: ContentEntity
)
fun onLostSelection()
fun onExecute(
v: View,
entity: ContentEntity,
selected: Boolean
)
}
init {
val model = repository.mediaServerModel ?: throw IllegalStateException()
mediaServerModel = model
mediaServerModel.setExploreListener(this)
contentListAdapter = ContentListAdapter(activity).also {
it.setOnItemClickListener(::onItemClick)
it.setOnItemLongClickListener(::onItemLongClick)
}
focusable = !FeatureUtils.hasTouchScreen(activity)
cdsListLayoutManager = LinearLayoutManager(activity)
itemAnimator = CustomItemAnimator(activity)
title = mediaServerModel.title
onRefreshListener = OnRefreshListener { mediaServerModel.reload() }
val server = mediaServerModel.mediaServer
settings.themeParams
.serverColorExtractor
.invoke(server, null)
toolbarBackground = server.getIntTag(Const.KEY_TOOLBAR_COLLAPSED_COLOR, Color.BLACK)
}
private fun onItemClick(
v: View,
entity: ContentEntity
) {
if (mediaServerModel.enterChild(entity)) {
cdsSelectListener.onLostSelection()
return
}
val selected = entity == mediaServerModel.selectedEntity
mediaServerModel.setSelectedEntity(entity)
contentListAdapter.setSelectedEntity(entity)
if (settings.shouldShowContentDetailOnTap()) {
if (twoPane && selected) {
cdsSelectListener.onExecute(v, entity, true)
} else {
cdsSelectListener.onSelect(v, entity)
}
} else {
cdsSelectListener.onExecute(v, entity, selected)
}
}
private fun onItemLongClick(
v: View,
entity: ContentEntity
) {
if (mediaServerModel.enterChild(entity)) {
cdsSelectListener.onLostSelection()
return
}
val selected = entity == mediaServerModel.selectedEntity
mediaServerModel.setSelectedEntity(entity)
contentListAdapter.setSelectedEntity(entity)
if (settings.shouldShowContentDetailOnTap()) {
cdsSelectListener.onExecute(v, entity, selected)
} else {
cdsSelectListener.onSelect(v, entity)
}
}
fun syncSelectedEntity() {
val entity = mediaServerModel.selectedEntity
if (!contentListAdapter.setSelectedEntity(entity) || entity == null) {
return
}
val index = contentListAdapter.indexOf(entity)
if (index >= 0) {
scrollPosition = index
}
}
fun onSortMenuClicked() {
SortDialog.show(activity)
}
fun onBackPressed(): Boolean {
cdsSelectListener.onLostSelection()
return mediaServerModel.exitToParent()
}
override fun onStart() {
setSize(0)
isRefreshing = true
handler.post { updateList(emptyList()) }
}
override fun onUpdate(list: List<ContentEntity>) {
setSize(list.size)
handler.post { updateList(list) }
}
override fun onComplete() {
isRefreshing = false
}
private fun setSize(size: Int) {
subtitle = "[$size] ${mediaServerModel.path}"
}
private val scrollPositionTask = Runnable {
scrollPosition = contentListAdapter.list.indexOf(mediaServerModel.selectedEntity)
}
private fun updateList(list: List<ContentEntity>) {
val entity = mediaServerModel.selectedEntity
val oldList = contentListAdapter.list
val diff = DiffUtil.calculateDiff(DiffCallback(oldList, list), true)
contentListAdapter.list = list
contentListAdapter.setSelectedEntity(entity)
diff.dispatchUpdatesTo(contentListAdapter)
handler.removeCallbacks(scrollPositionTask)
handler.postDelayed(scrollPositionTask, SCROLL_POSITION_DELAY)
}
private class DiffCallback(
private val old: List<ContentEntity>,
private val new: List<ContentEntity>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = old.size
override fun getNewListSize(): Int = new.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
old[oldItemPosition].id == new[newItemPosition].id
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
old[oldItemPosition].name == new[newItemPosition].name
}
fun terminate() {
mediaServerModel.terminate()
mediaServerModel.initialize()
}
companion object {
private const val INVALID_POSITION = -1
private const val SCROLL_POSITION_DELAY = 200L
}
}
| mit | ff9ebde7108caf1e913d7b8614a4719b | 31.774194 | 94 | 0.68221 | 4.809467 | false | false | false | false |
googleads/googleads-mobile-android-examples | kotlin/admob/RewardedInterstitialExample/app/src/main/java/com/google/android/gms/example/rewardedinterstitialexample/AdDialogFragment.kt | 2 | 5087 | package com.google.android.gms.example.rewardedinterstitialexample
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
/** Number of seconds to count down before showing ads. */
private const val AD_COUNTER_TIME = 5L
/** A string that represents this class in the logcat. */
private const val AD_DIALOG_TAG = "AdDialogFragment"
/**
* A dialog fragment to inform the users about an upcoming interstitial video ad and let the user
* click the cancel button to skip the ad. This fragment inflates the dialog_ad.xml layout.
*/
class AdDialogFragment : DialogFragment() {
/** Delivers the events to the Main Activity when the user interacts with this dialog. */
private var listener: AdDialogInteractionListener? = null
/** A timer for counting down until showing ads. */
private var countDownTimer: CountDownTimer? = null
/** Number of remaining seconds while the count down timer runs. */
private var timeRemaining: Long = 0
/**
* Registers the callbacks to be invoked when the user interacts with this dialog. If there is no
* user interactions, the dialog is dismissed and the user will see a video interstitial ad.
*
* @param listener The callbacks that will run when the user interacts with this dialog.
*/
fun setAdDialogInteractionListener(listener: AdDialogInteractionListener) {
this.listener = listener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view: View = requireActivity().layoutInflater.inflate(R.layout.dialog_ad, null)
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
val builder: AlertDialog.Builder = AlertDialog.Builder(this.activity!!)
builder.setView(view)
val args = arguments
var rewardAmount = -1
var rewardType: String? = null
if (args != null) {
rewardAmount = args.getInt(REWARD_AMOUNT)
rewardType = args.getString(REWARD_TYPE)
}
if (rewardAmount > 0 && rewardType != null) {
builder.setTitle(getString(R.string.more_coins_text, rewardAmount, rewardType))
}
builder.setNegativeButton(
getString(R.string.negative_button_text)
) { _, _ -> dialog?.cancel() }
val dialog: Dialog = builder.create()
createTimer(AD_COUNTER_TIME, view)
return dialog
}
/**
* Creates the a timer to count down until the rewarded interstitial ad.
*
* @param time Number of seconds to count down.
* @param dialogView The view of this dialog for updating the remaining seconds count.
*/
private fun createTimer(time: Long, dialogView: View) {
val textView: TextView = dialogView.findViewById(R.id.timer)
countDownTimer = object : CountDownTimer(time * 1000, 50) {
override fun onTick(millisUnitFinished: Long) {
timeRemaining = millisUnitFinished / 1000 + 1
textView.text =
String.format(getString(R.string.video_starting_in_text), timeRemaining)
}
/**
* Called when the count down finishes and the user hasn't cancelled the dialog.
*/
override fun onFinish() {
dialog?.dismiss()
if (listener != null) {
Log.d(AD_DIALOG_TAG, "onFinish: Calling onShowAd().")
listener!!.onShowAd()
}
}
}
countDownTimer?.start()
}
/** Called when the user clicks the "No, Thanks" button or press the back button. */
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
if (listener != null) {
Log.d(AD_DIALOG_TAG, "onCancel: Calling onCancelAd().")
listener!!.onCancelAd()
}
}
/** Called when the fragment is destroyed. */
override fun onDestroy() {
super.onDestroy()
Log.d(AD_DIALOG_TAG, "onDestroy: Cancelling the timer.")
countDownTimer?.cancel()
countDownTimer = null
}
/** Callbacks when the user interacts with this dialog. */
interface AdDialogInteractionListener {
/** Called when the timer finishes without user's cancellation. */
fun onShowAd()
/** Called when the user clicks the "No, thanks" button or press the back button. */
fun onCancelAd()
}
companion object {
private const val REWARD_AMOUNT = "rewardAmount"
private const val REWARD_TYPE = "rewardType"
/**
* Creates an instance of the AdDialogFragment and sets reward information for its title.
*
* @param rewardAmount Number of coins rewarded by watching an ad.
* @param rewardType The unit of the reward amount. For example: coins, tokens, life, etc.
*/
fun newInstance(rewardAmount: Int, rewardType: String): AdDialogFragment {
val args = Bundle()
args.putInt(REWARD_AMOUNT, rewardAmount)
args.putString(REWARD_TYPE, rewardType)
val fragment = AdDialogFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 7897ffe8462f45e4d03d3dea40dabd91 | 33.605442 | 99 | 0.696285 | 4.400519 | false | false | false | false |
lydia-schiff/hella-renderscript | hella/src/main/java/com/lydiaschiff/hella/renderer/GreyscaleRsRenderer.kt | 1 | 1234 | package com.lydiaschiff.hella.renderer
import android.os.Build
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicColorMatrix
import androidx.annotation.RequiresApi
import com.lydiaschiff.hella.RsRenderer
/**
* Render an image allocation in greyscale.
*/
@RequiresApi(17)
class GreyscaleRsRenderer : RsRenderer {
private var greyscaleScript: ScriptIntrinsicColorMatrix? = null
override fun renderFrame(rs: RenderScript, inAlloc: Allocation, outAlloc: Allocation) {
val script = greyscaleScript ?: createScript(rs, inAlloc.element).also {
it.setGreyscale()
greyscaleScript = it
}
script.forEach(inAlloc, outAlloc)
}
override val name = "Greyscale with ScriptIntrinsicColorMatrix"
override val canRenderInPlace = true
companion object {
private fun createScript(rs: RenderScript, e: Element): ScriptIntrinsicColorMatrix {
return if (Build.VERSION.SDK_INT >= 19) {
ScriptIntrinsicColorMatrix.create(rs)
} else {
ScriptIntrinsicColorMatrix.create(rs, e)
}
}
}
} | mit | 2dc2fb9b5e5e3c487157fbdfcdc9cbf0 | 29.875 | 92 | 0.706645 | 4.520147 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/StatsFragment.kt | 1 | 14860 | package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.databinding.FragmentStatsBinding
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.android.habitica.extensions.setScaledPadding
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.helpers.UserStatComputer
import com.habitrpg.shared.habitica.models.tasks.Attribute
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.stats.BulkAllocateStatsDialog
import javax.inject.Inject
import kotlin.math.min
class StatsFragment : BaseMainFragment<FragmentStatsBinding>() {
override var binding: FragmentStatsBinding? = null
override fun createBinding(
inflater: LayoutInflater,
container: ViewGroup?
): FragmentStatsBinding {
return FragmentStatsBinding.inflate(inflater, container, false)
}
private var canAllocatePoints: Boolean = false
@Inject
lateinit var inventoryRepository: InventoryRepository
@Inject
lateinit var userViewModel: MainUserViewModel
private var totalStrength = 0
set(value) {
field = value
binding?.strengthStatsView?.totalValue = value
}
private var totalIntelligence = 0
set(value) {
field = value
binding?.intelligenceStatsView?.totalValue = value
}
private var totalConstitution = 0
set(value) {
field = value
binding?.constitutionStatsView?.totalValue = value
}
private var totalPerception = 0
set(value) {
field = value
binding?.perceptionStatsView?.totalValue = value
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
tutorialStepIdentifier = "stats"
tutorialTexts = listOf(getString(R.string.tutorial_stats))
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onDestroy() {
inventoryRepository.close()
super.onDestroy()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.leftSparklesView?.setImageBitmap(HabiticaIconsHelper.imageOfAttributeSparklesLeft())
binding?.rightSparklesView?.setImageBitmap(HabiticaIconsHelper.imageOfAttributeSparklesRight())
context?.let {
val color = it.getThemeColor(R.attr.colorPrimaryOffset)
binding?.distributeEvenlyHelpButton?.setImageBitmap(
HabiticaIconsHelper.imageOfInfoIcon(
color
)
)
binding?.distributeClassHelpButton?.setImageBitmap(
HabiticaIconsHelper.imageOfInfoIcon(
color
)
)
binding?.distributeTaskHelpButton?.setImageBitmap(
HabiticaIconsHelper.imageOfInfoIcon(
color
)
)
}
userViewModel.user.observe(viewLifecycleOwner) { user ->
if (user == null) return@observe
canAllocatePoints =
user.stats?.lvl ?: 0 >= 10 && user.stats?.points ?: 0 > 0
binding?.unlockAtLevel?.visibility =
if (user.stats?.lvl ?: 0 < 10) View.VISIBLE else View.GONE
updateStats(user)
updateAttributePoints(user)
}
binding?.distributeEvenlyButton?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
changeAutoAllocationMode(Stats.AUTO_ALLOCATE_FLAT)
}
}
binding?.distributeClassButton?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
changeAutoAllocationMode(Stats.AUTO_ALLOCATE_CLASSBASED)
}
}
binding?.distributeTaskButton?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
changeAutoAllocationMode(Stats.AUTO_ALLOCATE_TASKBASED)
}
}
binding?.automaticAllocationSwitch?.setOnCheckedChangeListener { _, isChecked ->
userRepository.updateUser("preferences.automaticAllocation", isChecked)
.subscribe({}, ExceptionHandler.rx())
}
binding?.strengthStatsView?.allocateAction = { allocatePoint(Attribute.STRENGTH) }
binding?.intelligenceStatsView?.allocateAction = { allocatePoint(Attribute.INTELLIGENCE) }
binding?.constitutionStatsView?.allocateAction = { allocatePoint(Attribute.CONSTITUTION) }
binding?.perceptionStatsView?.allocateAction = { allocatePoint(Attribute.PERCEPTION) }
binding?.distributeEvenlyHelpButton?.setOnClickListener { showHelpAlert(R.string.distribute_evenly_help) }
binding?.distributeClassHelpButton?.setOnClickListener { showHelpAlert(R.string.distribute_class_help) }
binding?.distributeTaskHelpButton?.setOnClickListener { showHelpAlert(R.string.distribute_task_help) }
binding?.statsAllocationButton?.setOnClickListener {
if (canAllocatePoints) {
showBulkAllocateDialog()
}
}
}
private fun showBulkAllocateDialog() {
context?.let { context ->
val dialog = BulkAllocateStatsDialog(context, HabiticaBaseApplication.userComponent)
dialog.show()
}
}
private fun changeAutoAllocationMode(allocationMode: String) {
compositeSubscription.add(
userRepository.updateUser(
"preferences.allocationMode",
allocationMode
).subscribe({}, ExceptionHandler.rx())
)
binding?.distributeEvenlyButton?.isChecked = allocationMode == Stats.AUTO_ALLOCATE_FLAT
binding?.distributeClassButton?.isChecked = allocationMode == Stats.AUTO_ALLOCATE_CLASSBASED
binding?.distributeTaskButton?.isChecked = allocationMode == Stats.AUTO_ALLOCATE_TASKBASED
}
private fun showHelpAlert(resourceId: Int) {
val alert = context?.let { HabiticaAlertDialog(it) }
alert?.setMessage(resourceId)
alert?.addOkButton()
alert?.show()
}
private fun allocatePoint(stat: Attribute) {
compositeSubscription.add(
userRepository.allocatePoint(stat).subscribe({ }, ExceptionHandler.rx())
)
}
private fun updateAttributePoints(user: User) {
val automaticAllocation = user.preferences?.automaticAllocation ?: false
binding?.automaticAllocationSwitch?.isChecked = automaticAllocation
binding?.autoAllocationModeWrapper?.visibility =
if (automaticAllocation) View.VISIBLE else View.GONE
val allocationMode = user.preferences?.allocationMode ?: ""
binding?.distributeEvenlyButton?.isChecked = allocationMode == Stats.AUTO_ALLOCATE_FLAT
binding?.distributeClassButton?.isChecked = allocationMode == Stats.AUTO_ALLOCATE_CLASSBASED
binding?.distributeTaskButton?.isChecked = allocationMode == Stats.AUTO_ALLOCATE_TASKBASED
val canDistributePoints = 0 < (user.stats?.points ?: 0) && 10 <= (user.stats?.lvl ?: 0)
if (10 <= (user.stats?.lvl ?: 0)) {
binding?.automaticAllocationSwitch?.visibility = View.VISIBLE
binding?.automaticAllocationSwitch?.visibility = View.VISIBLE
} else {
binding?.automaticAllocationSwitch?.visibility = View.GONE
binding?.automaticAllocationSwitch?.visibility = View.GONE
}
binding?.strengthStatsView?.canDistributePoints = canDistributePoints
binding?.intelligenceStatsView?.canDistributePoints = canDistributePoints
binding?.constitutionStatsView?.canDistributePoints = canDistributePoints
binding?.perceptionStatsView?.canDistributePoints = canDistributePoints
context?.let { context ->
if (canDistributePoints) {
val points = user.stats?.points ?: 0
binding?.numberOfPointsTextView?.text =
getString(R.string.points_to_allocate, points)
binding?.numberOfPointsTextView?.setTextColor(
ContextCompat.getColor(
context,
R.color.white
)
)
binding?.numberOfPointsTextView?.background =
ContextCompat.getDrawable(context, R.drawable.button_gray_100)
binding?.leftSparklesView?.visibility = View.VISIBLE
binding?.rightSparklesView?.visibility = View.VISIBLE
} else {
binding?.numberOfPointsTextView?.text = getString(R.string.no_points_to_allocate)
binding?.numberOfPointsTextView?.setTextColor(
ContextCompat.getColor(
context,
R.color.text_quad
)
)
binding?.numberOfPointsTextView?.setBackgroundColor(
ContextCompat.getColor(
context,
R.color.transparent
)
)
binding?.leftSparklesView?.visibility = View.GONE
binding?.rightSparklesView?.visibility = View.GONE
}
}
binding?.numberOfPointsTextView?.setScaledPadding(context, 18, 4, 18, 4)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun updateStats(user: User) {
val outfit = user.items?.gear?.equipped
val outfitList = ArrayList<String>()
outfit?.let { thisOutfit ->
outfitList.add(thisOutfit.armor)
outfitList.add(thisOutfit.back)
outfitList.add(thisOutfit.body)
outfitList.add(thisOutfit.eyeWear)
outfitList.add(thisOutfit.head)
outfitList.add(thisOutfit.headAccessory)
outfitList.add(thisOutfit.shield)
outfitList.add(thisOutfit.weapon)
}
compositeSubscription.add(
inventoryRepository.getEquipment(outfitList).firstElement()
.retry(1)
.subscribe(
{
val levelStat = min((user.stats?.lvl ?: 0) / 2.0f, 50f).toInt()
totalStrength = levelStat
totalIntelligence = levelStat
totalConstitution = levelStat
totalPerception = levelStat
binding?.strengthStatsView?.levelValue = levelStat
binding?.intelligenceStatsView?.levelValue = levelStat
binding?.constitutionStatsView?.levelValue = levelStat
binding?.perceptionStatsView?.levelValue = levelStat
totalStrength += user.stats?.buffs?.str?.toInt() ?: 0
totalIntelligence += user.stats?.buffs?._int?.toInt() ?: 0
totalConstitution += user.stats?.buffs?.con?.toInt() ?: 0
totalPerception += user.stats?.buffs?.per?.toInt() ?: 0
binding?.strengthStatsView?.buffValue = user.stats?.buffs?.str?.toInt() ?: 0
binding?.intelligenceStatsView?.buffValue =
user.stats?.buffs?._int?.toInt() ?: 0
binding?.constitutionStatsView?.buffValue =
user.stats?.buffs?.con?.toInt() ?: 0
binding?.perceptionStatsView?.buffValue =
user.stats?.buffs?.per?.toInt() ?: 0
totalStrength += user.stats?.strength ?: 0
totalIntelligence += user.stats?.intelligence ?: 0
totalConstitution += user.stats?.constitution ?: 0
totalPerception += user.stats?.per ?: 0
binding?.strengthStatsView?.allocatedValue = user.stats?.strength ?: 0
binding?.intelligenceStatsView?.allocatedValue =
user.stats?.intelligence ?: 0
binding?.constitutionStatsView?.allocatedValue =
user.stats?.constitution ?: 0
binding?.perceptionStatsView?.allocatedValue = user.stats?.per ?: 0
val userStatComputer = UserStatComputer()
val statsRows = userStatComputer.computeClassBonus(it, user)
var strength = 0
var intelligence = 0
var constitution = 0
var perception = 0
for (row in statsRows) {
if (row.javaClass == UserStatComputer.AttributeRow::class.java) {
val attributeRow = row as UserStatComputer.AttributeRow
strength += attributeRow.strVal.toInt()
intelligence += attributeRow.intVal.toInt()
constitution += attributeRow.conVal.toInt()
perception += attributeRow.perVal.toInt()
}
}
totalStrength += strength
totalIntelligence += intelligence
totalConstitution += constitution
totalPerception += perception
binding?.strengthStatsView?.equipmentValue = strength
binding?.intelligenceStatsView?.equipmentValue = intelligence
binding?.constitutionStatsView?.equipmentValue = constitution
binding?.perceptionStatsView?.equipmentValue = perception
},
ExceptionHandler.rx()
)
)
}
}
| gpl-3.0 | 0b47c4adfaa4d3c50920c0408cf52ff6 | 43.624625 | 114 | 0.609825 | 5.503704 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-existdb/main/uk/co/reecedunn/intellij/plugin/existdb/query/rest/EXistDBQueryProcessor.kt | 1 | 3599 | /*
* Copyright (C) 2018-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.existdb.query.rest
import com.intellij.lang.Language
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.vfs.VirtualFile
import org.apache.http.client.methods.RequestBuilder
import uk.co.reecedunn.intellij.plugin.core.navigation.ItemPresentationImpl
import uk.co.reecedunn.intellij.plugin.existdb.log.Log4JPattern
import uk.co.reecedunn.intellij.plugin.existdb.resources.EXistDBIcons
import uk.co.reecedunn.intellij.plugin.existdb.resources.EXistDBQueries
import uk.co.reecedunn.intellij.plugin.processor.log.LogViewProvider
import uk.co.reecedunn.intellij.plugin.processor.query.QueryServer
import uk.co.reecedunn.intellij.plugin.processor.query.UnsupportedQueryType
import uk.co.reecedunn.intellij.plugin.processor.query.connection.InstanceDetails
import uk.co.reecedunn.intellij.plugin.processor.query.http.HttpConnection
import uk.co.reecedunn.intellij.plugin.processor.run.RunnableQuery
import uk.co.reecedunn.intellij.plugin.processor.run.RunnableQueryProvider
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery
internal class EXistDBQueryProcessor(
private val baseUri: String,
private val connection: HttpConnection,
private val settings: InstanceDetails
) : RunnableQueryProvider,
LogViewProvider {
// region QueryProcessor
override val presentation: ItemPresentation
get() {
val version = createRunnableQuery(EXistDBQueries.Version, XQuery).run().results
val icon = when (version[0].value) {
"FusionDB" -> EXistDBIcons.Product.FusionDB
else -> EXistDBIcons.Product.EXistDB
}
return ItemPresentationImpl(icon, "${version[0].value} ${version[1].value}")
}
override val servers: List<QueryServer> = listOf(QueryServer(QueryServer.NONE, QueryServer.NONE))
// endregion
// region RunnableQueryProvider
override fun createRunnableQuery(query: VirtualFile, language: Language): RunnableQuery = when (language) {
XQuery -> {
val builder = RequestBuilder.post("$baseUri/db")
EXistDBQuery(builder, query, connection, settings)
}
else -> throw UnsupportedQueryType(language)
}
// endregion
// region LogViewProvider
override fun logs(): List<String> = createRunnableQuery(EXistDBQueries.Log.Logs, XQuery).run().results.map {
it.value as String
}
override fun log(name: String): List<Any> = createRunnableQuery(EXistDBQueries.Log.Log, XQuery).use { query ->
query.bindVariable("name", name, "xs:string")
val results = query.run().results
val pattern = Log4JPattern.create(results.first().value as String)
results.subList(1, results.size).map { pattern.parse(it.value as String) }
}
override fun defaultLogFile(logs: List<String>): String = "exist.log"
// endregion
// region Closeable
override fun close() = connection.close()
// endregion
}
| apache-2.0 | a22f9342fb76ee15a74ce31edbf0d651 | 39.438202 | 114 | 0.735204 | 4.127294 | false | false | false | false |
edibleday/teavm-gradle-plugin | src/main/kotlin/com/edibleday/TeaVMTask.kt | 1 | 4758 | /**
* Copyright 2015 SIA "Edible Day"
*
* 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.edibleday
import org.apache.maven.plugin.MojoExecutionException
import org.gradle.api.DefaultTask
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskAction
import org.teavm.tooling.RuntimeCopyOperation
import org.teavm.tooling.TeaVMTool
import org.teavm.tooling.sources.DirectorySourceFileProvider
import org.teavm.tooling.sources.JarSourceFileProvider
import java.io.File
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
import java.net.URLClassLoader
import java.util.*
open class TeaVMTask : DefaultTask() {
var installDirectory: String = File(project.buildDir, "teavm").absolutePath
var targetFileName: String = "app.js"
var mainPageIncluded: Boolean = true
var copySources: Boolean = false
var generateSourceMap: Boolean = false
var minified: Boolean = true
var runtime: RuntimeCopyOperation = RuntimeCopyOperation.SEPARATE
val log by lazy { TeaVMLoggerGlue(project.logger) }
@TaskAction fun compTeaVM() {
val tool = TeaVMTool()
val project = project
tool.targetDirectory = File(installDirectory)
tool.targetFileName = targetFileName
tool.isMainPageIncluded = mainPageIncluded
if (project.hasProperty("mainClassName") && project.property("mainClassName") != null) {
tool.mainClass = "${project.property("mainClassName")}"
} else throw TeaVMException("mainClassName not found!")
val addSrc = { f: File, tool: TeaVMTool ->
if (f.isFile) {
if (f.absolutePath.endsWith(".jar")) {
tool.addSourceFileProvider(JarSourceFileProvider(f))
} else {
tool.addSourceFileProvider(DirectorySourceFileProvider(f))
}
} else {
tool.addSourceFileProvider(DirectorySourceFileProvider(f))
}
}
val convention = project.convention.getPlugin(JavaPluginConvention::class.java)
convention
.sourceSets
.getByName(SourceSet.MAIN_SOURCE_SET_NAME)
.allSource
.srcDirs.forEach { addSrc(it, tool) }
project
.configurations
.getByName("teavmsources")
.files
.forEach { addSrc(it, tool) }
val cacheDirectory = File(project.buildDir, "teavm-cache")
cacheDirectory.mkdirs()
tool.cacheDirectory = cacheDirectory
tool.runtime = runtime
tool.isMinifying = minified
tool.log = log
tool.isSourceFilesCopied = copySources
tool.isSourceMapsFileGenerated = generateSourceMap
val classLoader = prepareClassLoader()
try {
tool.classLoader = classLoader
tool.generate()
} finally {
try {
classLoader.close()
} catch (ignored: IOException) {
}
}
}
private fun prepareClassLoader(): URLClassLoader {
try {
val urls = ArrayList<URL>()
val classpath = StringBuilder()
for (file in project.configurations.getByName("runtime").files) {
if (classpath.length > 0) {
classpath.append(':')
}
classpath.append(file.path)
urls.add(file.toURI().toURL())
}
if (classpath.length > 0) {
classpath.append(':')
}
classpath.append(File(project.buildDir, "classes/main").path)
urls.add(File(project.buildDir, "classes/main").toURI().toURL())
classpath.append(':')
classpath.append(File(project.buildDir, "resources/main").path)
urls.add(File(project.buildDir, "resources/main").toURI().toURL())
return URLClassLoader(urls.toArray<URL>(arrayOfNulls<URL>(urls.size)), javaClass.classLoader)
} catch (e: MalformedURLException) {
throw MojoExecutionException("Error gathering classpath information", e)
}
}
}
| apache-2.0 | ff95e63aa37fee78ccf93f03b6dbe868 | 32.985714 | 105 | 0.63409 | 4.646484 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/ui/captcha/BrowserActionActivity.kt | 1 | 28593 | package exh.ui.captcha
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.webkit.*
import com.github.salomonbrys.kotson.get
import com.github.salomonbrys.kotson.string
import com.google.gson.JsonParser
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import kotlinx.android.synthetic.main.eh_activity_captcha.*
import okhttp3.*
import rx.Single
import rx.schedulers.Schedulers
import timber.log.Timber
import uy.kohesive.injekt.injectLazy
import java.net.URL
import java.util.*
import android.view.MotionEvent
import android.os.SystemClock
import com.afollestad.materialdialogs.MaterialDialog
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.source.online.HttpSource
import exh.source.DelegatedHttpSource
import exh.util.melt
import rx.Observable
import java.io.Serializable
import kotlin.collections.HashMap
class BrowserActionActivity : AppCompatActivity() {
private val sourceManager: SourceManager by injectLazy()
private val preferencesHelper: PreferencesHelper by injectLazy()
private val networkHelper: NetworkHelper by injectLazy()
val httpClient = networkHelper.client
private val jsonParser = JsonParser()
private var currentLoopId: String? = null
private var validateCurrentLoopId: String? = null
private var strictValidationStartTime: Long? = null
lateinit var credentialsObservable: Observable<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(eu.kanade.tachiyomi.R.layout.eh_activity_captcha)
val sourceId = intent.getLongExtra(SOURCE_ID_EXTRA, -1)
val originalSource = if(sourceId != -1L) sourceManager.get(sourceId) else null
val source = if(originalSource != null) {
originalSource as? ActionCompletionVerifier
?: run {
(originalSource as? HttpSource)?.let {
NoopActionCompletionVerifier(it)
}
}
} else null
val headers = ((source as? HttpSource)?.headers?.toMultimap()?.mapValues {
it.value.joinToString(",")
} ?: emptyMap()) + (intent.getSerializableExtra(HEADERS_EXTRA) as? HashMap<String, String> ?: emptyMap())
val cookies: HashMap<String, String>?
= intent.getSerializableExtra(COOKIES_EXTRA) as? HashMap<String, String>
val script: String? = intent.getStringExtra(SCRIPT_EXTRA)
val url: String? = intent.getStringExtra(URL_EXTRA)
val actionName = intent.getStringExtra(ACTION_NAME_EXTRA)
val verifyComplete = if(source != null) {
source::verifyComplete!!
} else intent.getSerializableExtra(VERIFY_LAMBDA_EXTRA) as? (String) -> Boolean
if(verifyComplete == null || url == null) {
finish()
return
}
val actionStr = actionName ?: "Solve captcha"
toolbar.title = if(source != null) {
"${source.name}: $actionStr"
} else actionStr
val parsedUrl = URL(url)
val cm = CookieManager.getInstance()
cookies?.forEach { (t, u) ->
val cookieString = t + "=" + u + "; domain=" + parsedUrl.host
cm.setCookie(url, cookieString)
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
CookieSyncManager.createInstance(this).sync()
webview.settings.javaScriptEnabled = true
webview.settings.domStorageEnabled = true
headers.entries.find { it.key.equals("user-agent", true) }?.let {
webview.settings.userAgentString = it.value
}
var loadedInners = 0
webview.webChromeClient = object : WebChromeClient() {
override fun onJsAlert(view: WebView?, url: String?, message: String, result: JsResult): Boolean {
if(message.startsWith("exh-")) {
loadedInners++
// Wait for both inner scripts to be loaded
if(loadedInners >= 2) {
// Attempt to autosolve captcha
if(preferencesHelper.eh_autoSolveCaptchas().getOrDefault()
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webview.post {
// 10 seconds to auto-solve captcha
strictValidationStartTime = System.currentTimeMillis() + 1000 * 10
beginSolveLoop()
beginValidateCaptchaLoop()
webview.evaluateJavascript(SOLVE_UI_SCRIPT_HIDE) {
webview.evaluateJavascript(SOLVE_UI_SCRIPT_SHOW, null)
}
}
}
}
result.confirm()
return true
}
return false
}
}
webview.webViewClient = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if(actionName == null && preferencesHelper.eh_autoSolveCaptchas().getOrDefault()) {
// Fetch auto-solve credentials early for speed
credentialsObservable = httpClient.newCall(Request.Builder()
// Rob demo credentials
.url("https://speech-to-text-demo.ng.bluemix.net/api/v1/credentials")
.build())
.asObservableSuccess()
.subscribeOn(Schedulers.io())
.map {
val json = jsonParser.parse(it.body()!!.string())
it.close()
json["token"].string
}.melt()
webview.addJavascriptInterface(this@BrowserActionActivity, "exh")
AutoSolvingWebViewClient(this, verifyComplete, script, headers)
} else {
HeadersInjectingWebViewClient(this, verifyComplete, script, headers)
}
} else {
BasicWebViewClient(this, verifyComplete, script)
}
webview.loadUrl(url, headers)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun captchaSolveFail() {
currentLoopId = null
validateCurrentLoopId = null
Timber.e(IllegalStateException("Captcha solve failure!"))
runOnUiThread {
webview.evaluateJavascript(SOLVE_UI_SCRIPT_HIDE, null)
MaterialDialog.Builder(this)
.title("Captcha solve failure")
.content("Failed to auto-solve the captcha!")
.cancelable(true)
.canceledOnTouchOutside(true)
.positiveText("Ok")
.show()
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@JavascriptInterface
fun callback(result: String?, loopId: String, stage: Int) {
if(loopId != currentLoopId) return
when(stage) {
STAGE_CHECKBOX -> {
if(result!!.toBoolean()) {
webview.postDelayed({
getAudioButtonLocation(loopId)
}, 250)
} else {
webview.postDelayed({
doStageCheckbox(loopId)
}, 250)
}
}
STAGE_GET_AUDIO_BTN_LOCATION -> {
if(result != null) {
val splitResult = result.split(" ").map { it.toFloat() }
val origX = splitResult[0]
val origY = splitResult[1]
val iw = splitResult[2]
val ih = splitResult[3]
val x = webview.x + origX / iw * webview.width
val y = webview.y + origY / ih * webview.height
Timber.d("Found audio button coords: %f %f", x, y)
simulateClick(x + 50, y + 50)
webview.post {
doStageDownloadAudio(loopId)
}
} else {
webview.postDelayed({
getAudioButtonLocation(loopId)
}, 250)
}
}
STAGE_DOWNLOAD_AUDIO -> {
if(result != null) {
Timber.d("Got audio URL: $result")
performRecognize(result)
.observeOn(Schedulers.io())
.subscribe ({
Timber.d("Got audio transcript: $it")
webview.post {
typeResult(loopId, it!!
.replace(TRANSCRIPT_CLEANER_REGEX, "")
.replace(SPACE_DEDUPE_REGEX, " ")
.trim())
}
}, {
captchaSolveFail()
})
} else {
webview.postDelayed({
doStageDownloadAudio(loopId)
}, 250)
}
}
STAGE_TYPE_RESULT -> {
if(result!!.toBoolean()) {
// Fail if captcha still not solved after 1.5s
strictValidationStartTime = System.currentTimeMillis() + 1500
} else {
captchaSolveFail()
}
}
}
}
fun performRecognize(url: String): Single<String> {
return credentialsObservable.flatMap { token ->
httpClient.newCall(Request.Builder()
.url(url)
.build()).asObservableSuccess().map {
token to it
}
}.flatMap { (token, response) ->
val audioFile = response.body()!!.bytes()
httpClient.newCall(Request.Builder()
.url(HttpUrl.parse("https://stream.watsonplatform.net/speech-to-text/api/v1/recognize")!!
.newBuilder()
.addQueryParameter("watson-token", token)
.build())
.post(MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("jsonDescription", RECOGNIZE_JSON)
.addFormDataPart("audio.mp3",
"audio.mp3",
RequestBody.create(MediaType.parse("audio/mp3"), audioFile))
.build())
.build()).asObservableSuccess()
}.map { response ->
jsonParser.parse(response.body()!!.string())["results"][0]["alternatives"][0]["transcript"].string.trim()
}.toSingle()
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun doStageCheckbox(loopId: String) {
if(loopId != currentLoopId) return
webview.evaluateJavascript("""
(function() {
$CROSS_WINDOW_SCRIPT_OUTER
let exh_cframe = document.querySelector('iframe[role=presentation][name|=a]');
if(exh_cframe != null) {
cwmExec(exh_cframe, `
let exh_cb = document.getElementsByClassName('recaptcha-checkbox-checkmark')[0];
if(exh_cb != null) {
exh_cb.click();
return "true";
} else {
return "false";
}
`, function(result) {
exh.callback(result, '$loopId', $STAGE_CHECKBOX);
});
} else {
exh.callback("false", '$loopId', $STAGE_CHECKBOX);
}
})();
""".trimIndent().replace("\n", ""), null)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun getAudioButtonLocation(loopId: String) {
webview.evaluateJavascript("""
(function() {
$CROSS_WINDOW_SCRIPT_OUTER
let exh_bframe = document.querySelector("iframe[title='recaptcha challenge'][name|=c]");
if(exh_bframe != null) {
let bfb = exh_bframe.getBoundingClientRect();
let iw = window.innerWidth;
let ih = window.innerHeight;
if(bfb.left < 0 || bfb.top < 0) {
exh.callback(null, '$loopId', $STAGE_GET_AUDIO_BTN_LOCATION);
} else {
cwmExec(exh_bframe, ` let exh_ab = document.getElementById("recaptcha-audio-button");
if(exh_ab != null) {
let bounds = exh_ab.getBoundingClientRect();
return (${'$'}{bfb.left} + bounds.left) + " " + (${'$'}{bfb.top} + bounds.top) + " " + ${'$'}{iw} + " " + ${'$'}{ih};
} else {
return null;
}
`, function(result) {
exh.callback(result, '$loopId', $STAGE_GET_AUDIO_BTN_LOCATION);
});
}
} else {
exh.callback(null, '$loopId', $STAGE_GET_AUDIO_BTN_LOCATION);
}
})();
""".trimIndent().replace("\n", ""), null)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun doStageDownloadAudio(loopId: String) {
webview.evaluateJavascript("""
(function() {
$CROSS_WINDOW_SCRIPT_OUTER
let exh_bframe = document.querySelector("iframe[title='recaptcha challenge'][name|=c]");
if(exh_bframe != null) {
cwmExec(exh_bframe, `
let exh_as = document.getElementById("audio-source");
if(exh_as != null) {
return exh_as.src;
} else {
return null;
}
`, function(result) {
exh.callback(result, '$loopId', $STAGE_DOWNLOAD_AUDIO);
});
} else {
exh.callback(null, '$loopId', $STAGE_DOWNLOAD_AUDIO);
}
})();
""".trimIndent().replace("\n", ""), null)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun typeResult(loopId: String, result: String) {
webview.evaluateJavascript("""
(function() {
$CROSS_WINDOW_SCRIPT_OUTER
let exh_bframe = document.querySelector("iframe[title='recaptcha challenge'][name|=c]");
if(exh_bframe != null) {
cwmExec(exh_bframe, `
let exh_as = document.getElementById("audio-response");
let exh_vb = document.getElementById("recaptcha-verify-button");
if(exh_as != null && exh_vb != null) {
exh_as.value = "$result";
exh_vb.click();
return "true";
} else {
return "false";
}
`, function(result) {
exh.callback(result, '$loopId', $STAGE_TYPE_RESULT);
});
} else {
exh.callback("false", '$loopId', $STAGE_TYPE_RESULT);
}
})();
""".trimIndent().replace("\n", ""), null)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun beginSolveLoop() {
val loopId = UUID.randomUUID().toString()
currentLoopId = loopId
doStageCheckbox(loopId)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@JavascriptInterface
fun validateCaptchaCallback(result: Boolean, loopId: String) {
if(loopId != validateCurrentLoopId) return
if(result) {
Timber.d("Captcha solved!")
webview.post {
webview.evaluateJavascript(SOLVE_UI_SCRIPT_HIDE, null)
}
val asbtn = intent.getStringExtra(ASBTN_EXTRA)
if(asbtn != null) {
webview.post {
webview.evaluateJavascript("(function() {document.querySelector('$asbtn').click();})();", null)
}
}
} else {
val savedStrictValidationStartTime = strictValidationStartTime
if(savedStrictValidationStartTime != null
&& System.currentTimeMillis() > savedStrictValidationStartTime) {
captchaSolveFail()
} else {
webview.postDelayed({
runValidateCaptcha(loopId)
}, 250)
}
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun runValidateCaptcha(loopId: String) {
if(loopId != validateCurrentLoopId) return
webview.evaluateJavascript("""
(function() {
$CROSS_WINDOW_SCRIPT_OUTER
let exh_cframe = document.querySelector('iframe[role=presentation][name|=a]');
if(exh_cframe != null) {
cwmExec(exh_cframe, `
let exh_cb = document.querySelector(".recaptcha-checkbox[aria-checked=true]");
if(exh_cb != null) {
return true;
} else {
return false;
}
`, function(result) {
exh.validateCaptchaCallback(result, '$loopId');
});
} else {
exh.validateCaptchaCallback(false, '$loopId');
}
})();
""".trimIndent().replace("\n", ""), null)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun beginValidateCaptchaLoop() {
val loopId = UUID.randomUUID().toString()
validateCurrentLoopId = loopId
runValidateCaptcha(loopId)
}
private fun simulateClick(x: Float, y: Float) {
val downTime = SystemClock.uptimeMillis()
val eventTime = SystemClock.uptimeMillis()
val properties = arrayOfNulls<MotionEvent.PointerProperties>(1)
val pp1 = MotionEvent.PointerProperties().apply {
id = 0
toolType = MotionEvent.TOOL_TYPE_FINGER
}
properties[0] = pp1
val pointerCoords = arrayOfNulls<MotionEvent.PointerCoords>(1)
val pc1 = MotionEvent.PointerCoords().apply {
this.x = x
this.y = y
pressure = 1f
size = 1f
}
pointerCoords[0] = pc1
var motionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, 1, properties, pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0)
dispatchTouchEvent(motionEvent)
motionEvent.recycle()
motionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, 1, properties, pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0)
dispatchTouchEvent(motionEvent)
motionEvent.recycle()
}
companion object {
const val VERIFY_LAMBDA_EXTRA = "verify_lambda_extra"
const val SOURCE_ID_EXTRA = "source_id_extra"
const val COOKIES_EXTRA = "cookies_extra"
const val SCRIPT_EXTRA = "script_extra"
const val URL_EXTRA = "url_extra"
const val ASBTN_EXTRA = "asbtn_extra"
const val ACTION_NAME_EXTRA = "action_name_extra"
const val HEADERS_EXTRA = "headers_extra"
const val STAGE_CHECKBOX = 0
const val STAGE_GET_AUDIO_BTN_LOCATION = 1
const val STAGE_DOWNLOAD_AUDIO = 2
const val STAGE_TYPE_RESULT = 3
val CROSS_WINDOW_SCRIPT_OUTER = """
function cwmExec(element, code, cb) {
console.log(">>> [CWM-Outer] Running: " + code);
let runId = Math.random();
if(cb != null) {
let listener;
listener = function(event) {
if(typeof event.data === "string" && event.data.startsWith("exh-")) {
let response = JSON.parse(event.data.substring(4));
if(response.id === runId) {
cb(response.result);
window.removeEventListener('message', listener);
console.log(">>> [CWM-Outer] Finished: " + response.id + " ==> " + response.result);
}
}
};
window.addEventListener('message', listener, false);
}
let runRequest = { id: runId, code: code };
element.contentWindow.postMessage("exh-" + JSON.stringify(runRequest), "*");
}
""".trimIndent().replace("\n", "")
val CROSS_WINDOW_SCRIPT_INNER = """
window.addEventListener('message', function(event) {
if(typeof event.data === "string" && event.data.startsWith("exh-")) {
let request = JSON.parse(event.data.substring(4));
console.log(">>> [CWM-Inner] Incoming: " + request.id);
let result = eval("(function() {" + request.code + "})();");
let response = { id: request.id, result: result };
console.log(">>> [CWM-Inner] Outgoing: " + response.id + " ==> " + response.result);
event.source.postMessage("exh-" + JSON.stringify(response), event.origin);
}
}, false);
console.log(">>> [CWM-Inner] Loaded!");
alert("exh-");
""".trimIndent()
val SOLVE_UI_SCRIPT_SHOW = """
(function() {
let exh_overlay = document.createElement("div");
exh_overlay.id = "exh_overlay";
exh_overlay.style.zIndex = 2000000001;
exh_overlay.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
exh_overlay.style.position = "fixed";
exh_overlay.style.top = 0;
exh_overlay.style.left = 0;
exh_overlay.style.width = "100%";
exh_overlay.style.height = "100%";
exh_overlay.style.pointerEvents = "none";
document.body.appendChild(exh_overlay);
let exh_otext = document.createElement("div");
exh_otext.id = "exh_otext";
exh_otext.style.zIndex = 2000000002;
exh_otext.style.position = "fixed";
exh_otext.style.top = "50%";
exh_otext.style.left = 0;
exh_otext.style.transform = "translateY(-50%)";
exh_otext.style.color = "white";
exh_otext.style.fontSize = "25pt";
exh_otext.style.pointerEvents = "none";
exh_otext.style.width = "100%";
exh_otext.style.textAlign = "center";
exh_otext.textContent = "Solving captcha..."
document.body.appendChild(exh_otext);
})();
""".trimIndent()
val SOLVE_UI_SCRIPT_HIDE = """
(function() {
let exh_overlay = document.getElementById("exh_overlay");
let exh_otext = document.getElementById("exh_otext");
if(exh_overlay != null) exh_overlay.remove();
if(exh_otext != null) exh_otext.remove();
})();
""".trimIndent()
val RECOGNIZE_JSON = """
{
"part_content_type": "audio/mp3",
"keywords": [],
"profanity_filter": false,
"max_alternatives": 1,
"speaker_labels": false,
"firstReadyInSession": false,
"preserveAdaptation": false,
"timestamps": false,
"inactivity_timeout": 30,
"word_confidence": false,
"audioMetrics": false,
"latticeGeneration": true,
"customGrammarWords": [],
"action": "recognize"
}
""".trimIndent()
val TRANSCRIPT_CLEANER_REGEX = Regex("[^0-9a-zA-Z_ -]")
val SPACE_DEDUPE_REGEX = Regex(" +")
private fun baseIntent(context: Context) =
Intent(context, BrowserActionActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
fun launchCaptcha(context: Context,
source: ActionCompletionVerifier,
cookies: Map<String, String>,
script: String?,
url: String,
autoSolveSubmitBtnSelector: String? = null) {
val intent = baseIntent(context).apply {
putExtra(SOURCE_ID_EXTRA, source.id)
putExtra(COOKIES_EXTRA, HashMap(cookies))
putExtra(SCRIPT_EXTRA, script)
putExtra(URL_EXTRA, url)
putExtra(ASBTN_EXTRA, autoSolveSubmitBtnSelector)
}
context.startActivity(intent)
}
fun launchUniversal(context: Context,
source: HttpSource,
url: String) {
val intent = baseIntent(context).apply {
putExtra(SOURCE_ID_EXTRA, source.id)
putExtra(URL_EXTRA, url)
}
context.startActivity(intent)
}
fun launchUniversal(context: Context,
sourceId: Long,
url: String) {
val intent = baseIntent(context).apply {
putExtra(SOURCE_ID_EXTRA, sourceId)
putExtra(URL_EXTRA, url)
}
context.startActivity(intent)
}
fun launchAction(context: Context,
completionVerifier: ActionCompletionVerifier,
script: String?,
url: String,
actionName: String) {
val intent = baseIntent(context).apply {
putExtra(SOURCE_ID_EXTRA, completionVerifier.id)
putExtra(SCRIPT_EXTRA, script)
putExtra(URL_EXTRA, url)
putExtra(ACTION_NAME_EXTRA, actionName)
}
context.startActivity(intent)
}
fun launchAction(context: Context,
completionVerifier: (String) -> Boolean,
script: String?,
url: String,
actionName: String,
headers: Map<String, String>? = emptyMap()) {
val intent = baseIntent(context).apply {
putExtra(HEADERS_EXTRA, HashMap(headers))
putExtra(VERIFY_LAMBDA_EXTRA, completionVerifier as Serializable)
putExtra(SCRIPT_EXTRA, script)
putExtra(URL_EXTRA, url)
putExtra(ACTION_NAME_EXTRA, actionName)
}
context.startActivity(intent)
}
}
}
class NoopActionCompletionVerifier(private val source: HttpSource): DelegatedHttpSource(source),
ActionCompletionVerifier {
override val versionId get() = source.versionId
override val lang: String get() = source.lang
override fun verifyComplete(url: String) = false
}
interface ActionCompletionVerifier : Source {
fun verifyComplete(url: String): Boolean
}
| apache-2.0 | 64501fd5e609d29be2e11b2e71dbba2a | 39.442716 | 149 | 0.504844 | 4.985702 | false | false | false | false |
rabsouza/bgscore | app/src/androidTest/java/br/com/battista/bgscore/helper/DrawableMatcher.kt | 1 | 2207 | package br.com.battista.bgscore.helper
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
class DrawableMatcher internal constructor(private val expectedId: Int) : TypeSafeMatcher<View>(View::class.java) {
private lateinit var resourceName: String
init {
resourceName = ""
}
override fun matchesSafely(target: View): Boolean {
if (target !is ImageView) {
return false
}
if (expectedId == EMPTY) {
return target.drawable == null
}
if (expectedId == ANY) {
return target.drawable != null
}
val resources = target.getContext().resources
val expectedDrawable = resources.getDrawable(expectedId)
resourceName = resources.getResourceEntryName(expectedId)
if (expectedDrawable == null) {
return false
}
val bitmap = getBitmap(target.drawable)
val otherBitmap = getBitmap(expectedDrawable)
return bitmap.sameAs(otherBitmap)
}
private fun getBitmap(drawable: Drawable): Bitmap {
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
override fun describeTo(description: Description) {
description.appendText("with drawable from resource id: ")
description.appendValue(expectedId)
if (resourceName.isNotBlank()) {
description.appendText("[")
description.appendText(resourceName)
description.appendText("]")
}
}
companion object {
internal val EMPTY = -1
internal val ANY = -2
fun withDrawable(resourceId: Int): Matcher<View> {
return DrawableMatcher(resourceId)
}
fun noDrawable(): Matcher<View> {
return DrawableMatcher(-1)
}
}
}
| gpl-3.0 | 56e7d4923b66ee4846a3d6e80d69af90 | 28.824324 | 116 | 0.649751 | 5.073563 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandPos.kt | 1 | 1048 | package nl.sugcube.dirtyarrows.command
import nl.sugcube.dirtyarrows.Broadcast
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.util.sendFormattedMessage
import nl.sugcube.dirtyarrows.util.toCoordinateString
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* @author SugarCaney
*/
open class CommandPos(val id: Int) : SubCommand<DirtyArrows>(
name = "pos$id",
usage = "/da pos$id",
argumentCount = 0,
description = "Set region position $id."
) {
init {
addPermissions("dirtyarrows.admin")
}
override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) {
val player = sender as? Player ?: error("Sender is not a player.")
val location = player.location
plugin.regionManager.setSelection(id, location)
sender.sendFormattedMessage(Broadcast.POSITION_SET.format(id, location.toCoordinateString()))
}
override fun assertSender(sender: CommandSender) = sender is Player
} | gpl-3.0 | 1cfcd02f406eda9efb899b42bf0cd019 | 31.78125 | 101 | 0.721374 | 4.312757 | false | true | false | false |
walleth/walleth | app/src/main/java/org/walleth/transactions/TransactionViewHolder.kt | 1 | 4111 | package org.walleth.transactions
import android.text.format.DateUtils
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.transaction_item.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.kethereum.extensions.transactions.getTokenRelevantTo
import org.kethereum.extensions.transactions.getTokenRelevantValue
import org.ligi.kaxt.setVisibility
import org.walleth.R
import org.walleth.chains.ChainInfoProvider
import org.walleth.data.AppDatabase
import org.walleth.data.addresses.resolveNameWithFallback
import org.walleth.data.config.Settings
import org.walleth.data.exchangerate.ExchangeRateProvider
import org.walleth.data.tokens.getRootToken
import org.walleth.data.transactions.TransactionEntity
import org.walleth.valueview.ValueViewController
class TransactionViewHolder(itemView: View,
private val direction: TransactionAdapterDirection,
val chainInfoProvider: ChainInfoProvider,
private val exchangeRateProvider: ExchangeRateProvider,
val settings: Settings) : RecyclerView.ViewHolder(itemView) {
private val amountViewModel by lazy {
ValueViewController(itemView.difference, exchangeRateProvider, settings)
}
fun bind(transactionWithState: TransactionEntity?, appDatabase: AppDatabase) {
if (transactionWithState != null) {
val transaction = transactionWithState.transaction
val relevantAddress = if (direction == TransactionAdapterDirection.INCOMING) {
transaction.from
} else {
transaction.getTokenRelevantTo() ?: transaction.to
}
val tokenValue = transaction.getTokenRelevantValue()
if (tokenValue != null) {
val tokenAddress = transaction.to
if (tokenAddress != null) {
GlobalScope.launch(Dispatchers.Main) {
appDatabase.tokens.forAddress(tokenAddress)?.let {
amountViewModel.setValue(tokenValue, it)
}
}
}
} else {
GlobalScope.launch(Dispatchers.Main) {
amountViewModel.setValue(transaction.value, chainInfoProvider.getCurrent().getRootToken())
}
}
relevantAddress?.let {
GlobalScope.launch(Dispatchers.Main) {
itemView.address.text = appDatabase.addressBook.resolveNameWithFallback(it)
}
}
itemView.transaction_err.setVisibility(transactionWithState.transactionState.error != null)
if (transactionWithState.transactionState.error != null) {
itemView.transaction_err.text = transactionWithState.transactionState.error
}
val epochMillis = (transaction.creationEpochSecond ?: 0) * 1000L
val context = itemView.context
itemView.date.text = DateUtils.getRelativeDateTimeString(context, epochMillis,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
0
)
itemView.date.setVisibility(false)
itemView.address.setVisibility(false)
itemView.transaction_state_indicator.setImageResource(
when {
!transactionWithState.transactionState.isPending -> R.drawable.ic_lock_black_24dp
transactionWithState.signatureData == null -> R.drawable.ic_lock_open_black_24dp
else -> R.drawable.ic_lock_outline_24dp
}
)
itemView.isClickable = true
itemView.setOnClickListener {
transactionWithState.hash.let {
context.startActivity(context.getTransactionActivityIntentForHash(it))
}
}
}
}
} | gpl-3.0 | 6421bca140bc2c551c28bc7212f89bfb | 40.12 | 110 | 0.633909 | 5.555405 | false | false | false | false |
zlyne0/colonization | core/src/net/sf/freecol/common/model/ai/missions/workerrequest/ColonistsPurchaseRecommendations.kt | 1 | 4907 | package net.sf.freecol.common.model.ai.missions.workerrequest
import net.sf.freecol.common.model.Game
import net.sf.freecol.common.model.Unit
import net.sf.freecol.common.model.ai.MapTileDebugInfo
import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer
import net.sf.freecol.common.model.ai.missions.TransportUnitMission
import net.sf.freecol.common.model.ai.missions.foreachMission
import net.sf.freecol.common.model.ai.missions.transportunit.TransportUnitRequestMission
import net.sf.freecol.common.model.ai.missions.workerrequest.WorkerRequestLogger.logger
import net.sf.freecol.common.model.player.Player
import promitech.colonization.ai.score.ScoreableObjectsList
class ColonistsPurchaseRecommendations(
val game: Game,
val player: Player,
val playerMissionContainer: PlayerMissionsContainer
) {
fun buyRecommendations(
workerPlaceCalculator: ColonyWorkerRequestPlaceCalculator,
entryPointTurnRange: EntryPointTurnRange,
transporter: Unit
) {
val recommendations = generateRecommendations(workerPlaceCalculator, entryPointTurnRange, transporter)
for (buyRecommendation in recommendations) {
if (player.europe.canAiBuyUnit(buyRecommendation.workerType(), player.gold)) {
val newUnit = player.europe.buyUnitByAI(buyRecommendation.workerType())
val mission = ColonyWorkerMission(buyRecommendation.location, newUnit, buyRecommendation.goodsType)
playerMissionContainer.addMission(mission)
val transportUnitRequestMission = TransportUnitRequestMission(game.turn, mission.unit, mission.tile)
playerMissionContainer.addMission(mission, transportUnitRequestMission)
}
}
}
fun generateRecommendations(
workerPlaceCalculator: ColonyWorkerRequestPlaceCalculator,
entryPointTurnRange: EntryPointTurnRange,
transporter: Unit
): ScoreableObjectsList<WorkerRequestScoreValue> {
val tileScore = workerPlaceCalculator.score(playerMissionContainer)
val scorePolicy = ScorePolicy.WorkerPriceToValue(entryPointTurnRange, player)
scorePolicy.calculateScore(tileScore)
val transporterCapacity = transporterCapacity(transporter)
val buyRecomendations = createList(player.gold, transporterCapacity, tileScore)
return buyRecomendations
}
private fun transporterCapacity(transporter: Unit): Int {
var capacity: Int = transporter.freeUnitsSlots()
playerMissionContainer.foreachMission(TransportUnitMission::class.java, { transportUnitMission ->
if (transportUnitMission.isCarrier(transporter)) {
capacity -= transportUnitMission.spaceTakenByUnits()
}
})
return capacity
}
private fun createList(
gold: Int, navyCargoCapacity: Int, workerRequests: ScoreableObjectsList<WorkerRequestScoreValue>
): ScoreableObjectsList<WorkerRequestScoreValue> {
if (navyCargoCapacity <= 0) {
logger.debug("player[%s].PurchaseColonists no navy cargo capacity", player.id)
return ScoreableObjectsList<WorkerRequestScoreValue>(0)
}
var budget = gold
val list = ScoreableObjectsList<WorkerRequestScoreValue>(navyCargoCapacity)
for (workerRequest in workerRequests) {
if (list.size() >= navyCargoCapacity) {
break
}
if (!player.europe.isUnitAvailableToBuyByAI(workerRequest.workerType())) {
logger.debug("PurchaseColonists.unitType[%s] not available to buy in europe", workerRequest.workerType())
continue
}
val unitPrice = player.europe.aiUnitPrice(workerRequest.workerType())
if (unitPrice > budget) {
if (logger.isDebug()) {
logger.debug("PurchaseColonists.unitType[%s].price[%s] not afforable for player[%s]",
workerRequest.workerType(), unitPrice, player.id
)
}
continue
}
budget -= unitPrice
list.add(workerRequest)
}
return list
}
fun printToLog(workers: ScoreableObjectsList<WorkerRequestScoreValue>, entryPointTurnRange: EntryPointTurnRange) {
if (logger.isDebug) {
var str = "worker recomendations size: ${workers.size()}\n"
for (worker in workers) {
str += worker.toPrettyString(player, entryPointTurnRange) + "\n"
}
logger.debug(str)
}
}
fun printToMap(buyRecomendations: ScoreableObjectsList<WorkerRequestScoreValue>, mapDebugView: MapTileDebugInfo) {
for (worker in buyRecomendations) {
mapDebugView.strIfNull(worker.location.x, worker.location.y, worker.score.toString())
}
}
} | gpl-2.0 | 758135cdc2605f0878a24a3ffceb711d | 42.821429 | 121 | 0.688608 | 4.660019 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsBrowseScreen.kt | 1 | 3666 | package eu.kanade.presentation.more.settings.screen
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.fragment.app.FragmentActivity
import eu.kanade.domain.base.BasePreferences
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.presentation.more.settings.Preference
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.extension.ExtensionUpdateJob
import eu.kanade.tachiyomi.util.system.AuthenticatorUtil.authenticate
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class SettingsBrowseScreen : SearchableSettings {
@ReadOnlyComposable
@Composable
@StringRes
override fun getTitleRes() = R.string.browse
@Composable
override fun getPreferences(): List<Preference> {
val context = LocalContext.current
val sourcePreferences = remember { Injekt.get<SourcePreferences>() }
val preferences = remember { Injekt.get<BasePreferences>() }
return listOf(
Preference.PreferenceGroup(
title = stringResource(R.string.label_sources),
preferenceItems = listOf(
Preference.PreferenceItem.SwitchPreference(
pref = sourcePreferences.duplicatePinnedSources(),
title = stringResource(R.string.pref_duplicate_pinned_sources),
subtitle = stringResource(R.string.pref_duplicate_pinned_sources_summary),
),
),
),
Preference.PreferenceGroup(
title = stringResource(R.string.label_extensions),
preferenceItems = listOf(
Preference.PreferenceItem.SwitchPreference(
pref = preferences.automaticExtUpdates(),
title = stringResource(R.string.pref_enable_automatic_extension_updates),
onValueChanged = {
ExtensionUpdateJob.setupTask(context, it)
true
},
),
),
),
Preference.PreferenceGroup(
title = stringResource(R.string.action_global_search),
preferenceItems = listOf(
Preference.PreferenceItem.SwitchPreference(
pref = sourcePreferences.searchPinnedSourcesOnly(),
title = stringResource(R.string.pref_search_pinned_sources_only),
),
),
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_nsfw_content),
preferenceItems = listOf(
Preference.PreferenceItem.SwitchPreference(
pref = sourcePreferences.showNsfwSource(),
title = stringResource(R.string.pref_show_nsfw_source),
subtitle = stringResource(R.string.requires_app_restart),
onValueChanged = {
(context as FragmentActivity).authenticate(
title = context.getString(R.string.pref_category_nsfw_content),
)
},
),
Preference.PreferenceItem.InfoPreference(stringResource(R.string.parental_controls_info)),
),
),
)
}
}
| apache-2.0 | 8dacbd3034ce2a33d67bd60f0188960e | 43.707317 | 110 | 0.595199 | 5.791469 | false | false | false | false |
pambrose/prometheus-proxy | src/main/kotlin/io/prometheus/Agent.kt | 1 | 11240 | /*
* Copyright © 2020 Paul Ambrose ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus
import com.github.pambrose.common.coroutine.delay
import com.github.pambrose.common.delegate.AtomicDelegates.nonNullableReference
import com.github.pambrose.common.dsl.GuavaDsl.toStringElements
import com.github.pambrose.common.service.GenericService
import com.github.pambrose.common.servlet.LambdaServlet
import com.github.pambrose.common.time.format
import com.github.pambrose.common.util.MetricsUtils.newBacklogHealthCheck
import com.github.pambrose.common.util.Version
import com.github.pambrose.common.util.getBanner
import com.github.pambrose.common.util.hostInfo
import com.github.pambrose.common.util.randomId
import com.github.pambrose.common.util.simpleClassName
import com.google.common.util.concurrent.RateLimiter
import io.grpc.Status
import io.grpc.StatusException
import io.grpc.StatusRuntimeException
import io.prometheus.agent.AgentConnectionContext
import io.prometheus.agent.AgentGrpcService
import io.prometheus.agent.AgentHttpService
import io.prometheus.agent.AgentMetrics
import io.prometheus.agent.AgentOptions
import io.prometheus.agent.AgentPathManager
import io.prometheus.agent.EmbeddedAgentInfo
import io.prometheus.agent.RequestFailureException
import io.prometheus.client.Summary
import io.prometheus.common.BaseOptions.Companion.DEBUG
import io.prometheus.common.ConfigVals
import io.prometheus.common.ConfigWrappers.newAdminConfig
import io.prometheus.common.ConfigWrappers.newMetricsConfig
import io.prometheus.common.ConfigWrappers.newZipkinConfig
import io.prometheus.common.getVersionDesc
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import mu.KLogging
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.roundToInt
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeMark
import kotlin.time.TimeSource.Monotonic
@Version(version = BuildConfig.APP_VERSION, date = BuildConfig.APP_RELEASE_DATE)
class Agent(
val options: AgentOptions,
inProcessServerName: String = "",
testMode: Boolean = false,
initBlock: (Agent.() -> Unit)? = null
) :
GenericService<ConfigVals>(
options.configVals,
newAdminConfig(options.adminEnabled, options.adminPort, options.configVals.agent.admin),
newMetricsConfig(options.metricsEnabled, options.metricsPort, options.configVals.agent.metrics),
newZipkinConfig(options.configVals.agent.internal.zipkin),
{ getVersionDesc(true) },
isTestMode = testMode
) {
private val agentConfigVals = configVals.agent.internal
private val clock = Monotonic
private val agentHttpService = AgentHttpService(this)
private val initialConnectionLatch = CountDownLatch(1)
// Prime the limiter
private val reconnectLimiter = RateLimiter.create(1.0 / agentConfigVals.reconnectPauseSecs).apply { acquire() }
private var lastMsgSentMark: TimeMark by nonNullableReference(clock.markNow())
internal val agentName = options.agentName.ifBlank { "Unnamed-${hostInfo.hostName}" }
internal val scrapeRequestBacklogSize = AtomicInteger(0)
internal val pathManager = AgentPathManager(this)
internal val grpcService = AgentGrpcService(this, options, inProcessServerName)
internal var agentId: String by nonNullableReference("")
internal val launchId = randomId(15)
internal val metrics by lazy { AgentMetrics(this) }
init {
fun toPlainText() = """
Prometheus Agent Info [${getVersionDesc(false)}]
Uptime: ${upTime.format(true)}
AgentId: $agentId
AgentName: $agentName
ProxyHost: $proxyHost
Admin Service:
${if (isAdminEnabled) servletService.toString() else "Disabled"}
Metrics Service:
${if (isMetricsEnabled) metricsService.toString() else "Disabled"}
""".trimIndent()
logger.info { "Agent name: $agentName" }
logger.info { "Proxy reconnect pause time: ${agentConfigVals.reconnectPauseSecs.seconds}" }
logger.info { "Scrape timeout time: ${options.scrapeTimeoutSecs.seconds}" }
initServletService {
if (options.debugEnabled) {
logger.info { "Adding /$DEBUG endpoint" }
addServlet(
DEBUG,
LambdaServlet {
listOf(toPlainText(), pathManager.toPlainText()).joinToString("\n")
}
)
}
}
initBlock?.invoke(this)
}
override fun run() {
fun exceptionHandler(name: String) =
CoroutineExceptionHandler { _, e ->
if (grpcService.agent.isRunning)
Status.fromThrowable(e).apply { logger.error { "Error in $name(): $code $description" } }
}
suspend fun connectToProxy() {
// Reset gRPC stubs if previous iteration had a successful connection, i.e., the agentId != ""
if (agentId.isNotEmpty()) {
grpcService.resetGrpcStubs()
logger.info { "Resetting agentId" }
agentId = ""
}
// Reset values for each connection attempt
pathManager.clear()
scrapeRequestBacklogSize.set(0)
lastMsgSentMark = clock.markNow()
if (grpcService.connectAgent()) {
grpcService.registerAgent(initialConnectionLatch)
pathManager.registerPaths()
val connectionContext = AgentConnectionContext()
coroutineScope {
launch(Dispatchers.Default + exceptionHandler("readRequestsFromProxy")) {
grpcService.readRequestsFromProxy(agentHttpService, connectionContext)
}
launch(Dispatchers.Default + exceptionHandler("startHeartBeat")) {
startHeartBeat(connectionContext)
}
// This exceptionHandler is not necessary
launch(Dispatchers.Default + exceptionHandler("writeResponsesToProxyUntilDisconnected")) {
grpcService.writeResponsesToProxyUntilDisconnected(this@Agent, connectionContext)
}
launch(Dispatchers.Default + exceptionHandler("scrapeResultsChannel.send")) {
// This is terminated by connectionContext.close()
for (scrapeRequestAction in connectionContext.scrapeRequestsChannel) {
// The url fetch occurs during the invoke() on the scrapeRequestAction
val scrapeResponse = scrapeRequestAction.invoke()
connectionContext.scrapeResultsChannel.send(scrapeResponse)
}
}
}
}
}
while (isRunning) {
try {
runBlocking {
connectToProxy()
}
} catch (e: RequestFailureException) {
logger.info { "Disconnected from proxy at $proxyHost after invalid response ${e.message}" }
} catch (e: StatusRuntimeException) {
logger.info { "Disconnected from proxy at $proxyHost" }
} catch (e: StatusException) {
logger.warn { "Cannot connect to proxy at $proxyHost ${e.simpleClassName} ${e.message}" }
} catch (e: Throwable) {
// Catch anything else to avoid exiting retry loop
logger.warn { "Throwable caught ${e.simpleClassName} ${e.message}" }
} finally {
logger.info { "Waited ${reconnectLimiter.acquire().roundToInt().seconds} to reconnect" }
}
}
}
internal val proxyHost get() = "${grpcService.hostName}:${grpcService.port}"
internal fun startTimer(agent: Agent): Summary.Timer? =
metrics.scrapeRequestLatency.labels(agent.launchId, agentName).startTimer()
override fun serviceName() = "$simpleClassName $agentName"
override fun registerHealthChecks() {
super.registerHealthChecks()
healthCheckRegistry.register(
"scrape_request_backlog_check",
newBacklogHealthCheck(
scrapeRequestBacklogSize.get(),
agentConfigVals.scrapeRequestBacklogUnhealthySize
)
)
}
private suspend fun startHeartBeat(connectionContext: AgentConnectionContext) =
if (agentConfigVals.heartbeatEnabled) {
val heartbeatPauseTime = agentConfigVals.heartbeatCheckPauseMillis.milliseconds
val maxInactivityTime = agentConfigVals.heartbeatMaxInactivitySecs.seconds
logger.info { "Heartbeat scheduled to fire after $maxInactivityTime of inactivity" }
while (isRunning && connectionContext.connected) {
val timeSinceLastWrite = lastMsgSentMark.elapsedNow()
if (timeSinceLastWrite > maxInactivityTime) {
logger.debug { "Sending heartbeat" }
grpcService.sendHeartBeat()
}
delay(heartbeatPauseTime)
}
logger.info { "Heartbeat completed" }
} else {
logger.info { "Heartbeat disabled" }
}
internal fun updateScrapeCounter(agent: Agent, type: String) {
if (type.isNotEmpty())
metrics { scrapeRequestCount.labels(agent.launchId, type).inc() }
}
internal fun markMsgSent() {
lastMsgSentMark = clock.markNow()
}
internal fun awaitInitialConnection(timeout: Duration) =
initialConnectionLatch.await(timeout.inWholeMilliseconds, MILLISECONDS)
internal fun metrics(args: AgentMetrics.() -> Unit) {
if (isMetricsEnabled)
args.invoke(metrics)
}
override fun shutDown() {
grpcService.shutDown()
super.shutDown()
}
override fun toString() =
toStringElements {
add("agentId", agentId)
add("agentName", agentName)
add("proxyHost", proxyHost)
add("adminService", if (isAdminEnabled) servletService else "Disabled")
add("metricsService", if (isMetricsEnabled) metricsService else "Disabled")
}
companion object : KLogging() {
@JvmStatic
fun main(argv: Array<String>) {
startSyncAgent(argv, true)
}
@JvmStatic
fun startSyncAgent(argv: Array<String>, exitOnMissingConfig: Boolean) {
logger.apply {
info { getBanner("banners/agent.txt", this) }
info { getVersionDesc() }
}
Agent(options = AgentOptions(argv, exitOnMissingConfig)) { startSync() }
}
@JvmStatic
fun startAsyncAgent(
configFilename: String,
exitOnMissingConfig: Boolean,
logBanner: Boolean = true
): EmbeddedAgentInfo {
if (logBanner)
logger.apply {
info { getBanner("banners/agent.txt", this) }
info { getVersionDesc() }
}
val agent = Agent(options = AgentOptions(configFilename, exitOnMissingConfig)) { startAsync() }
return EmbeddedAgentInfo(agent.launchId, agent.agentName)
}
}
}
| apache-2.0 | 9c9753b22f2fb525b7a10e32a60d2ea5 | 35.728758 | 113 | 0.716612 | 4.4956 | false | true | false | false |
rinp/javaQuiz | src/main/kotlin/xxx/jq/dto/ResultListDto.kt | 1 | 1325 | package xxx.jq.dto
import org.springframework.data.domain.Page
import xxx.jq.entity.ResultHeader
import java.io.Serializable
import java.time.Duration
import java.time.LocalDateTime
import java.util.*
/**
* @param quizzes 表示される問題
* @param totalPages 全体のページ数
* @param page 対象となったページ数
* @param size ページ内の表示数
* @author rinp
* @since 2015/10/08
*/
data class ResultListDto(
val results: List<ResultListDto.Result> = ArrayList(),
val totalPages: Int = 0,
val page: Int = 0,
val size: Int = 0
) : Serializable {
constructor(page: Page<ResultHeader>) : this(
results = page.content.map { Result(it) },
totalPages = page.totalPages,
page = page.number,
size = page.size
)
data class Result(
val id: Long,
var createDate: LocalDateTime,
var executeTime: Duration,
var answerCount: Int,
var correctCount: Int
) : Serializable {
constructor(rh: ResultHeader) : this(
id = rh.id!!,
createDate = rh.createDate,
executeTime = rh.executeTime,
answerCount = rh.answerCount,
correctCount = rh.correctCount
)
}
}
| mit | 709f78a0843728317d2651f65bfac2ce | 26.413043 | 62 | 0.59318 | 3.965409 | false | false | false | false |
Maccimo/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.kt | 4 | 5946 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.util
import com.intellij.collaboration.ui.SimpleEventListener
import com.intellij.concurrency.JobScheduler
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EventDispatcher
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import java.io.IOException
import java.net.UnknownHostException
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import kotlin.properties.ObservableProperty
import kotlin.reflect.KProperty
/**
* Various utility methods for the GutHub plugin.
*/
object GithubUtil {
@JvmField
val LOG: Logger = Logger.getInstance("github")
@NlsSafe
const val SERVICE_DISPLAY_NAME: String = "GitHub"
@NlsSafe
const val ENTERPRISE_SERVICE_DISPLAY_NAME: String = "GitHub Enterprise"
const val GIT_AUTH_PASSWORD_SUBSTITUTE: String = "x-oauth-basic"
@JvmStatic
fun addCancellationListener(run: () -> Unit): ScheduledFuture<*> {
return JobScheduler.getScheduler().scheduleWithFixedDelay(run, 1000, 300, TimeUnit.MILLISECONDS)
}
private fun addCancellationListener(indicator: ProgressIndicator, thread: Thread): ScheduledFuture<*> {
return addCancellationListener { if (indicator.isCanceled) thread.interrupt() }
}
@Throws(IOException::class)
@JvmStatic
fun <T> runInterruptable(indicator: ProgressIndicator,
task: ThrowableComputable<T, IOException>): T {
var future: ScheduledFuture<*>? = null
try {
val thread = Thread.currentThread()
future = addCancellationListener(indicator, thread)
return task.compute()
}
finally {
future?.cancel(true)
Thread.interrupted()
}
}
@NlsSafe
@JvmStatic
fun getErrorTextFromException(e: Throwable): String {
return if (e is UnknownHostException) {
"Unknown host: " + e.message
}
else StringUtil.notNullize(e.message, "Unknown error")
}
/**
* Splits full commit message into subject and description in GitHub style:
* First line becomes subject, everything after first line becomes description
* Also supports empty line that separates subject and description
*
* @param commitMessage full commit message
* @return couple of subject and description based on full commit message
*/
@JvmStatic
fun getGithubLikeFormattedDescriptionMessage(commitMessage: String?): Couple<String> {
//Trim original
val message = commitMessage?.trim { it <= ' ' } ?: ""
if (message.isEmpty()) {
return Couple.of("", "")
}
val firstLineEnd = message.indexOf("\n")
val subject: String
val description: String
if (firstLineEnd > -1) {
//Subject is always first line
subject = message.substring(0, firstLineEnd).trim { it <= ' ' }
//Description is all text after first line, we also trim it to remove empty lines on start of description
description = message.substring(firstLineEnd + 1).trim { it <= ' ' }
}
else {
//If we don't have any line separators and cannot detect description,
//we just assume that it is one-line commit and use full message as subject with empty description
subject = message
description = ""
}
return Couple.of(subject, description)
}
object Delegates {
fun <T> observableField(initialValue: T, dispatcher: EventDispatcher<SimpleEventListener>): ObservableProperty<T> {
return object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = dispatcher.multicaster.eventOccurred()
}
}
}
@JvmStatic
@Deprecated("{@link GithubGitHelper}", ReplaceWith("GithubGitHelper.findGitRepository(project, file)",
"org.jetbrains.plugins.github.util.GithubGitHelper"))
@ApiStatus.ScheduledForRemoval
fun getGitRepository(project: Project, file: VirtualFile?): GitRepository? {
return GithubGitHelper.findGitRepository(project, file)
}
@JvmStatic
@Deprecated("{@link GithubGitHelper}")
private fun findGithubRemoteUrl(repository: GitRepository): String? {
val remote = findGithubRemote(repository) ?: return null
return remote.getSecond()
}
@JvmStatic
@Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}, {@link GithubGitHelper}")
private fun findGithubRemote(repository: GitRepository): Pair<GitRemote, String>? {
val server = GithubAuthenticationManager.getInstance().getSingleOrDefaultAccount(repository.project)?.server ?: return null
var githubRemote: Pair<GitRemote, String>? = null
for (gitRemote in repository.remotes) {
for (remoteUrl in gitRemote.urls) {
if (server.matches(remoteUrl)) {
val remoteName = gitRemote.name
if ("github" == remoteName || "origin" == remoteName) {
return Pair.create(gitRemote, remoteUrl)
}
if (githubRemote == null) {
githubRemote = Pair.create(gitRemote, remoteUrl)
}
break
}
}
}
return githubRemote
}
@JvmStatic
@Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}")
@ApiStatus.ScheduledForRemoval
fun isRepositoryOnGitHub(repository: GitRepository): Boolean {
return findGithubRemoteUrl(repository) != null
}
}
| apache-2.0 | 8e7823ba2165300dcd4b46c0c0cad892 | 35.256098 | 127 | 0.718298 | 4.719048 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/OP/syntax/lexer/SyntaxLexer.kt | 1 | 3786 | package com.bajdcc.OP.syntax.lexer
import com.bajdcc.OP.syntax.lexer.tokenizer.CommentTokenizer
import com.bajdcc.OP.syntax.lexer.tokenizer.NonTerminalTokenizer
import com.bajdcc.OP.syntax.lexer.tokenizer.OperatorTokenizer
import com.bajdcc.OP.syntax.lexer.tokenizer.TerminalTokenizer
import com.bajdcc.OP.syntax.token.Token
import com.bajdcc.OP.syntax.token.TokenType
import com.bajdcc.util.lexer.algorithm.ITokenAlgorithm
import com.bajdcc.util.lexer.algorithm.TokenAlgorithmCollection
import com.bajdcc.util.lexer.algorithm.impl.WhitespaceTokenizer
import com.bajdcc.util.lexer.error.RegexException
import com.bajdcc.util.lexer.regex.IRegexStringFilterHost
import com.bajdcc.util.lexer.regex.RegexStringIterator
import com.bajdcc.util.lexer.token.MetaType
/**
* 解析文法的词法分析器
*
* @author bajdcc
*/
class SyntaxLexer @Throws(RegexException::class)
constructor() : RegexStringIterator(), IRegexStringFilterHost {
/**
* 算法集合(正则表达式匹配)
*/
private val algorithmCollections = TokenAlgorithmCollection(
this, this)
/**
* 字符转换算法
*/
private var tokenAlgorithm: ITokenAlgorithm? = null
/**
* 丢弃的类型集合
*/
private val setDiscardToken = mutableSetOf<TokenType>()
/**
* 设置要分析的内容
*
* @param context 文法推导式
*/
override/* 初始化 */ var context: String
get() = super.context
set(context) {
super.context = context
position.column = 0
position.line = 0
data.current = '\u0000'
data.index = 0
data.meta = MetaType.END
stackIndex.clear()
stackPosition.clear()
}
init {
initialize()
}
/**
* 获取一个单词
*
* @return 单词
*/
fun nextToken(): Token? {
val token = Token.transfer(algorithmCollections.scan())
return if (setDiscardToken.contains(token.kToken)) {// 需要丢弃
null
} else token
}
/**
* 设置丢弃符号
*
* @param type 要丢弃的符号类型(不建议丢弃EOF,因为需要用来判断结束)
*/
fun discard(type: TokenType) {
setDiscardToken.add(type)
}
override fun setFilter(alg: ITokenAlgorithm) {
tokenAlgorithm = alg
}
override fun transform() {
super.transform()
if (tokenAlgorithm != null) {
val type = tokenAlgorithm!!.metaHash[data.current]
if (type != null)
data.meta = type
}
}
/**
* 初始化(添加组件)
*
* @throws RegexException 正则表达式错误
*/
@Throws(RegexException::class)
private fun initialize() {
//
// ### 算法容器中装载解析组件是有一定顺序的 ###
//
// 组件调用原理:
// 每个组件有自己的正则表达式匹配字符串
// (可选)有自己的过滤方法,如字符串中的转义过滤
//
// 解析时,分别按序调用解析组件,若组件解析失败,则调用下一组件
// 若某一组件解析成功,即返回匹配结果
// 若全部解析失败,则调用出错处理(默认为前进一字符)
//
algorithmCollections.attach(WhitespaceTokenizer())// 空白字符解析组件
algorithmCollections.attach(CommentTokenizer())// 注释解析组件
algorithmCollections.attach(TerminalTokenizer())// 终结符解析组件
algorithmCollections.attach(NonTerminalTokenizer())// 非终结符解析组件
algorithmCollections.attach(OperatorTokenizer())// 操作符解析组件
}
}
| mit | 30c461f17b42591115a0f3a1254ee225 | 25.561983 | 70 | 0.627256 | 3.781176 | false | false | false | false |
onoderis/failchat | src/main/kotlin/failchat/twitch/TwitchChatClient.kt | 1 | 7647 | package failchat.twitch
import failchat.Origin
import failchat.Origin.TWITCH
import failchat.chat.ChatClient
import failchat.chat.ChatClientCallbacks
import failchat.chat.ChatClientStatus
import failchat.chat.ChatMessage
import failchat.chat.ChatMessageHistory
import failchat.chat.MessageHandler
import failchat.chat.MessageIdGenerator
import failchat.chat.OriginStatus.CONNECTED
import failchat.chat.OriginStatus.DISCONNECTED
import failchat.chat.StatusUpdate
import failchat.chat.findTyped
import failchat.chat.handlers.BraceEscaper
import failchat.chat.handlers.ElementLabelEscaper
import kotlinx.coroutines.runBlocking
import mu.KLogging
import org.pircbotx.Configuration
import org.pircbotx.PircBotX
import org.pircbotx.hooks.ListenerAdapter
import org.pircbotx.hooks.events.ActionEvent
import org.pircbotx.hooks.events.ConnectEvent
import org.pircbotx.hooks.events.DisconnectEvent
import org.pircbotx.hooks.events.ListenerExceptionEvent
import org.pircbotx.hooks.events.MessageEvent
import org.pircbotx.hooks.events.UnknownEvent
import java.nio.charset.Charset
import java.time.Duration
import java.util.concurrent.atomic.AtomicReference
import java.util.regex.Pattern
import kotlin.concurrent.thread
class TwitchChatClient(
private val userName: String,
ircAddress: String,
ircPort: Int,
botName: String,
botPassword: String,
twitchEmoticonHandler: TwitchEmoticonHandler,
private val messageIdGenerator: MessageIdGenerator,
bttvEmoticonHandler: BttvEmoticonHandler,
ffzEmoticonHandler: FfzEmoticonHandler,
sevenTvGlobalEmoticonHandler: MessageHandler<ChatMessage>,
sevenTvChannelEmoticonHandler: MessageHandler<ChatMessage>,
twitchBadgeHandler: TwitchBadgeHandler,
private val history: ChatMessageHistory,
override val callbacks: ChatClientCallbacks
) : ChatClient {
private companion object : KLogging() {
val reconnectTimeout: Duration = Duration.ofSeconds(10)
val banMessagePattern: Pattern = Pattern.compile("""^:tmi\.twitch\.tv CLEARCHAT #.+ :(.+)""")
}
override val origin = Origin.TWITCH
override val status: ChatClientStatus get() = atomicStatus.get()
private val twitchIrcClient: PircBotX
private val serverEntries = listOf(Configuration.ServerEntry(ircAddress, ircPort))
private val atomicStatus: AtomicReference<ChatClientStatus> = AtomicReference(ChatClientStatus.READY)
private val messageHandlers: List<MessageHandler<TwitchMessage>> = listOf(
ElementLabelEscaper(),
twitchEmoticonHandler,
bttvEmoticonHandler,
ffzEmoticonHandler,
sevenTvGlobalEmoticonHandler,
sevenTvChannelEmoticonHandler,
BraceEscaper(),
TwitchHighlightHandler(userName),
TwitchRewardHandler(),
TwitchHighlightByPointsHandler(),
twitchBadgeHandler,
TwitchAuthorColorHandler()
)
init {
val configuration = Configuration.Builder()
.setName(botName)
.setServerPassword(botPassword)
.setServers(serverEntries)
.addAutoJoinChannel("#" + userName.toLowerCase())
.addListener(TwitchIrcListener())
// .addCapHandler() //todo try out
.setAutoReconnect(false)
.setAutoReconnectDelay(reconnectTimeout.toMillis().toInt())
.setAutoReconnectAttempts(Int.MAX_VALUE) // bugged, 5 attempts todo retest
.setEncoding(Charset.forName("UTF-8"))
.setCapEnabled(false)
.buildConfiguration()
twitchIrcClient = PircBotX(configuration)
}
override fun start() {
val statusChanged = atomicStatus.compareAndSet(ChatClientStatus.READY, ChatClientStatus.CONNECTED)
if (!statusChanged) throw IllegalStateException("Expected status: ${ChatClientStatus.READY}")
thread(start = true, name = "TwitchIrcClientThread") {
try {
twitchIrcClient.startBot()
} catch (e: Exception) {
logger.warn("Failed to start twitch irc client", e)
}
}
}
override fun stop() {
atomicStatus.set(ChatClientStatus.OFFLINE)
twitchIrcClient.close()
}
private inner class TwitchIrcListener : ListenerAdapter() {
override fun onConnect(event: ConnectEvent) {
logger.info("Connected to irc channel: {}", userName)
atomicStatus.set(ChatClientStatus.CONNECTED)
twitchIrcClient.sendCAP().request("twitch.tv/tags")
twitchIrcClient.sendCAP().request("twitch.tv/commands")
callbacks.onStatusUpdate(StatusUpdate(TWITCH, CONNECTED))
}
override fun onDisconnect(event: DisconnectEvent) {
when (atomicStatus.get()) {
ChatClientStatus.OFFLINE,
ChatClientStatus.ERROR -> return
else -> {
atomicStatus.set(ChatClientStatus.CONNECTING)
logger.info("Twitch irc client disconnected")
callbacks.onStatusUpdate(StatusUpdate(TWITCH, DISCONNECTED))
}
}
}
override fun onMessage(event: MessageEvent) {
logger.debug {
"Message was received from twitch. ${event.user}. Message: '${event.message}'. Tags: '${event.v3Tags}'"
}
val message = parseOrdinaryMessage(event)
messageHandlers.forEach { it.handleMessage(message) }
callbacks.onChatMessage(message)
}
override fun onListenerException(event: ListenerExceptionEvent) {
logger.warn("Listener exception", event.exception)
}
/**
* Handle "/me" messages.
* */
override fun onAction(event: ActionEvent) {
val message = parseMeMessage(event)
messageHandlers.forEach { it.handleMessage(message) }
callbacks.onChatMessage(message)
}
override fun onUnknown(event: UnknownEvent) {
logger.debug("Unknown event: {}", event.line)
val matcher = banMessagePattern.matcher(event.line)
if (!matcher.find()) return
val author = matcher.group(1)
val messagesToDelete = runBlocking {
history.findTyped<TwitchMessage> { it.author.id.equals(author, ignoreCase = true) }
}
messagesToDelete.forEach {
callbacks.onChatMessageDeleted(it)
}
}
}
private fun parseOrdinaryMessage(event: MessageEvent): TwitchMessage {
val displayedName = event.v3Tags.get(TwitchIrcTags.displayName) //could return null (e.g. from twitchnotify)
// Если пользователь не менял ник, то в v3tags пусто, ник capitalized
val author: String = if (displayedName.isNullOrEmpty()) {
event.userHostmask.nick.capitalize()
} else {
displayedName
}
return TwitchMessage(
id = messageIdGenerator.generate(),
author = author,
text = event.message,
tags = event.v3Tags
)
}
private fun parseMeMessage(event: ActionEvent): TwitchMessage {
// todo emoticons, color
return TwitchMessage(
id = messageIdGenerator.generate(),
author = event.userHostmask.nick,
text = event.message,
tags = mapOf()
)
}
}
| gpl-3.0 | 834d9cc0b9465bcd257a0c9173063d65 | 36.303922 | 119 | 0.652694 | 4.903351 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/visual/VisualSwapSelectionsAction.kt | 1 | 1912 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.motion.visual
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.group.visual.vimSetSelection
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.subMode
/**
* @author vlan
*/
class VisualSwapSelectionsAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_READONLY
// FIXME: 2019-03-05 Make it multicaret
override fun execute(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments,
): Boolean {
return swapVisualSelections(editor)
}
}
private fun swapVisualSelections(editor: VimEditor): Boolean {
val lastSelectionType = editor.vimLastSelectionType ?: return false
val lastVisualRange = injector.markGroup.getVisualSelectionMarks(editor) ?: return false
val primaryCaret = editor.primaryCaret()
editor.removeSecondaryCarets()
val vimSelectionStart = primaryCaret.vimSelectionStart
editor.vimLastSelectionType = SelectionType.fromSubMode(editor.subMode)
injector.markGroup.setVisualSelectionMarks(editor, TextRange(vimSelectionStart, primaryCaret.offset.point))
editor.subMode = lastSelectionType.toSubMode()
primaryCaret.vimSetSelection(lastVisualRange.startOffset, lastVisualRange.endOffset, true)
injector.motion.scrollCaretIntoView(editor)
return true
}
| mit | 166c0508ebbb20efad462107d1f9e568 | 33.763636 | 109 | 0.799686 | 4.202198 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/game/base/BaseGameArea.kt | 1 | 2786 | package org.hexworks.zircon.api.game.base
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.persistentHashMapOf
import org.hexworks.cobalt.core.api.behavior.DisposeState
import org.hexworks.cobalt.core.api.behavior.NotDisposed
import org.hexworks.cobalt.databinding.api.value.ObservableValue
import org.hexworks.zircon.api.Beta
import org.hexworks.zircon.api.behavior.Scrollable3D
import org.hexworks.zircon.api.data.Block
import org.hexworks.zircon.api.data.Position3D
import org.hexworks.zircon.api.data.Size3D
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.game.GameAreaTileFilter
import org.hexworks.zircon.internal.behavior.impl.DefaultScrollable3D
import org.hexworks.zircon.internal.game.GameAreaState
import org.hexworks.zircon.internal.game.InternalGameArea
@Beta
@Suppress("RUNTIME_ANNOTATION_NOT_SUPPORTED")
abstract class BaseGameArea<T : Tile, B : Block<T>>(
initialVisibleSize: Size3D,
initialActualSize: Size3D,
initialVisibleOffset: Position3D = Position3D.defaultPosition(),
initialContents: PersistentMap<Position3D, B> = persistentHashMapOf(),
initialFilters: Iterable<GameAreaTileFilter>,
private val scrollable3D: DefaultScrollable3D = DefaultScrollable3D(
initialVisibleSize = initialVisibleSize,
initialActualSize = initialActualSize
)
) : InternalGameArea<T, B>, Scrollable3D by scrollable3D {
final override val visibleOffsetValue: ObservableValue<Position3D>
get() = scrollable3D.visibleOffsetValue
final override val filter = initialFilters.fold(GameAreaTileFilter.identity, GameAreaTileFilter::plus)
override var state = GameAreaState(
blocks = initialContents,
actualSize = initialActualSize,
visibleSize = initialVisibleSize,
visibleOffset = initialVisibleOffset,
filter = filter
)
override val blocks: Map<Position3D, B>
get() = state.blocks
override var disposeState: DisposeState = NotDisposed
internal set
private val offsetChangedSubscription = visibleOffsetValue.onChange { (_, newValue) ->
state = state.copy(visibleOffset = newValue)
}
override fun dispose(disposeState: DisposeState) {
offsetChangedSubscription.dispose()
this.disposeState = disposeState
}
override fun hasBlockAt(position: Position3D) = blocks.containsKey(position)
override fun fetchBlockAtOrNull(position: Position3D) = blocks[position]
override fun setBlockAt(position: Position3D, block: B) {
if (actualSize.containsPosition(position)) {
state = state.copy(
blocks = state.blocks.put(position, block)
)
}
}
override fun asInternalGameArea() = this
}
| apache-2.0 | e4a40f5dd2d55bfacd050ba224564943 | 36.146667 | 106 | 0.752333 | 4.158209 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/TypeAliases.kt | 1 | 697 | /* 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 com.kotlinnlp.simplednn.simplemath.ndarray
internal typealias Indices = Pair<Int, Int>
internal typealias SparseEntry = Pair<Indices, Double>
internal typealias VectorIndices = MutableList<Int>
internal typealias VectorsMap = MutableMap<Int, VectorIndices?>
internal typealias VectorsMapEntry = MutableMap.MutableEntry<Int, VectorIndices?>
| mpl-2.0 | 963d986ed06d3b6bfe0504377fc657b0 | 48.785714 | 81 | 0.705882 | 4.585526 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IdeVirtualFileFinder.kt | 1 | 2214 | // 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.vfilefinder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ID
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import java.io.FileNotFoundException
import java.io.InputStream
class IdeVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFinder() {
override fun findMetadata(classId: ClassId): InputStream? {
val file = findVirtualFileWithHeader(classId.asSingleFqName(), KotlinMetadataFileIndex.KEY)?.takeIf { it.exists() } ?: return null
return try {
file.inputStream
} catch (e: FileNotFoundException) {
null
}
}
override fun hasMetadataPackage(fqName: FqName): Boolean = KotlinMetadataFilePackageIndex.hasSomethingInPackage(fqName, scope)
override fun findBuiltInsData(packageFqName: FqName): InputStream? =
findVirtualFileWithHeader(packageFqName, KotlinBuiltInsMetadataIndex.KEY)?.inputStream
override fun findSourceOrBinaryVirtualFile(classId: ClassId) = findVirtualFileWithHeader(classId)
init {
if (scope != GlobalSearchScope.EMPTY_SCOPE && scope.project == null) {
LOG.warn("Scope with null project $scope")
}
}
override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? =
findVirtualFileWithHeader(classId.asSingleFqName(), KotlinClassFileIndex.KEY)
private fun findVirtualFileWithHeader(fqName: FqName, key: ID<FqName, Void>): VirtualFile? {
val iterator = FileBasedIndex.getInstance().getContainingFilesIterator(key, fqName, scope)
return if (iterator.hasNext()) {
iterator.next()
} else {
null
}
}
companion object {
private val LOG = Logger.getInstance(IdeVirtualFileFinder::class.java)
}
}
| apache-2.0 | 9b8393240d8cc378a29ae5cc9a280f1e | 39.254545 | 158 | 0.735321 | 4.834061 | false | false | false | false |
mvysny/vaadin-on-kotlin | vok-framework/src/main/kotlin/eu/vaadinonkotlin/Services.kt | 1 | 3730 | package eu.vaadinonkotlin
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass
/**
* A namespace object for attaching your service classes.
*
* Register your stateless services simply as `val Services.yourService: YourService get() = YourService()`
*
* Register your singleton services as `val Services.yourService: YourService get() = singletons.getOrCreate { YourService() }`.
* The service will be created lazily, and at most once.
*
* WARNING: Calling [VaadinOnKotlin.destroy] will clean up the singleton instances. If you need to
* de-init your services, you have to do it beforehand.
*
* See [VoK: Services](https://www.vaadinonkotlin.eu/services/) documentation for more details.
*/
public object Services {
/**
* Internal: Only serves for singleton service definition. Don't use to look up your application services.
*
* Register your singleton services as `val Services.yourService: YourService get() = singletons.getOrCreate { YourService() }`.
* The service will be created lazily, and at most once.
*/
public val singletons: Singletons = Singletons()
}
/**
* A registry of JVM singleton services (= there's at most 1 instance of the service
* class in the JVM).
*/
public class Singletons {
private val instances = ConcurrentHashMap<Class<*>, Any>()
/**
* Registers the service instance, but only if it hasn't been registered yet. Fails if the service is already registered.
*
* Can be used for testing purposes, to allow registering of mock/fake services before the app's actual Bootstrap code is called.
*/
public operator fun <T: Any> set(serviceClass: KClass<T>, instance: T) {
check(instances.putIfAbsent(serviceClass.java, instance) == null) { "Service $serviceClass is already registered" }
}
/**
* Looks up a service by its [serviceClass] in the list of JVM singletons. If it's missing,
* the [instanceInitializer] will be called, to create the instance of the service.
*
* The [instanceInitializer] will be called at most once; while the initializer is running,
* any further lookups of the same service will block until the initializer is ready.
*
* Fails if [VaadinOnKotlin.isStarted] is false. That means that in your bootstrap, first
* call [VaadinOnKotlin.init], and only then start initializing your singleton services.
* During shutdown, first de-init all of your singleton services, and only then call
* [VaadinOnKotlin.destroy].
*/
@Suppress("UNCHECKED_CAST")
public fun <T: Any> getOrCreate(serviceClass: KClass<T>, instanceInitializer: () -> T): T {
check(VaadinOnKotlin.isStarted) { "VoK is not started" }
return instances.computeIfAbsent(serviceClass.java) { instanceInitializer() } as T
}
/**
* There's an inherent problem with this function. Consider the following use-case:
* ```
* interface MyService {}
* class MyServiceImpl : MyService
* class MyServiceTestingFake : MyService
* val Services.getOrCreate { MyServiceImpl() } // will T be MyService or MyServiceImpl? Actually, the latter, which makes it impossible to fake the service.
* ```
*/
@Deprecated("The service is stored under the key T, however it's up to Kotlin to guess the value of T. Please use the other getOrCreate() function and specify T explicitly")
public inline fun <reified T: Any> getOrCreate(noinline instanceInitializer: () -> T): T =
getOrCreate(T::class, instanceInitializer)
/**
* Removes all singleton instances; further service lookups will create a new instance.
*/
internal fun destroy() {
instances.clear()
}
}
| mit | 2c594c55e24c7da0964839e8a0e06e36 | 44.487805 | 177 | 0.703485 | 4.504831 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DependencyCollector.kt | 1 | 3805 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginAware
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.RequiredElement
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.openapi.util.NlsSafe
import com.intellij.serviceContainer.BaseKeyedLazyInstance
import com.intellij.util.xmlb.annotations.Attribute
import org.jetbrains.annotations.ApiStatus
internal class DependencyCollectorBean : BaseKeyedLazyInstance<DependencyCollector>() {
@Attribute("kind")
@JvmField
@RequiredElement
var kind: String = ""
@Attribute("implementation")
@JvmField
@RequiredElement
var implementation: String = ""
companion object {
val EP_NAME = ExtensionPointName.create<DependencyCollectorBean>("com.intellij.dependencyCollector")
}
override fun getImplementationClassName(): String = implementation
}
/**
* Collects dependencies for the given project, so that the IDE can offer to enable/install plugins supporting those dependencies.
* Implementations of this interface are registered through the `dependencyCollector` extension point.
*
* The plugins which need to be suggested must define "dependencySupport"
* with a coordinate that corresponding to one of the dependencies with the same "kind".
*/
interface DependencyCollector {
/**
* Returns the list of dependencies for the given project. Each element in the returned list is the name/coordinate of a dependency.
* The specific format of returned strings depends on the dependency kind. For Java, the format is Maven group ID and artifact ID
* separated by a colon.
*/
fun collectDependencies(project: Project): Collection<String>
}
/**
* Marks a plugin as supporting a given dependency. The `coordinate` attribute specifies the name or coordinate of the supported
* library/dependency, in the same format as returned from [DependencyCollector.collectDependencies] for the respective dependency kind.
*/
internal class DependencySupportBean() : PluginAware {
private var pluginDescriptor: PluginDescriptor? = null
@Attribute("kind")
@JvmField
@RequiredElement
var kind: String = ""
@Attribute("coordinate")
@JvmField
@RequiredElement
var coordinate: String = ""
/**
* The user-readable name of the corresponding library or framework. Shown to the user in messages suggesting to install/enable plugins.
*/
@Attribute("displayName")
@JvmField
@NlsSafe
var displayName: String = ""
companion object {
val EP_NAME = ExtensionPointName.create<DependencySupportBean>("com.intellij.dependencySupport")
}
@ApiStatus.Experimental
internal constructor(attributes: Map<String, String>) : this() {
kind = attributes["kind"]!!
coordinate = attributes["coordinate"]!!
displayName = attributes.getOrDefault("displayName", "")
}
override fun setPluginDescriptor(pluginDescriptor: PluginDescriptor) {
this.pluginDescriptor = pluginDescriptor
}
}
internal const val DEPENDENCY_SUPPORT_FEATURE = "dependencySupport"
internal val DependencySupportBean.id: @NlsSafe String
get() = "$kind:$coordinate"
internal val DependencySupportBean.displayNameOrId: @NlsSafe String
get() = displayName.ifEmpty { id }
internal class DependencyFeatureCollector : ProjectPostStartupActivity {
override suspend fun execute(project: Project) {
PluginFeatureService.instance.collectFeatureMapping(
DEPENDENCY_SUPPORT_FEATURE,
DependencySupportBean.EP_NAME,
{ it.id },
{ it.displayNameOrId },
)
}
}
| apache-2.0 | d47495d5aa26642ee6eec0368cb3b531 | 33.590909 | 138 | 0.770828 | 4.816456 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/usecase/FindChallengeProgressUseCase.kt | 1 | 4462 | package io.ipoli.android.challenge.usecase
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.DateUtils
import io.ipoli.android.common.datetime.Time
import io.ipoli.android.common.datetime.datesBetween
import io.ipoli.android.common.datetime.isBetween
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.data.persistence.QuestRepository
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/13/18.
*/
class FindChallengeProgressUseCase(private val questRepository: QuestRepository) :
UseCase<FindChallengeProgressUseCase.Params, Challenge> {
override fun execute(parameters: Params): Challenge {
val challenge = parameters.challenge
val repeatingCount = challenge.repeatingQuests.sumBy { rq ->
val rqEnd = rq.end
val start = rq.start
val end =
if (rqEnd == null) challenge.endDate else DateUtils.min(rqEnd, challenge.endDate)
val removedCount =
challenge.quests.filter { it.repeatingQuestId == rq.id && it.isRemoved }.size
val allCount = questRepository.findCountForRepeatingQuestInPeriod(rq.id, start, end)
allCount - removedCount
}
val completedCount = challenge.quests.filter { it.isCompleted && !it.isRemoved }.size
val allCount = repeatingCount + challenge.baseQuests.filter { it is Quest }.size
val newTrackedValues = challenge.trackedValues.map {
when (it) {
is Challenge.TrackedValue.Progress -> {
val increasePerQuest = (1f / allCount) * 100f
val historyData =
challenge.startDate.datesBetween(parameters.currentDate).map { d ->
d to 0f
}.toMap().toMutableMap()
challenge.quests
.filter { q ->
q.isCompleted && q.completedAtDate!!.isBetween(
challenge.startDate,
parameters.currentDate
)
}
.forEach { q ->
historyData[q.completedAtDate!!] = historyData[q.completedAtDate]!! +
increasePerQuest
}
val history = historyData.map { h ->
h.key to Challenge.TrackedValue.Log(h.value.toDouble(), Time.now(), h.key)
}.toMap().toSortedMap()
it.copy(
completedCount = completedCount,
allCount = allCount,
history = history
)
}
is Challenge.TrackedValue.Target -> {
var currentValue =
if (it.history.isNotEmpty())
it.history[it.history.lastKey()]!!.value
else
it.startValue
val cumulativeHistory = if (it.isCumulative) {
currentValue = it.startValue + it.history.values.map { l ->
l.value
}.sum()
var cumVal = it.startValue
it.history.values.map { l ->
cumVal += l.value
l.date to l.copy(value = cumVal)
}.toMap().toSortedMap()
} else
null
it.copy(
currentValue = currentValue,
remainingValue = Math.abs(it.targetValue - currentValue),
cumulativeHistory = cumulativeHistory
)
}
else -> it
}
}
return challenge.copy(
progress = Challenge.Progress(
completedCount = completedCount,
allCount = allCount
),
trackedValues = newTrackedValues
)
}
data class Params(
val challenge: Challenge,
val lastDayOfWeek: DayOfWeek = DateUtils.lastDayOfWeek,
val currentDate: LocalDate = LocalDate.now()
)
} | gpl-3.0 | 761dd715dc7159f181f554f3ebbc4935 | 36.191667 | 98 | 0.515464 | 5.481572 | false | false | false | false |
square/picasso | picasso/src/main/java/com/squareup/picasso3/PicassoExecutorService.kt | 1 | 2394 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.os.Process
import android.os.Process.THREAD_PRIORITY_BACKGROUND
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit.MILLISECONDS
/**
* The default [java.util.concurrent.ExecutorService] used for new [Picasso] instances.
*/
class PicassoExecutorService(
threadCount: Int = DEFAULT_THREAD_COUNT,
threadFactory: ThreadFactory = PicassoThreadFactory()
) : ThreadPoolExecutor(
threadCount, threadCount, 0, MILLISECONDS, PriorityBlockingQueue(), threadFactory
) {
override fun submit(task: Runnable): Future<*> {
val ftask = PicassoFutureTask(task as BitmapHunter)
execute(ftask)
return ftask
}
private class PicassoThreadFactory : ThreadFactory {
override fun newThread(r: Runnable): Thread = PicassoThread(r)
private class PicassoThread(r: Runnable) : Thread(r) {
override fun run() {
Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND)
super.run()
}
}
}
private class PicassoFutureTask(private val hunter: BitmapHunter) :
FutureTask<BitmapHunter>(hunter, null), Comparable<PicassoFutureTask> {
override fun compareTo(other: PicassoFutureTask): Int {
val p1 = hunter.priority
val p2 = other.hunter.priority
// High-priority requests are "lesser" so they are sorted to the front.
// Equal priorities are sorted by sequence number to provide FIFO ordering.
return if (p1 == p2) hunter.sequence - other.hunter.sequence else p2.ordinal - p1.ordinal
}
}
private companion object {
private const val DEFAULT_THREAD_COUNT = 3
}
}
| apache-2.0 | 5b01b366a107fc1815a1129beba5404e | 34.205882 | 95 | 0.741019 | 4.290323 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/ui/GitEditorPromo.kt | 3 | 2700 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.icons.AllIcons
import com.intellij.ide.CommandLineWaitingManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.IconButton
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import com.intellij.ui.EditorNotifications
import com.intellij.ui.InplaceButton
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepositoryFiles
import git4idea.repo.GitRepositoryManager
import java.awt.BorderLayout
import java.util.function.Function
import javax.swing.JComponent
private const val PROMO_DISMISSED_KEY = "git.editor.promo.dismissed"
private class GitEditorPromo : EditorNotificationProvider {
override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?>? {
if (!isEnabled() || !CommandLineWaitingManager.getInstance().hasHookFor(file) || file.name != GitRepositoryFiles.COMMIT_EDITMSG) {
return null
}
return Function {
val panel = EditorNotificationPanel(HintUtil.PROMOTION_PANE_KEY, EditorNotificationPanel.Status.Info)
panel.icon(AllIcons.Ide.Gift)
panel.text = GitBundle.message("editor.promo.commit.text", ApplicationNamesInfo.getInstance().fullProductName)
val repository = GitRepositoryManager.getInstance(project).repositories.find { it.repositoryFiles.isCommitMessageFile(file.path) }
if (repository == null) {
panel.createActionLabel(GitBundle.message("editor.promo.help.link")) {
HelpManager.getInstance().invokeHelp("Commit and push changes")
}
}
else {
panel.createActionLabel(GitBundle.message("editor.promo.commit.try.link"), IdeActions.ACTION_CHECKIN_PROJECT, false)
}
panel.add(
InplaceButton(IconButton(GitBundle.message("editor.promo.close.link"), AllIcons.Actions.Close, AllIcons.Actions.CloseHovered)) {
PropertiesComponent.getInstance().setValue(PROMO_DISMISSED_KEY, true)
EditorNotifications.getInstance(project).updateNotifications(this)
}, BorderLayout.EAST)
panel
}
}
private fun isEnabled(): Boolean = !PropertiesComponent.getInstance().getBoolean(PROMO_DISMISSED_KEY)
} | apache-2.0 | 626af57d15a0222308403dc377853ad5 | 46.385965 | 136 | 0.782593 | 4.477612 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/testSources/dsl/GradlePropertiesFileTest.kt | 2 | 3154 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.dsl
import com.intellij.lang.properties.psi.PropertiesFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiUtilCore
import com.intellij.testFramework.runInEdtAndWait
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.testFramework.GradleCodeInsightTestCase
import org.jetbrains.plugins.gradle.testFramework.GradleTestFixtureBuilder
import org.jetbrains.plugins.gradle.testFramework.annotations.AllGradleVersionsSource
import org.jetbrains.plugins.gradle.testFramework.util.withBuildFile
import org.jetbrains.plugins.gradle.testFramework.util.withSettingsFile
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.params.ParameterizedTest
class GradlePropertiesFileTest : GradleCodeInsightTestCase() {
@ParameterizedTest
@AllGradleVersionsSource
fun `test find usages of property`(gradleVersion: GradleVersion) {
test(gradleVersion, PROPERTIES_FIXTURE) {
runInEdtAndWait {
val buildscript = findOrCreateFile("build.gradle", "foo")
val child = projectRoot.findChild("gradle.properties")
assertNotNull(child, "Expected not-null child")
val prop = (PsiUtilCore.getPsiFile(codeInsightFixture.project, child!!) as PropertiesFile).findPropertyByKey("foo")
assertNotNull(prop, "Expected not-null prop")
val buildscriptScope = GlobalSearchScope.fileScope(codeInsightFixture.project, buildscript)
val usageRefs = ReferencesSearch.search(prop!!.psiElement, buildscriptScope).findAll()
val usageRef = usageRefs.singleOrNull()
assertNotNull(usageRef, "Expected not-null usage ref")
assertTrue(usageRef!!.element.language == GroovyLanguage)
}
}
}
@ParameterizedTest
@AllGradleVersionsSource
fun `test completion in project`(gradleVersion: GradleVersion) {
test(gradleVersion, PROPERTIES_FIXTURE) {
testCompletion("project.<caret>", "foo", "foobar")
}
}
@ParameterizedTest
@AllGradleVersionsSource
fun `test completion in ext`(gradleVersion: GradleVersion) {
test(gradleVersion, PROPERTIES_FIXTURE) {
testCompletion("project.ext.<caret>", "foo", "foobar")
}
}
@ParameterizedTest
@AllGradleVersionsSource
fun `test go to definition`(gradleVersion: GradleVersion) {
test(gradleVersion, PROPERTIES_FIXTURE) {
testGotoDefinition("fo<caret>o") {
assertTrue(it.containingFile is PropertiesFile)
}
}
}
companion object {
val PROPERTIES_FIXTURE = GradleTestFixtureBuilder.create("GradlePropertiesFileTest") {
withSettingsFile {
setProjectName("GradlePropertiesFileTest")
}
withBuildFile(content = "")
withFile("gradle.properties", /* language=properties */ """
foo=1
foobar=2
foo.bar=3
""".trimIndent())
}
}
} | apache-2.0 | 3c9784c94dd5fda1d26e231246dd1467 | 38.4375 | 123 | 0.751744 | 4.82263 | false | true | false | false |
ktorio/ktor | ktor-io/js/src/io/ktor/utils/io/core/StringsJS.kt | 1 | 1867 | package io.ktor.utils.io.core
import io.ktor.utils.io.bits.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.internal.*
import org.khronos.webgl.*
import kotlin.require
/**
* Create an instance of [String] from the specified [bytes] range starting at [offset] and bytes [length]
* interpreting characters in the specified [charset].
*/
@Suppress("FunctionName")
public actual fun String(bytes: ByteArray, offset: Int, length: Int, charset: Charset): String {
if (offset < 0 || length < 0 || offset + length > bytes.size) {
checkIndices(offset, length, bytes)
}
@Suppress("UnsafeCastFromDynamic")
val i8: Int8Array = bytes.asDynamic() // we know that K/JS generates Int8Array for ByteBuffer
val bufferOffset = i8.byteOffset + offset
val buffer = i8.buffer.slice(bufferOffset, bufferOffset + length)
@Suppress("DEPRECATION")
val view = ChunkBuffer(Memory.of(buffer), null, ChunkBuffer.NoPool)
view.resetForRead()
val packet = ByteReadPacket(view, ChunkBuffer.NoPoolManuallyManaged)
return charset.newDecoder().decode(packet, Int.MAX_VALUE)
}
public fun checkIndices(offset: Int, length: Int, bytes: ByteArray): Nothing {
require(offset >= 0) { throw IndexOutOfBoundsException("offset ($offset) shouldn't be negative") }
require(length >= 0) { throw IndexOutOfBoundsException("length ($length) shouldn't be negative") }
require(offset + length <= bytes.size) {
throw IndexOutOfBoundsException("offset ($offset) + length ($length) > bytes.size (${bytes.size})")
}
throw IndexOutOfBoundsException()
}
internal actual fun String.getCharsInternal(dst: CharArray, dstOffset: Int) {
val length = length
require(dstOffset + length <= dst.size)
var dstIndex = dstOffset
for (srcIndex in 0 until length) {
dst[dstIndex++] = this[srcIndex]
}
}
| apache-2.0 | 52c25dff1a462ca50a2788b442b3dbdd | 36.34 | 107 | 0.706481 | 3.98081 | false | false | false | false |
cfieber/orca | orca-dry-run/src/test/kotlin/com/netflix/spinnaker/orca/dryrun/DryRunTaskTest.kt | 1 | 3069 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.dryrun
import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.TaskResult
import com.netflix.spinnaker.orca.dryrun.stub.OutputStub
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.nhaarman.mockito_kotlin.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
object DryRunTaskTest : Spek({
val outputStub: OutputStub = mock()
val subject = DryRunTask(listOf(outputStub))
describe("running the task") {
val pipeline = pipeline {
stage {
type = "deploy"
refId = "1"
}
stage {
type = "bake"
refId = "2"
}
trigger = DefaultTrigger("manual", null, "[email protected]")
}
given("a stage with no outputs in the trigger and no output stub") {
beforeGroup {
whenever(outputStub.supports(any())) doReturn false
}
afterGroup {
reset(outputStub)
}
var result: TaskResult? = null
on("running the task") {
result = subject.execute(pipeline.stageByRef("1"))
}
it("should return success") {
assertThat(result!!.status).isEqualTo(SUCCEEDED)
}
it("should create no outputs") {
assertThat(result!!.outputs).isEmpty()
}
it("should not try to stub output") {
verify(outputStub, never()).outputs(any())
}
}
given("a stage with an output stub") {
val stubOutput = mapOf("negative" to "covfefe")
beforeGroup {
whenever(outputStub.supports(any())) doAnswer { it.getArgument<Stage>(0).type == "bake" }
whenever(outputStub.outputs(pipeline.stageByRef("2"))) doReturn stubOutput
}
afterGroup {
reset(outputStub)
}
var result: TaskResult? = null
on("running the task") {
result = subject.execute(pipeline.stageByRef("2"))
}
it("should return success") {
assertThat(result!!.status).isEqualTo(SUCCEEDED)
}
it("should have stubbed outputs") {
assertThat(result!!.outputs).isEqualTo(stubOutput)
}
}
}
})
| apache-2.0 | 7848974764e3fff5690d9c0512f5fc06 | 27.155963 | 97 | 0.670577 | 4.102941 | false | false | false | false |
ezand/jottakloud | src/main/kotlin/org/ezand/jottakloud/Jottacloud.kt | 1 | 5276 | package org.ezand.jottakloud
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import khttp.get
import khttp.responses.Response
import khttp.structures.authorization.BasicAuthorization
import mu.KLogging
import org.ezand.jottakloud.data.*
import org.ezand.jottakloud.deserializers.JottacloudDateTimeDeserializer
import org.ezand.jottakloud.exceptions.JottakloudException
import org.joda.time.DateTime
import java.io.InputStream
import java.net.URL
import java.net.URLEncoder
class Jottacloud(val auth: JottacloudAuthentication, val baseUrl: URL = URL("https://www.jottacloud.com/jfs")) {
companion object : KLogging()
private val xmlMapper = XmlMapper()
.registerModule(KotlinModule())
.registerModule(JacksonXmlModule())
.registerModule(JodaModule().addDeserializer(DateTime::class.java, JottacloudDateTimeDeserializer()))
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE)
fun getUser(): User? {
val url = buildUrl(auth.username)
logger.debug { "Getting user: $url" }
val response = get(url, auth = auth.basicAuth())
return objectOrNull(response)
}
fun getDevice(deviceName: String): Device? {
val url = buildUrl("${auth.username}/$deviceName")
logger.debug { "Getting device '$deviceName': $url" }
val response = get(url, auth = auth.basicAuth())
return objectOrNull(response)
}
fun getMountPoint(deviceName: String, mountPointName: String): MountPoint? {
val url = buildUrl("${auth.username}/$deviceName/$mountPointName")
logger.debug { "Getting mount point: '$deviceName' -> '$mountPointName': $url" }
val response = get(url, auth = auth.basicAuth())
return objectOrNull(response)
}
fun getFolder(deviceName: String, mountPointName: String, path: String): FolderDetails? {
val url = buildUrl("${auth.username}/$deviceName/$mountPointName/$path")
logger.debug { "Getting folder: '$deviceName' -> '$mountPointName' -> '$path': $url" }
val response = get(url, auth = auth.basicAuth())
return objectOrNull(response)
}
fun getFile(deviceName: String, mountPointName: String, path: String): FileDetails? {
val url = buildUrl("${auth.username}/$deviceName/$mountPointName/$path")
logger.debug { "Getting file: '$deviceName' -> '$mountPointName' -> '$path': $url" }
val response = get(url, auth = auth.basicAuth())
return objectOrNull(response)
}
fun getFiles(deviceName: String, mountPointName: String, path: String, recursive: Boolean = false): List<FileDetails> {
return getFiles(deviceName, mountPointName, path, emptyList(), recursive)
}
fun downloadFile(deviceName: String, mountPointName: String, path: String): InputStream? {
val url = buildUrl("${auth.username}/$deviceName/$mountPointName/$path?mode=bin")
logger.debug { "Getting file: '$deviceName' -> '$mountPointName' -> '$path': $url" }
val response = get(url, auth = auth.basicAuth())
return streamOrNull(response)
}
private fun getFiles(deviceName: String, mountPointName: String, path: String, files: List<FileDetails>, recursive: Boolean): List<FileDetails> {
val folder = getFolder(deviceName, mountPointName, path)
if (folder != null) {
val filesInFolder = folder.files.map { getFile(deviceName, mountPointName, it.name) }.filterNotNull()
if (recursive) {
return folder.folders.fold(filesInFolder) { f, subFolder ->
return getFiles(deviceName, mountPointName, subFolder.name, f, recursive)
}
} else {
return filesInFolder
}
} else {
return files
}
}
private fun JottacloudAuthentication.basicAuth(): BasicAuthorization {
return BasicAuthorization(this.username, this.password)
}
private fun buildUrl(url: String): String {
val encodedUrl = url.split("/")
.map { URLEncoder.encode(it, "utf-8") }
.joinToString("/")
return "$baseUrl/$encodedUrl"
}
inline private fun <reified T : Any> objectOrNull(response: Response): T? {
when (response.statusCode) {
200 -> try {
return xmlMapper.readValue(response.text, T::class.java)
} catch (e: Exception) {
throw JottakloudException("An error occurred while mapping the xml response", e)
}
404 -> return null
else -> throw JottakloudException("Unexpected http-status from Jottacloud: ${response.statusCode}. Message: ${response.text}")
}
}
private fun streamOrNull(response: Response): InputStream? {
if (response.statusCode == 200) return response.raw else return null
}
}
| mit | ac3435f30e1cfadd27bade7a013504fd | 40.543307 | 149 | 0.667362 | 4.41876 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/indicator/datasetindicatorengine/DataSetIndicatorEvaluatorShould.kt | 1 | 5861 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.indicator.datasetindicatorengine
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.hisp.dhis.android.core.constant.Constant
import org.hisp.dhis.android.core.indicator.Indicator
import org.hisp.dhis.android.core.indicator.IndicatorType
import org.hisp.dhis.android.core.parser.internal.service.ExpressionService
import org.hisp.dhis.android.core.parser.internal.service.dataobject.DimensionalItemObject
import org.junit.Before
import org.junit.Test
class DataSetIndicatorEvaluatorShould {
private val indicator: Indicator = mock()
private val indicatorType: IndicatorType = mock()
private val days: Int = 31
private val constant: Constant = Constant.builder().uid("SOp2Q9u5vf2").value(3.5).build()
private val constantMap: Map<String, Constant> = mapOf(constant.uid() to constant)
private val diItem1 = "Jc3zxCRAB86"
private val diItem2 = "qoiAI2HJSIa.uCfsdJFdyfR"
private val diObject1: DimensionalItemObject = mock()
private val diObject2: DimensionalItemObject = mock()
private lateinit var valueMap: Map<DimensionalItemObject, Double>
private lateinit var orgunitGroupMap: Map<String, Int>
private lateinit var expressionService: ExpressionService
private lateinit var evaluator: DataSetIndicatorEvaluator
@Before
fun setUp() {
expressionService = ExpressionService(mock(), mock(), mock(), mock())
evaluator = DataSetIndicatorEvaluator(expressionService)
whenever(indicatorType.factor()) doReturn 1
whenever(diObject1.dimensionItem) doReturn diItem1
whenever(diObject2.dimensionItem) doReturn diItem2
whenever(indicator.numerator()) doReturn "#{$diItem1}"
whenever(indicator.denominator()) doReturn "#{$diItem2}"
whenever(indicator.decimals()) doReturn 2
orgunitGroupMap = mapOf()
}
@Test
fun evaluate_indicator_factor() {
valueMap = mapOf(
diObject1 to 5.0,
diObject2 to 10.0
)
whenever(indicatorType.factor()) doReturn 1
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(0.5)
whenever(indicatorType.factor()) doReturn 100
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(50)
whenever(indicatorType.factor()) doReturn -10
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(-5)
}
@Test
fun evaluate_indicator_decimals_default() {
valueMap = mapOf(
diObject1 to 10.0,
diObject2 to 3.0
)
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(3.33)
}
@Test
fun evaluate_indicator_decimals_configurable() {
whenever(indicator.decimals()) doReturn 3
valueMap = mapOf(
diObject1 to 10.0,
diObject2 to 3.0
)
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(3.333)
}
@Test
fun evaluate_null_numerator() {
valueMap = mapOf(
diObject2 to 10.0
)
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(0.0)
}
@Test
fun evaluate_null_denominator() {
valueMap = mapOf(
diObject1 to 10.0
)
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(0.0)
}
@Test
fun evaluate_zero_denominator() {
valueMap = mapOf(
diObject1 to 10.0,
diObject2 to 0.0
)
assertThat(
evaluator.evaluate(indicator, indicatorType, valueMap, constantMap, orgunitGroupMap, days)
).isEqualTo(0.0)
}
}
| bsd-3-clause | 71976aed21b2aea6065199f9e3c1a095 | 35.403727 | 102 | 0.698516 | 4.393553 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveWhenElseBranchFix.kt | 5 | 2133 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.CodeInsightUtilCore
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class MoveWhenElseBranchFix(element: KtWhenExpression) : KotlinQuickFixAction<KtWhenExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("move.else.branch.to.the.end")
override fun getText() = familyName
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = element ?: return false
return KtPsiUtil.checkWhenExpressionHasSingleElse(element)
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val entries = element.entries
val lastEntry = entries.lastOrNull() ?: return
val elseEntry = entries.singleOrNull { it.isElse } ?: return
val cursorOffset = editor!!.caretModel.offset - elseEntry.textOffset
val insertedBranch = element.addAfter(elseEntry, lastEntry) as KtWhenEntry
elseEntry.delete()
val insertedWhenEntry = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(insertedBranch) ?: return
editor.caretModel.moveToOffset(insertedWhenEntry.textOffset + cursorOffset)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): MoveWhenElseBranchFix? {
val whenExpression = diagnostic.psiElement.getNonStrictParentOfType<KtWhenExpression>() ?: return null
return MoveWhenElseBranchFix(whenExpression)
}
}
}
| apache-2.0 | 2426b493f559db4562429b8ecd3075da | 44.382979 | 158 | 0.7609 | 4.948956 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/rds/src/main/kotlin/com/kotlin/rds/CreateDBSnapshot.kt | 1 | 2015 | // snippet-sourcedescription:[CreateDBSnapshot.kt demonstrates how to create an Amazon Relational Database Service (RDS) snapshot.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Relational Database Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.rds
// snippet-start:[rds.kotlin.create_snap.import]
import aws.sdk.kotlin.services.rds.RdsClient
import aws.sdk.kotlin.services.rds.model.CreateDbSnapshotRequest
import kotlin.system.exitProcess
// snippet-end:[rds.kotlin.create_snap.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<dbInstanceIdentifier> <dbSnapshotIdentifier>
Where:
dbInstanceIdentifier - The database instance identifier.
dbSnapshotIdentifier - The dbSnapshotIdentifier identifier.
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val dbInstanceIdentifier = args[0]
val dbSnapshotIdentifier = args[1]
createSnapshot(dbInstanceIdentifier, dbSnapshotIdentifier)
}
// snippet-start:[rds.kotlin.create_snap.main]
suspend fun createSnapshot(dbInstanceIdentifierVal: String?, dbSnapshotIdentifierVal: String?) {
val snapshotRequest = CreateDbSnapshotRequest {
dbInstanceIdentifier = dbInstanceIdentifierVal
dbSnapshotIdentifier = dbSnapshotIdentifierVal
}
RdsClient { region = "us-west-2" }.use { rdsClient ->
val response = rdsClient.createDbSnapshot(snapshotRequest)
print("The Snapshot id is ${response.dbSnapshot?.dbiResourceId}")
}
}
// snippet-end:[rds.kotlin.create_snap.main]
| apache-2.0 | 4463230360ed649f475fa529670e7f8f | 32.152542 | 131 | 0.709181 | 4.112245 | false | false | false | false |
google/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopup.kt | 1 | 15090 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui.branch
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.TreePopup
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.WindowStateService
import com.intellij.ui.ActiveComponent
import com.intellij.ui.ClientProperty
import com.intellij.ui.JBColor
import com.intellij.ui.TreeActions
import com.intellij.ui.popup.NextStepHandler
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.WizardPopup
import com.intellij.ui.popup.util.PopupImplUtil
import com.intellij.ui.render.RenderingUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.tree.ui.DefaultTreeUI
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.FontUtil
import com.intellij.util.text.nullize
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.tree.TreeUtil
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.ui.branch.GitBranchesTreeUtil.overrideBuiltInAction
import git4idea.ui.branch.GitBranchesTreeUtil.selectFirstLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectLastLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectNextLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectPrevLeaf
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.drop
import java.awt.Component
import java.awt.Cursor
import java.awt.Point
import java.awt.event.*
import java.util.function.Predicate
import java.util.function.Supplier
import javax.swing.*
import javax.swing.tree.TreeCellRenderer
import javax.swing.tree.TreeModel
import javax.swing.tree.TreePath
import javax.swing.tree.TreeSelectionModel
class GitBranchesTreePopup(project: Project, step: GitBranchesTreePopupStep)
: WizardPopup(project, null, step),
TreePopup, NextStepHandler {
private lateinit var tree: JTree
private var showingChildPath: TreePath? = null
private var pendingChildPath: TreePath? = null
private val treeStep: GitBranchesTreePopupStep
get() = step as GitBranchesTreePopupStep
private lateinit var searchPatternStateFlow: MutableStateFlow<String?>
private var userResized: Boolean
init {
setMinimumSize(JBDimension(200, 200))
dimensionServiceKey = GitBranchPopup.DIMENSION_SERVICE_KEY
userResized = WindowStateService.getInstance(project).getSizeFor(project, dimensionServiceKey) != null
setSpeedSearchAlwaysShown()
installShortcutActions(step.treeModel)
installHeaderToolbar()
installResizeListener()
DataManager.registerDataProvider(component, DataProvider { dataId -> if (POPUP_KEY.`is`(dataId)) this else null })
}
override fun createContent(): JComponent {
tree = Tree(treeStep.treeModel).also {
configureTreePresentation(it)
overrideTreeActions(it)
addTreeMouseControlsListeners(it)
Disposer.register(this) {
it.model = null
}
}
searchPatternStateFlow = MutableStateFlow(null)
speedSearch.installSupplyTo(tree, false)
@OptIn(FlowPreview::class)
with(uiScope(this)) {
launch {
searchPatternStateFlow.drop(1).debounce(100).collectLatest { pattern ->
treeStep.setSearchPattern(pattern)
selectPreferred()
}
}
}
return tree
}
internal fun restoreDefaultSize() {
userResized = false
WindowStateService.getInstance(project).putSizeFor(project, dimensionServiceKey, null)
pack(true, true)
}
private fun installResizeListener() {
val popupWindow = popupWindow ?: return
val windowListener: ComponentListener = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) {
userResized = true
}
}
popupWindow.addComponentListener(windowListener)
addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
popupWindow.removeComponentListener(windowListener)
}
})
}
override fun storeDimensionSize() {
if (userResized) {
super.storeDimensionSize()
}
}
private fun installShortcutActions(model: TreeModel) {
val root = model.root
(0 until model.getChildCount(root))
.asSequence()
.map { model.getChild(root, it) }
.filterIsInstance<PopupFactoryImpl.ActionItem>()
.map(PopupFactoryImpl.ActionItem::getAction)
.forEach { action ->
registerAction(ActionManager.getInstance().getId(action), KeymapUtil.getKeyStroke(action.shortcutSet), createShortcutAction(action))
}
}
private fun installHeaderToolbar() {
val settingsGroup = ActionManager.getInstance().getAction(GitBranchesTreePopupStep.HEADER_SETTINGS_ACTION_GROUP)
val toolbarGroup = DefaultActionGroup(GitBranchPopupFetchAction(javaClass), settingsGroup)
val toolbar = ActionManager.getInstance()
.createActionToolbar(GitBranchesTreePopupStep.ACTION_PLACE, toolbarGroup, true)
.apply {
targetComponent = [email protected]
setReservePlaceAutoPopupIcon(false)
component.isOpaque = false
}
title.setButtonComponent(object : ActiveComponent.Adapter() {
override fun getComponent(): JComponent = toolbar.component
}, JBUI.Borders.emptyRight(2))
}
private fun createShortcutAction(action: AnAction) = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
cancel()
ActionUtil.invokeAction(action,
GitBranchesTreePopupStep.createDataContext(project, treeStep.repository),
GitBranchesTreePopupStep.ACTION_PLACE, null, null)
}
}
private fun configureTreePresentation(tree: JTree) = with(tree) {
ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_BACKGROUND, Supplier { JBUI.CurrentTheme.Tree.background(true, true) })
ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_FOREGROUND, Supplier { JBUI.CurrentTheme.Tree.foreground(true, true) })
ClientProperty.put(this, RenderingUtil.SEPARATOR_ABOVE_PREDICATE, Predicate { treeStep.isSeparatorAboveRequired(it) })
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
isRootVisible = false
showsRootHandles = true
cellRenderer = Renderer(treeStep)
accessibleContext.accessibleName = GitBundle.message("git.branches.popup.tree.accessible.name")
ClientProperty.put(this, DefaultTreeUI.LARGE_MODEL_ALLOWED, true)
rowHeight = JBUIScale.scale(20)
isLargeModel = true
expandsSelectedPaths = true
}
private fun overrideTreeActions(tree: JTree) = with(tree) {
overrideBuiltInAction("toggle") {
val path = selectionPath
if (path != null && model.getChildCount(path.lastPathComponent) == 0) {
handleSelect(true, null)
true
}
else false
}
overrideBuiltInAction(TreeActions.Right.ID) {
val path = selectionPath
if (path != null && model.getChildCount(path.lastPathComponent) == 0) {
handleSelect(false, null)
true
}
else false
}
overrideBuiltInAction(TreeActions.Down.ID) {
if (speedSearch.isHoldingFilter) selectNextLeaf()
else false
}
overrideBuiltInAction(TreeActions.Up.ID) {
if (speedSearch.isHoldingFilter) selectPrevLeaf()
else false
}
overrideBuiltInAction(TreeActions.Home.ID) {
if (speedSearch.isHoldingFilter) selectFirstLeaf()
else false
}
overrideBuiltInAction(TreeActions.End.ID) {
if (speedSearch.isHoldingFilter) selectLastLeaf()
else false
}
}
private fun addTreeMouseControlsListeners(tree: JTree) = with(tree) {
addMouseMotionListener(SelectionMouseMotionListener())
addMouseListener(SelectOnClickListener())
}
override fun getActionMap(): ActionMap = tree.actionMap
override fun getInputMap(): InputMap = tree.inputMap
override fun afterShow() {
selectPreferred()
}
private fun selectPreferred() {
val preferredSelection = treeStep.getPreferredSelection()
if (preferredSelection != null) {
tree.makeVisible(preferredSelection)
tree.selectionPath = preferredSelection
TreeUtil.scrollToVisible(tree, preferredSelection, true)
}
else TreeUtil.promiseSelectFirstLeaf(tree)
}
override fun isResizable(): Boolean = true
private inner class SelectionMouseMotionListener : MouseMotionAdapter() {
private var lastMouseLocation: Point? = null
/**
* this method should be changed only in par with
* [com.intellij.ui.popup.list.ListPopupImpl.MyMouseMotionListener.isMouseMoved]
*/
private fun isMouseMoved(location: Point): Boolean {
if (lastMouseLocation == null) {
lastMouseLocation = location
return false
}
val prev = lastMouseLocation
lastMouseLocation = location
return prev != location
}
override fun mouseMoved(e: MouseEvent) {
if (!isMouseMoved(e.locationOnScreen)) return
val path = getPath(e)
if (path != null) {
tree.selectionPath = path
notifyParentOnChildSelection()
if (treeStep.isSelectable(TreeUtil.getUserObject(path.lastPathComponent))) {
tree.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
if (pendingChildPath == null || pendingChildPath != path) {
pendingChildPath = path
restartTimer()
}
return
}
}
tree.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)
}
}
private inner class SelectOnClickListener : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
if (e.button != MouseEvent.BUTTON1) return
val path = getPath(e) ?: return
val selected = path.lastPathComponent
if (treeStep.isSelectable(TreeUtil.getUserObject(selected))) {
handleSelect(true, e)
}
}
}
private fun getPath(e: MouseEvent): TreePath? = tree.getClosestPathForLocation(e.point.x, e.point.y)
private fun handleSelect(handleFinalChoices: Boolean, e: MouseEvent?) {
val selectionPath = tree.selectionPath
val pathIsAlreadySelected = showingChildPath != null && showingChildPath == selectionPath
if (pathIsAlreadySelected) return
pendingChildPath = null
val selected = tree.lastSelectedPathComponent
if (selected != null) {
val userObject = TreeUtil.getUserObject(selected)
if (treeStep.isSelectable(userObject)) {
disposeChildren()
val hasNextStep = myStep.hasSubstep(userObject)
if (!hasNextStep && !handleFinalChoices) {
showingChildPath = null
return
}
val queriedStep = PopupImplUtil.prohibitFocusEventsInHandleSelect().use {
myStep.onChosen(userObject, handleFinalChoices)
}
if (queriedStep == PopupStep.FINAL_CHOICE || !hasNextStep) {
setFinalRunnable(myStep.finalRunnable)
setOk(true)
disposeAllParents(e)
}
else {
showingChildPath = selectionPath
handleNextStep(queriedStep, selected)
showingChildPath = null
}
}
}
}
override fun handleNextStep(nextStep: PopupStep<*>?, parentValue: Any) {
val selectionPath = tree.selectionPath ?: return
val pathBounds = tree.getPathBounds(selectionPath) ?: return
val point = Point(pathBounds.x, pathBounds.y)
SwingUtilities.convertPointToScreen(point, tree)
myChild = createPopup(this, nextStep, parentValue)
myChild.show(content, content.locationOnScreen.x + content.width - STEP_X_PADDING, point.y, true)
}
override fun onSpeedSearchPatternChanged() {
with(uiScope(this)) {
launch {
searchPatternStateFlow.emit(speedSearch.enteredPrefix.nullize(true))
}
}
}
override fun getPreferredFocusableComponent(): JComponent = tree
override fun onChildSelectedFor(value: Any) {
val path = value as TreePath
if (tree.selectionPath != path) {
tree.selectionPath = path
}
}
companion object {
internal val POPUP_KEY = DataKey.create<GitBranchesTreePopup>("GIT_BRANCHES_TREE_POPUP")
@JvmStatic
fun show(project: Project, repository: GitRepository) {
GitBranchesTreePopup(project, GitBranchesTreePopupStep(project, repository)).showCenteredInCurrentWindow(project)
}
private fun uiScope(parent: Disposable) =
CoroutineScope(SupervisorJob() + Dispatchers.Main).also {
Disposer.register(parent) { it.cancel() }
}
private class Renderer(private val step: GitBranchesTreePopupStep) : TreeCellRenderer {
private val mainLabel = JLabel().apply {
border = JBUI.Borders.emptyBottom(1)
}
private val secondaryLabel = JLabel().apply {
font = FontUtil.minusOne(font)
border = JBUI.Borders.empty(0, 10, 1, 5)
horizontalAlignment = SwingConstants.RIGHT
}
private val arrowLabel = JLabel().apply {
border = JBUI.Borders.empty(0, 2)
}
private val textPanel = JBUI.Panels.simplePanel()
.addToLeft(mainLabel)
.addToCenter(secondaryLabel)
.andTransparent()
private val mainPanel = JBUI.Panels.simplePanel()
.addToCenter(textPanel)
.addToRight(arrowLabel)
.andTransparent()
override fun getTreeCellRendererComponent(tree: JTree?,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): Component {
val userObject = TreeUtil.getUserObject(value)
mainLabel.apply {
icon = step.getIcon(userObject)
text = step.getText(userObject)
foreground = JBUI.CurrentTheme.Tree.foreground(selected, true)
}
secondaryLabel.apply {
text = step.getSecondaryText(userObject)
//todo: LAF color
foreground = if(selected) JBUI.CurrentTheme.Tree.foreground(true, true) else JBColor.GRAY
}
arrowLabel.apply {
isVisible = step.hasSubstep(userObject)
icon = if (selected) AllIcons.Icons.Ide.MenuArrowSelected else AllIcons.Icons.Ide.MenuArrow
}
return mainPanel
}
}
}
}
| apache-2.0 | ced59dc9e992b10f8bbbbc56886a786b | 33.689655 | 140 | 0.702783 | 4.778341 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt | 2 | 10629 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.MarkupModel
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.ui.JBColor
import com.intellij.ui.NonFocusableCheckBox
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinInplaceVariableIntroducer
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.getValueParameterList
import org.jetbrains.kotlin.psi.psiUtil.getValueParameters
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
import java.awt.Color
import javax.swing.JCheckBox
class KotlinInplaceParameterIntroducer(
val originalDescriptor: IntroduceParameterDescriptor,
val parameterType: KotlinType,
val suggestedNames: Array<out String>,
project: Project,
editor: Editor
) : AbstractKotlinInplaceIntroducer<KtParameter>(
null,
originalDescriptor.originalRange.elements.single() as KtExpression,
originalDescriptor.occurrencesToReplace.map { it.elements.single() as KtExpression }.toTypedArray(),
INTRODUCE_PARAMETER,
project,
editor
) {
companion object {
private val LOG = Logger.getInstance(KotlinInplaceParameterIntroducer::class.java)
}
enum class PreviewDecorator {
FOR_ADD() {
override val textAttributes: TextAttributes = with(TextAttributes()) {
effectType = EffectType.ROUNDED_BOX
effectColor = JBColor.RED
this
}
},
FOR_REMOVAL() {
override val textAttributes: TextAttributes = with(TextAttributes()) {
effectType = EffectType.STRIKEOUT
effectColor = Color.BLACK
this
}
};
protected abstract val textAttributes: TextAttributes
fun applyToRange(range: TextRange, markupModel: MarkupModel) {
markupModel.addRangeHighlighter(
range.startOffset,
range.endOffset,
0,
textAttributes,
HighlighterTargetArea.EXACT_RANGE
)
}
}
private inner class Preview(addedParameter: KtParameter?, currentName: String?) {
private val _rangesToRemove = ArrayList<TextRange>()
var addedRange: TextRange? = null
private set
var text: String = ""
private set
val rangesToRemove: List<TextRange> get() = _rangesToRemove
init {
val templateState = TemplateManagerImpl.getTemplateState(myEditor)
val currentType = if (templateState?.template != null) {
templateState.getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME)?.text
} else null
val builder = StringBuilder()
with(descriptor) {
(callable as? KtFunction)?.receiverTypeReference?.let { receiverTypeRef ->
builder.append(receiverTypeRef.text).append('.')
if (!descriptor.withDefaultValue && receiverTypeRef in parametersToRemove) {
_rangesToRemove.add(TextRange(0, builder.length))
}
}
builder.append(callable.name)
val parameters = callable.getValueParameters()
builder.append("(")
for (i in parameters.indices) {
val parameter = parameters[i]
val parameterText = if (parameter == addedParameter) {
val parameterName = currentName ?: parameter.name
val parameterType = currentType ?: parameter.typeReference!!.text
descriptor = descriptor.copy(newParameterName = parameterName!!, newParameterTypeText = parameterType)
val modifier = if (valVar != KotlinValVar.None) "${valVar.keywordName} " else ""
val defaultValue = if (withDefaultValue) {
" = ${if (newArgumentValue is KtProperty) newArgumentValue.name else newArgumentValue.text}"
} else ""
"$modifier$parameterName: $parameterType$defaultValue"
} else parameter.text
builder.append(parameterText)
val range = TextRange(builder.length - parameterText.length, builder.length)
if (parameter == addedParameter) {
addedRange = range
} else if (!descriptor.withDefaultValue && parameter in parametersToRemove) {
_rangesToRemove.add(range)
}
if (i < parameters.lastIndex) {
builder.append(", ")
}
}
builder.append(")")
if (addedRange == null) {
LOG.error("Added parameter not found: ${callable.getElementTextWithContext()}")
}
}
text = builder.toString()
}
}
private var descriptor = originalDescriptor
private var replaceAllCheckBox: JCheckBox? = null
init {
initFormComponents {
addComponent(previewComponent)
val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.introduce.default.value"))
defaultValueCheckBox.isSelected = descriptor.withDefaultValue
defaultValueCheckBox.addActionListener {
descriptor = descriptor.copy(withDefaultValue = defaultValueCheckBox.isSelected)
updateTitle(variable)
}
addComponent(defaultValueCheckBox)
val occurrenceCount = descriptor.occurrencesToReplace.size
if (occurrenceCount > 1) {
val replaceAllCheckBox = NonFocusableCheckBox(
KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount))
replaceAllCheckBox.isSelected = true
addComponent(replaceAllCheckBox)
[email protected] = replaceAllCheckBox
}
}
}
override fun getActionName() = "IntroduceParameter"
override fun checkLocalScope() = descriptor.callable
override fun getVariable() = originalDescriptor.callable.getValueParameters().lastOrNull()
override fun suggestNames(replaceAll: Boolean, variable: KtParameter?) = suggestedNames
override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>): KtParameter {
return runWriteAction {
with(descriptor) {
val parameterList = callable.getValueParameterList()
?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent()
val parameter = KtPsiFactory(myProject).createParameter("$newParameterName: $newParameterTypeText")
parameterList.addParameter(parameter)
}
}
}
override fun deleteTemplateField(psiField: KtParameter) {
if (psiField.isValid) {
(psiField.parent as? KtParameterList)?.removeParameter(psiField)
}
}
override fun isReplaceAllOccurrences() = replaceAllCheckBox?.isSelected ?: true
override fun setReplaceAllOccurrences(allOccurrences: Boolean) {
replaceAllCheckBox?.isSelected = allOccurrences
}
override fun getComponent() = myWholePanel
override fun updateTitle(addedParameter: KtParameter?, currentName: String?) {
val preview = Preview(addedParameter, currentName)
val document = previewEditor.document
runWriteAction { document.setText(preview.text) }
val markupModel = DocumentMarkupModel.forDocument(document, myProject, true)
markupModel.removeAllHighlighters()
preview.rangesToRemove.forEach { PreviewDecorator.FOR_REMOVAL.applyToRange(it, markupModel) }
preview.addedRange?.let { PreviewDecorator.FOR_ADD.applyToRange(it, markupModel) }
revalidate()
}
override fun getRangeToRename(element: PsiElement): TextRange {
if (element is KtProperty) return element.nameIdentifier!!.textRange.shiftRight(-element.startOffset)
return super.getRangeToRename(element)
}
override fun createMarker(element: PsiElement): RangeMarker {
if (element is KtProperty) return super.createMarker(element.nameIdentifier)
return super.createMarker(element)
}
override fun performIntroduce() {
getDescriptorToRefactor(isReplaceAllOccurrences).performRefactoring()
}
private fun getDescriptorToRefactor(replaceAll: Boolean): IntroduceParameterDescriptor {
val originalRange = expr.toRange()
return descriptor.copy(
originalRange = originalRange,
occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange),
argumentValue = expr!!
)
}
fun switchToDialogUI() {
stopIntroduce(myEditor)
KotlinIntroduceParameterDialog(
myProject,
myEditor,
getDescriptorToRefactor(true),
myNameSuggestions.toTypedArray(),
listOf(parameterType) + parameterType.supertypes(),
KotlinIntroduceParameterHelper.Default
).show()
}
}
| apache-2.0 | 4698cfb55bc28affc3a2832b82747224 | 40.03861 | 158 | 0.662621 | 5.937989 | false | false | false | false |
JetBrains/intellij-community | platform/diagnostic/telemetry/src/TraceManager.kt | 1 | 7371 | // 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.diagnostic.telemetry
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.util.SystemProperties
import com.intellij.openapi.util.io.FileSetLimiter
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.metrics.Meter
import io.opentelemetry.sdk.OpenTelemetrySdk
import io.opentelemetry.sdk.metrics.SdkMeterProvider
import io.opentelemetry.sdk.metrics.export.MetricExporter
import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader
import io.opentelemetry.sdk.resources.Resource
import io.opentelemetry.sdk.trace.SdkTracerProvider
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes
import kotlinx.coroutines.CoroutineScope
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.time.Duration
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
/**
* See [Span](https://opentelemetry.io/docs/reference/specification),
* [Manual Instrumentation](https://opentelemetry.io/docs/instrumentation/java/manual/#create-spans-with-events).
*
* TODO Rename TraceManager to more generic (OTel|Telemetry|Monitoring|...)Manager
* Name TraceManager is misleading now: today it is entry-point not only for Traces (spans), but also for Metrics. It looks
* unnatural (to me) to request Meter instances with the call like TraceManager.getMeter("meterName").
* We could move .getMeter() to another facade (e.g. MeterManager), but this looks artificial (to me:), since Tracer and
* Meter are both parts of OpenTelemetry sdk anyway, and inherently configured/initialized together.
*
*/
@ApiStatus.Experimental
@ApiStatus.Internal
object TraceManager {
private var sdk: OpenTelemetry = OpenTelemetry.noop()
private var verboseMode: Boolean = false
fun init(mainScope: CoroutineScope) {
val traceFile = System.getProperty("idea.diagnostic.opentelemetry.file")
val traceEndpoint = System.getProperty("idea.diagnostic.opentelemetry.otlp")
//RC: Contrary to traces, metrics ARE enabled by default.
// Default metrics files look like '<logs>/open-telemetry-metrics.2022-11-01-20-15-44.csv' (date
// suffix is appended automatically, see .createMetricsExporter() for details)
// To disable metrics: set `-Didea.diagnostic.opentelemetry.metrics.file=""` (i.e. empty string)
val metricsReportingPath = System.getProperty("idea.diagnostic.opentelemetry.metrics.file",
"open-telemetry-metrics.csv")
val metricsEnabled = !metricsReportingPath.isNullOrEmpty()
if (traceFile == null && traceEndpoint == null && !metricsEnabled) {
// noop
return
}
val serviceName = ApplicationNamesInfo.getInstance().fullProductName
val appInfo = ApplicationInfoImpl.getShadowInstance()
val serviceVersion = appInfo.build.asStringWithoutProductCode()
val serviceNamespace = appInfo.build.productCode
val spanExporters = mutableListOf<AsyncSpanExporter>()
if (traceFile != null) {
spanExporters.add(JaegerJsonSpanExporter(file = Path.of(traceFile),
serviceName = serviceName,
serviceVersion = serviceVersion,
serviceNamespace = serviceNamespace))
}
if (traceEndpoint != null) {
spanExporters.add(OtlpSpanExporter(traceEndpoint))
}
val metricExporters = mutableListOf<MetricExporter>()
if (metricsEnabled) {
val exporter = createMetricsExporter(metricsReportingPath)
metricExporters.add(exporter)
}
val resource = Resource.create(Attributes.of(
ResourceAttributes.SERVICE_NAME, serviceName,
ResourceAttributes.SERVICE_VERSION, serviceVersion,
ResourceAttributes.SERVICE_NAMESPACE, serviceNamespace,
ResourceAttributes.SERVICE_INSTANCE_ID, DateTimeFormatter.ISO_INSTANT.format(Instant.now()),
))
val otelSdkBuilder = OpenTelemetrySdk.builder()
if (spanExporters.isNotEmpty()) {
val tracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor(mainScope = mainScope, spanExporters = spanExporters))
.setResource(resource)
.build()
otelSdkBuilder.setTracerProvider(tracerProvider)
ShutDownTracker.getInstance().registerShutdownTask {
tracerProvider.shutdown().join(10, TimeUnit.SECONDS)
}
}
if (metricExporters.isNotEmpty()) {
// no analog of SpanExporter.composite() available for metrics:
assert(metricExporters.size == 1) {
"Only single MetricsExporter supported so far, but got: $metricExporters"
}
val metricsReader = PeriodicMetricReader.builder(metricExporters.first())
.setInterval(Duration.ofMinutes(1)) // == default value, but to be explicit
.build()
val meterProvider = SdkMeterProvider.builder()
.registerMetricReader(metricsReader)
.setResource(resource)
.build()
otelSdkBuilder.setMeterProvider(meterProvider)
ShutDownTracker.getInstance().registerShutdownTask(meterProvider::shutdown)
}
sdk = otelSdkBuilder.buildAndRegisterGlobal()
val useVerboseSdk = System.getProperty("idea.diagnostic.opentelemetry.verbose")
verboseMode = useVerboseSdk?.toBooleanStrictOrNull() == true
}
private fun createMetricsExporter(metricsReportingPath: String): MetricExporter {
val suffixDateFormat = System.getProperty("idea.diagnostic.opentelemetry.metrics.suffix-date-format", "yyyy-MM-dd-HH-mm-ss")
val maxFilesToKeep = SystemProperties.getIntProperty("idea.diagnostic.opentelemetry.metrics.max-files-to-keep", 14)
//if metrics path is relative -> resolve it against IDEA logDir:
val pathResolvedAgainstLogDir = PathManager.getLogDir().resolve(metricsReportingPath).toAbsolutePath()
val writeMetricsTo = FileSetLimiter.inDirectory(pathResolvedAgainstLogDir.parent)
.withBaseNameAndDateFormatSuffix(pathResolvedAgainstLogDir.fileName.toString(), suffixDateFormat)
.removeOldFilesBut(maxFilesToKeep, FileSetLimiter.DELETE_ASYNC)
.createNewFile()
return CsvMetricsExporter(writeMetricsTo)
}
/**
* Method creates a tracer with the scope name.
* Separate tracers define different scopes, and as result separate main nodes in the result data.
* It is expected that for different subsystems different tracers would be used, to isolate the results.
*
* @param verbose provides a way to disable by default some tracers.
* Such tracers will be created only if additional system property "verbose" is set to true.
*
*/
@JvmOverloads
fun getTracer(scopeName: String, verbose: Boolean = false): IJTracer {
return wrapTracer(scopeName, sdk.getTracer(scopeName), verbose, verboseMode)
}
fun noopTracer(): IJTracer {
return IJNoopTracer
}
fun getMeter(scopeName: String): Meter = sdk.getMeter(scopeName)
} | apache-2.0 | f3e164f2a63ce3afb43eca846f86b6dd | 43.95122 | 135 | 0.738434 | 4.586808 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/line-markers/src/org/jetbrains/kotlin/idea/codeInsight/lineMarkers/KotlinRecursiveCallLineMarkerProvider.kt | 1 | 6427 | // 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.codeInsight.lineMarkers
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.refactoring.suggested.createSmartPointer
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.KtExplicitReceiverValue
import org.jetbrains.kotlin.analysis.api.calls.KtImplicitReceiverValue
import org.jetbrains.kotlin.analysis.api.calls.KtSmartCastedReceiverValue
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.idea.base.codeInsight.CallTarget
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinCallProcessor
import org.jetbrains.kotlin.idea.base.codeInsight.process
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.parents
internal class KotlinRecursiveCallLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<in LineMarkerInfo<*>>) {
KotlinCallProcessor.process(elements) { target ->
val symbol = target.symbol
val targetDeclaration = target.symbol.psi as? KtDeclaration ?: return@process
if (symbol.origin == KtSymbolOrigin.SOURCE_MEMBER_GENERATED || !targetDeclaration.isAncestor(target.caller)) {
return@process
}
if (isRecursiveCall(target, targetDeclaration)) {
@NlsSafe val declarationName = when (symbol) {
is KtVariableLikeSymbol -> symbol.name.asString()
is KtFunctionSymbol -> symbol.name.asString() + "()"
is KtPropertyGetterSymbol -> "get()"
is KtPropertySetterSymbol -> "set()"
is KtConstructorSymbol -> "constructor()"
else -> return@process
}
val message = KotlinLineMarkersBundle.message("line.markers.recursive.call.description")
result += RecursiveCallLineMarkerInfo(target.anchorLeaf, message, declarationName, targetDeclaration.createSmartPointer())
}
}
}
private fun KtAnalysisSession.isRecursiveCall(target: CallTarget, targetDeclaration: PsiElement): Boolean {
for (parent in target.caller.parents) {
when (parent) {
targetDeclaration -> return checkDispatchReceiver(target)
is KtPropertyAccessor -> {} // Skip, handle in 'KtProperty'
is KtProperty -> if (!parent.isLocal) return false
is KtDestructuringDeclaration -> {} // Skip, destructuring declaration is not a scoping declaration
is KtFunctionLiteral -> {} // Count calls inside lambdas
is KtNamedFunction -> if (parent.nameIdentifier != null) return false // Count calls inside anonymous functions
is KtObjectDeclaration -> if (!parent.isObjectLiteral()) return false
is KtDeclaration -> return false
}
}
return false
}
private fun KtAnalysisSession.checkDispatchReceiver(target: CallTarget): Boolean {
var dispatchReceiver = target.partiallyAppliedSymbol.dispatchReceiver ?: return true
while (dispatchReceiver is KtSmartCastedReceiverValue) {
dispatchReceiver = dispatchReceiver.original
}
val containingClass = target.symbol.getContainingSymbol() as? KtClassOrObjectSymbol ?: return true
if (dispatchReceiver is KtExplicitReceiverValue) {
if (dispatchReceiver.isSafeNavigation) {
return false
}
return when (val expression = KtPsiUtil.deparenthesize(dispatchReceiver.expression)) {
is KtThisExpression -> expression.instanceReference.mainReference.resolveToSymbol() == containingClass
is KtExpression -> when (val receiverSymbol = expression.mainReference?.resolveToSymbol()) {
is KtFunctionSymbol -> {
receiverSymbol.isOperator
&& receiverSymbol.name.asString() == "invoke"
&& containingClass.classKind.isObject
&& receiverSymbol.getContainingSymbol() == containingClass
}
is KtClassOrObjectSymbol -> {
receiverSymbol.classKind.isObject
&& receiverSymbol == containingClass
}
else -> false
}
else -> false
}
}
if (dispatchReceiver is KtImplicitReceiverValue) {
return dispatchReceiver.symbol == containingClass
}
return false
}
private class RecursiveCallLineMarkerInfo(
anchor: PsiElement,
message: String,
@NlsSafe private val declarationName: String,
targetElementPointer: SmartPsiElementPointer<PsiElement>?,
) : MergeableLineMarkerInfo<PsiElement>(
/* element = */ anchor,
/* textRange = */ anchor.textRange,
/* icon = */ AllIcons.Gutter.RecursiveMethod,
/* tooltipProvider = */ { message },
/* navHandler = */ targetElementPointer?.let(::SimpleNavigationHandler),
/* alignment = */ GutterIconRenderer.Alignment.RIGHT,
/* accessibleNameProvider = */ { message }
) {
override fun createGutterRenderer() = LineMarkerGutterIconRenderer(this)
override fun getElementPresentation(element: PsiElement) = declarationName
override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is RecursiveCallLineMarkerInfo
override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>) = infos.firstNotNullOf { it.icon }
}
} | apache-2.0 | e4946f40cd05239e2008162ebfd22e1b | 48.446154 | 138 | 0.668897 | 5.764126 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/cache/ScriptConfigurationCache.kt | 1 | 3999 | // 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.core.script.configuration.cache
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.script.configuration.utils.getKtFile
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import java.io.Serializable
import kotlin.script.experimental.api.ScriptDiagnostic
/**
* Cached configurations for the file's specific snapshot state.
*
* The writer should put related inputs snapshot for loaded configuration.
* This would allow making up-to-date checks for existed entry.
*
* The configuration may be loaded but not applied. So, it makes
* sense to do up-to-date check on loaded configuration (not on applied).
* For those reasons, we are storing both for each file.
*/
interface ScriptConfigurationCache {
operator fun get(file: VirtualFile): ScriptConfigurationState?
fun setApplied(file: VirtualFile, configurationSnapshot: ScriptConfigurationSnapshot)
fun setLoaded(file: VirtualFile, configurationSnapshot: ScriptConfigurationSnapshot)
fun remove(file: VirtualFile): Boolean
fun allApplied(): List<Pair<VirtualFile, ScriptCompilationConfigurationWrapper>>
fun clear()
fun getAnyLoadedScript(): ScriptCompilationConfigurationWrapper?
}
internal sealed class ScriptConfigurationCacheScope {
object All : ScriptConfigurationCacheScope()
class File(val file: KtFile) : ScriptConfigurationCacheScope()
}
data class ScriptConfigurationState(val applied: ScriptConfigurationSnapshot? = null, val loaded: ScriptConfigurationSnapshot? = null) {
fun isUpToDate(project: Project, file: VirtualFile, ktFile: KtFile? = null): Boolean {
return (loaded ?: applied)?.inputs?.isUpToDate(project, file, ktFile) ?: false
}
}
data class ScriptConfigurationSnapshot(
val inputs: CachedConfigurationInputs,
val reports: List<ScriptDiagnostic>,
val configuration: ScriptCompilationConfigurationWrapper?
)
interface CachedConfigurationInputs: Serializable {
fun isUpToDate(project: Project, file: VirtualFile, ktFile: KtFile? = null): Boolean
object OutOfDate : CachedConfigurationInputs {
override fun isUpToDate(project: Project, file: VirtualFile, ktFile: KtFile?): Boolean = false
}
object UpToDate: CachedConfigurationInputs {
override fun isUpToDate(project: Project, file: VirtualFile, ktFile: KtFile?): Boolean = true
}
data class PsiModificationStamp(
val fileModificationStamp: Long,
val psiModificationStamp: Long
) : CachedConfigurationInputs {
override fun isUpToDate(project: Project, file: VirtualFile, ktFile: KtFile?): Boolean =
get(project, file, ktFile) == this
companion object {
fun get(project: Project, file: VirtualFile, ktFile: KtFile?): PsiModificationStamp {
val actualKtFile = project.getKtFile(file, ktFile)
return PsiModificationStamp(
file.modificationStamp,
actualKtFile?.modificationStamp ?: 0
)
}
}
}
data class SourceContentsStamp(val source: String) : CachedConfigurationInputs {
override fun isUpToDate(project: Project, file: VirtualFile, ktFile: KtFile?): Boolean {
return get(file) == this
}
companion object {
fun get(file: VirtualFile): SourceContentsStamp {
val text = runReadAction {
FileDocumentManager.getInstance().getDocument(file)!!.text
}
return SourceContentsStamp(text)
}
}
}
}
| apache-2.0 | 7b527accab7e30aa25b85111ab634d85 | 39.393939 | 158 | 0.722181 | 5.153351 | false | true | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/theme/Dimensions.kt | 1 | 2454 | package com.nononsenseapps.feeder.ui.compose.theme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Immutable
class Dimensions(
/**
* Margin of the navigation button in app bar
*/
val navIconMargin: Dp,
/**
* A gutter is the space between columns that helps separate content.
*/
val gutter: Dp,
/**
* Margins are the space between content and the left and right edges of the screen.
*/
val margin: Dp,
/**
* The max width of the content in case of very wide screens.
*/
val maxContentWidth: Dp,
/**
* The responsive column grid is made up of columns, gutters, and margins, providing a
* convenient structure for the layout of elements within the body region.
* Components, imagery, and text align with the column grid to ensure a logical and
* consistent layout across screen sizes and orientations.
*
* As the size of the body region grows or shrinks, the number of grid columns
* changes in response.
*/
val layoutColumns: Int,
/**
* Number of columns in feed screen
*/
val feedScreenColumns: Int
)
val phoneDimensions = Dimensions(
maxContentWidth = 840.dp,
navIconMargin = 16.dp,
margin = 16.dp,
gutter = 16.dp,
layoutColumns = 4,
feedScreenColumns = 1,
)
val tabletDimensions = Dimensions(
maxContentWidth = 840.dp,
navIconMargin = 32.dp,
margin = 32.dp,
gutter = 32.dp,
layoutColumns = 8,
feedScreenColumns = 2
)
val wideTabletDimensions = Dimensions(
maxContentWidth = 840.dp,
navIconMargin = 32.dp,
margin = 32.dp,
gutter = 32.dp,
layoutColumns = 12,
feedScreenColumns = 4
)
val LocalDimens = staticCompositionLocalOf {
phoneDimensions
}
@Composable
fun ProvideDimens(
content: @Composable () -> Unit,
) {
val config = LocalConfiguration.current
val dimensionSet = remember {
when {
config.smallestScreenWidthDp >= 600 -> tabletDimensions
else -> phoneDimensions
}
}
CompositionLocalProvider(LocalDimens provides dimensionSet, content = content)
}
| gpl-3.0 | fc6502cba5cfed095cced3a0b2a326ba | 26.573034 | 90 | 0.689079 | 4.267826 | false | false | false | false |
prt2121/kotlin-ios | current-address/ios/src/main/kotlin/com/prt2121/currentaddress/PlacemarkViewController.kt | 1 | 2686 | package com.prt2121.currentaddress
import org.robovm.apple.corelocation.CLPlacemark
import org.robovm.apple.foundation.NSIndexPath
import org.robovm.apple.foundation.NSIndexSet
import org.robovm.apple.uikit.UITableViewController
import org.robovm.apple.uikit.UITableViewRowAnimation
import org.robovm.objc.annotation.CustomClass
/**
* Created by pt2121 on 11/28/15.
*/
@CustomClass("PlacemarkViewController")
class PlacemarkViewController : UITableViewController() {
var placemark: CLPlacemark? = null
override fun viewWillAppear(animated: Boolean) {
super.viewWillAppear(animated)
// Get the thoroughfare table cell and set the detail text to show the
// thoroughfare.
var cell = tableView.getCellForRow(NSIndexPath.row(0, 0))
cell.detailTextLabel.text = placemark!!.thoroughfare
// Get the sub-thoroughfare table cell and set the detail text to show
// the sub-thoroughfare.
cell = tableView.getCellForRow(NSIndexPath.row(1, 0))
cell.detailTextLabel.text = placemark!!.subThoroughfare
// Get the locality table cell and set the detail text to show the
// locality.
cell = tableView.getCellForRow(NSIndexPath.row(2, 0))
cell.detailTextLabel.text = placemark!!.locality
// Get the sub-locality table cell and set the detail text to show the
// sub-locality.
cell = tableView.getCellForRow(NSIndexPath.row(3, 0))
cell.detailTextLabel.text = placemark!!.subLocality
// Get the administrative area table cell and set the detail text to
// show the administrative area.
cell = tableView.getCellForRow(NSIndexPath.row(4, 0))
cell.detailTextLabel.text = placemark!!.administrativeArea
// Get the sub-administrative area table cell and set the detail text to
// show the sub-administrative area.
cell = tableView.getCellForRow(NSIndexPath.row(5, 0))
cell.detailTextLabel.text = placemark!!.subAdministrativeArea
// Get the postal code table cell and set the detail text to show the
// postal code.
cell = tableView.getCellForRow(NSIndexPath.row(6, 0))
cell.detailTextLabel.text = placemark!!.postalCode
// Get the country table cell and set the detail text to show the
// country.
cell = tableView.getCellForRow(NSIndexPath.row(7, 0))
cell.detailTextLabel.text = placemark!!.country
// Get the ISO country code table cell and set the detail text to show
// the ISO country code.
cell = tableView.getCellForRow(NSIndexPath.row(8, 0))
cell.detailTextLabel.text = placemark!!.isOcountryCode
// Tell the table to reload section zero of the table.
tableView.reloadSections(NSIndexSet(0), UITableViewRowAnimation.None)
}
} | apache-2.0 | 20b77a49f20a49cd85722756e2abab27 | 38.514706 | 76 | 0.74274 | 4.014948 | false | false | false | false |
allotria/intellij-community | platform/lang-api/src/com/intellij/execution/suggestUsingDashboard.kt | 2 | 2729 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file: JvmName("SuggestUsingRunDashBoardUtil")
package com.intellij.execution
import com.intellij.CommonBundle
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.dashboard.RunDashboardManager
import com.intellij.icons.AllIcons
import com.intellij.lang.LangBundle
import com.intellij.notification.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
/**
* If Run Dashboard is not configured for [configurationTypes], show [Notification] allowing to enable dashboard for those configurations.
**/
fun promptUserToUseRunDashboard(project: Project, configurationTypes: Collection<ConfigurationType>) {
ApplicationManager.getApplication().invokeLater {
val currentTypes = RunDashboardManager.getInstance(project).types
val typesToAdd = configurationTypes.filter {
it.id !in currentTypes
}
if (typesToAdd.isNotEmpty()) {
Notifications.Bus.notify(
SuggestDashboardNotification(project, typesToAdd.toSet(), RunDashboardManager.getInstance(project).toolWindowId), project)
}
}
}
private const val suggestRunDashboardId = "Suggest Run Dashboard"
private class SuggestDashboardNotification(
private val project: Project,
private val types: Set<ConfigurationType>,
toolWindowId: String
) : Notification(
suggestRunDashboardId,
AllIcons.RunConfigurations.TestState.Run,
LangBundle.message("notification.title.use.toolwindow", toolWindowId),
null,
LangBundle.message("notification.suggest.dashboard", toolWindowId, toolWindowId, types.joinToString(prefix = "<b>", postfix = "</b>", separator = "<br>") { it.configurationTypeDescription }),
NotificationType.INFORMATION,
{ _, _ -> }
) {
init {
addAction(NotificationAction.create(CommonBundle.message("button.without.mnemonic.yes")) { _ ->
ApplicationManager.getApplication().invokeLater {
runWriteAction {
val runDashboardManager = RunDashboardManager.getInstance(project)
runDashboardManager.types = runDashboardManager.types + types.map { it.id }
}
}
expire()
})
addAction(NotificationAction.create(LangBundle.message("button.not.this.time.text")) { _ ->
expire()
})
addAction(NotificationAction.create(LangBundle.message("button.do.not.ask.again.text")) { _ ->
NotificationsConfiguration.getNotificationsConfiguration().changeSettings(
suggestRunDashboardId, NotificationDisplayType.NONE, true, false
)
expire()
})
}
} | apache-2.0 | 95b262a2176c205c8bf664f90dc73e38 | 40.363636 | 193 | 0.758153 | 4.746087 | false | true | false | false |
allotria/intellij-community | platform/platform-util-io/src/org/jetbrains/io/Responses.kt | 2 | 4342 | // 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:JvmName("Responses")
package org.jetbrains.io
import com.intellij.openapi.util.NlsSafe
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.ByteBufUtil
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelFutureListener
import io.netty.handler.codec.http.*
import io.netty.util.CharsetUtil
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.util.*
fun response(contentType: String?, content: ByteBuf?): FullHttpResponse {
val response = if (content == null)
DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)
else
DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content)
if (contentType != null) {
response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType)
}
return response
}
fun response(content: CharSequence, charset: Charset = CharsetUtil.US_ASCII): FullHttpResponse {
return DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(content, charset))
}
fun HttpResponse.addNoCache(): HttpResponse {
@Suppress("SpellCheckingInspection")
headers().add(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0")//NON-NLS
headers().add(HttpHeaderNames.PRAGMA, "no-cache")//NON-NLS
return this
}
@JvmOverloads
fun HttpResponse.send(channel: Channel, request: HttpRequest?, extraHeaders: HttpHeaders? = null) {
if (status() != HttpResponseStatus.NOT_MODIFIED && !HttpUtil.isContentLengthSet(this)) {
HttpUtil.setContentLength(this, (if (this is FullHttpResponse) content().readableBytes() else 0).toLong())
}
addCommonHeaders()
extraHeaders?.let {
headers().add(it)
}
send(channel, request != null && !addKeepAliveIfNeeded(request))
}
fun HttpResponse.addKeepAliveIfNeeded(request: HttpRequest): Boolean {
if (HttpUtil.isKeepAlive(request)) {
HttpUtil.setKeepAlive(this, true)
return true
}
return false
}
fun HttpResponse.addCommonHeaders() {
if (!headers().contains(HttpHeaderNames.DATE)) {
headers().set(HttpHeaderNames.DATE, Calendar.getInstance().time)
}
if (!headers().contains(HttpHeaderNames.X_FRAME_OPTIONS)) {
headers().set(HttpHeaderNames.X_FRAME_OPTIONS, "SameOrigin")
}
@Suppress("SpellCheckingInspection")
headers().set("X-Content-Type-Options", "nosniff")//NON-NLS
headers().set("x-xss-protection", "1; mode=block")//NON-NLS
if (status() < HttpResponseStatus.MULTIPLE_CHOICES) {
headers().set(HttpHeaderNames.ACCEPT_RANGES, "bytes")//NON-NLS
}
}
fun HttpResponse.send(channel: Channel, close: Boolean) {
if (!channel.isActive) {
return
}
val future = channel.write(this)
if (this !is FullHttpResponse) {
channel.write(LastHttpContent.EMPTY_LAST_CONTENT)
}
channel.flush()
if (close) {
future.addListener(ChannelFutureListener.CLOSE)
}
}
fun HttpResponseStatus.response(request: HttpRequest? = null, description: String? = null): HttpResponse = createStatusResponse(this, request, description)
@JvmOverloads
fun HttpResponseStatus.send(channel: Channel, request: HttpRequest? = null, description: String? = null, extraHeaders: HttpHeaders? = null) {
createStatusResponse(this, request, description).send(channel, request, extraHeaders)
}
internal fun createStatusResponse(responseStatus: HttpResponseStatus, request: HttpRequest?, description: String? = null): HttpResponse {
if (request != null && request.method() == HttpMethod.HEAD) {
return DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, Unpooled.EMPTY_BUFFER)
}
@NlsSafe
val builder = StringBuilder()
val message = responseStatus.toString()
builder.append("<!doctype html><title>").append(message).append("</title>").append("<h1 style=\"text-align: center\">").append(message).append("</h1>")
if (description != null) {
builder.append("<p>").append(description).append("</p>")
}
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, ByteBufUtil.encodeString(ByteBufAllocator.DEFAULT, CharBuffer.wrap(builder), Charsets.UTF_8))
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html")
return response
} | apache-2.0 | 01adad981d6f1017c6b7a3ab5e980407 | 36.439655 | 172 | 0.749424 | 4.065543 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/console/helpcommands/ConsoleHelpCommand.kt | 1 | 1484 | package com.masahirosaito.spigot.homes.commands.subcommands.console.helpcommands
import com.masahirosaito.spigot.homes.commands.BaseCommand
import com.masahirosaito.spigot.homes.commands.CommandUsage
import com.masahirosaito.spigot.homes.commands.maincommands.homecommands.HomeCommand.Companion.homeCommand
import com.masahirosaito.spigot.homes.commands.subcommands.console.ConsoleCommand
import com.masahirosaito.spigot.homes.strings.commands.HelpCommandStrings.CONSOLE_COMMAND_LIST
import com.masahirosaito.spigot.homes.strings.commands.HelpCommandStrings.DESCRIPTION
import com.masahirosaito.spigot.homes.strings.commands.HelpCommandStrings.USAGE_HELP
import com.masahirosaito.spigot.homes.strings.commands.HelpCommandStrings.USAGE_HELP_COMMAND
import org.bukkit.command.ConsoleCommandSender
class ConsoleHelpCommand : ConsoleCommand {
override val name: String = "help"
override val description: String = DESCRIPTION()
override val commands: List<BaseCommand> = listOf(ConsoleHelpUsageCommand(this))
override val usage: CommandUsage = CommandUsage(this, listOf(
"home help" to USAGE_HELP(),
"home help <command_name>" to USAGE_HELP_COMMAND()
))
override fun configs(): List<Boolean> = listOf()
override fun isValidArgs(args: List<String>): Boolean = args.isEmpty()
override fun execute(consoleCommandSender: ConsoleCommandSender, args: List<String>) {
send(consoleCommandSender, CONSOLE_COMMAND_LIST())
}
}
| apache-2.0 | 31b843231141708bec34b4fdd6165a63 | 50.172414 | 106 | 0.79717 | 4.443114 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/ReferencesInStorageTest.kt | 2 | 16625 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase.assertEmpty
import com.intellij.workspaceModel.storage.entities.*
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
private fun WorkspaceEntityStorage.singleParent() = entities(ParentEntity::class.java).single()
private fun WorkspaceEntityStorage.singleChild() = entities(ChildEntity::class.java).single()
class ReferencesInStorageTest {
private lateinit var virtualFileManager: VirtualFileUrlManager
@Before
fun setUp() {
virtualFileManager = VirtualFileUrlManagerImpl()
}
@Test
fun `add entity`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity("foo"))
builder.assertConsistency()
assertEquals("foo", child.parent.parentProperty)
assertEquals(child, builder.singleChild())
assertEquals(child.parent, builder.singleParent())
assertEquals(child, child.parent.children.single())
}
@Test
fun `add entity via diff`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity("foo")
val diff = createBuilderFrom(builder.toStorage())
diff.addChildEntity(parentEntity = parentEntity)
builder.addDiff(diff)
builder.assertConsistency()
val child = builder.singleChild()
assertEquals("foo", child.parent.parentProperty)
assertEquals(child, builder.singleChild())
assertEquals(child.parent, builder.singleParent())
assertEquals(child, child.parent.children.single())
}
@Test
fun `add remove reference inside data class`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val parent2 = builder.addParentEntity("parent2")
builder.assertConsistency()
val child = builder.addChildEntity(parent1, "child", DataClass("data", builder.createReference(parent2)))
builder.assertConsistency()
assertEquals(child, parent1.children.single())
assertEquals(emptyList<ChildEntity>(), parent2.children.toList())
assertEquals("parent1", child.parent.parentProperty)
assertEquals("parent2", child.dataClass!!.parent.resolve(builder)?.parentProperty)
assertEquals(setOf(parent1, parent2), builder.entities(ParentEntity::class.java).toSet())
builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = null
}
builder.assertConsistency()
assertEquals(setOf(parent1, parent2), builder.entities(ParentEntity::class.java).toSet())
}
@Test
fun `remove child entity`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.assertConsistency()
val child = builder.addChildEntity(parent)
builder.assertConsistency()
builder.removeEntity(child)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ChildEntity>(), parent.children.toList())
assertEquals(parent, builder.singleParent())
}
@Test
fun `remove parent entity`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
builder.removeEntity(child.parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity via diff`() {
val builder = createEmptyBuilder()
val oldParent = builder.addParentEntity("oldParent")
val oldChild = builder.addChildEntity(oldParent, "oldChild")
val diff = createEmptyBuilder()
val parent = diff.addParentEntity("newParent")
diff.addChildEntity(parent, "newChild")
diff.removeEntity(parent)
diff.assertConsistency()
builder.addDiff(diff)
builder.assertConsistency()
assertEquals(listOf(oldChild), builder.entities(ChildEntity::class.java).toList())
assertEquals(listOf(oldParent), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity with two children`() {
val builder = createEmptyBuilder()
val child1 = builder.addChildEntity(builder.addParentEntity())
builder.addChildEntity(parentEntity = child1.parent)
builder.removeEntity(child1.parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity in DAG`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
val child = builder.addChildEntity(parentEntity = parent)
builder.addChildChildEntity(parent, child)
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
// UNSUPPORTED
/*
@Test
fun `remove parent entity referenced via data class`() {
val builder = PEntityStorageBuilder.create()
val parent1 = builder.addPParentEntity("parent1")
val parent2 = builder.addPParentEntity("parent2")
builder.addPChildEntity(parent1, "child", PDataClass("data", builder.createReference(parent2)))
builder.removeEntity(parent2)
builder.assertConsistency()
assertEquals(emptyList<PChildEntity>(), builder.entities(PChildEntity::class.java).toList())
assertEquals(listOf(parent1), builder.entities(PParentEntity::class.java).toList())
assertEquals(emptyList<PChildEntity>(), parent1.children.toList())
}
*/
@Test
fun `remove parent entity referenced via two paths`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.addChildEntity(parent, "child", DataClass("data", builder.createReference(parent)))
builder.assertConsistency()
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity referenced via two paths via entity ref`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.addChildEntity(parent, "child", DataClass("data", parent.createReference()))
builder.assertConsistency()
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `modify parent property`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newParent = builder.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", newParent.parentProperty)
assertEquals(newParent, builder.singleParent())
assertEquals(newParent, child.parent)
assertEquals(child, newParent.children.single())
assertEquals("parent", oldParent.parentProperty)
}
@Test
fun `modify parent property via diff`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val diff = createBuilderFrom(builder)
diff.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.addDiff(diff)
builder.assertConsistency()
val newParent = builder.singleParent()
assertEquals("changed", newParent.parentProperty)
assertEquals(newParent, builder.singleParent())
assertEquals(newParent, child.parent)
assertEquals(child, newParent.children.single())
assertEquals("parent", oldParent.parentProperty)
}
@Test
fun `modify child property`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
childProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", newChild.childProperty)
assertEquals(oldParent, builder.singleParent())
assertEquals(newChild, builder.singleChild())
assertEquals(oldParent, newChild.parent)
assertEquals(oldParent, child.parent)
assertEquals(newChild, oldParent.children.single())
assertEquals("child", child.childProperty)
}
@Test
fun `modify reference to parent`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newParent = builder.addParentEntity("new")
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
parent = newParent
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals(setOf(oldParent, newParent), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.parent)
assertEquals(newChild, newParent.children.single())
assertEquals(newParent, child.parent)
//assertEquals(oldParent, child.parent) // ProxyBasedStore behaviour
assertEquals(emptyList<ChildEntity>(), oldParent.children.toList())
}
@Test
fun `modify reference to parent via data class`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val oldParent = builder.addParentEntity("parent2")
val child = builder.addChildEntity(parent1, "child", DataClass("data", builder.createReference(oldParent)))
val newParent = builder.addParentEntity("new")
builder.assertConsistency()
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data2", builder.createReference(newParent))
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals("data2", newChild.dataClass!!.stringProperty)
assertEquals(setOf(oldParent, newParent, parent1), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.dataClass.parent.resolve(builder))
assertEquals(oldParent, child.dataClass!!.parent.resolve(builder))
}
@Test
fun `modify reference to parent via data class via entity ref`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val oldParent = builder.addParentEntity("parent2")
val child = builder.addChildEntity(parent1, "child", DataClass("data", oldParent.createReference()))
val newParent = builder.addParentEntity("new")
builder.assertConsistency()
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data2", newParent.createReference())
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals("data2", newChild.dataClass!!.stringProperty)
assertEquals(setOf(oldParent, newParent, parent1), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.dataClass.parent.resolve(builder))
assertEquals(oldParent, child.dataClass!!.parent.resolve(builder))
}
@Test
fun `builder from storage`() {
val storage = createEmptyBuilder().apply {
addChildEntity(addParentEntity())
}.toStorage()
storage.assertConsistency()
assertEquals("parent", storage.singleParent().parentProperty)
val builder = createBuilderFrom(storage)
builder.assertConsistency()
val oldParent = builder.singleParent()
assertEquals("parent", oldParent.parentProperty)
val newParent = builder.modifyEntity(ModifiableParentEntity::class.java, oldParent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", builder.singleParent().parentProperty)
assertEquals("parent", storage.singleParent().parentProperty)
assertEquals(newParent, builder.singleChild().parent)
assertEquals("changed", builder.singleChild().parent.parentProperty)
assertEquals("parent", storage.singleChild().parent.parentProperty)
val parent2 = builder.addParentEntity("parent2")
builder.modifyEntity(ModifiableChildEntity::class.java, builder.singleChild()) {
dataClass = DataClass("data", builder.createReference(parent2))
}
builder.assertConsistency()
assertEquals("parent", storage.singleParent().parentProperty)
assertEquals(null, storage.singleChild().dataClass)
assertEquals("data", builder.singleChild().dataClass!!.stringProperty)
assertEquals(parent2, builder.singleChild().dataClass!!.parent.resolve(builder))
assertEquals(setOf(parent2, newParent), builder.entities(ParentEntity::class.java).toSet())
}
@Test
fun `storage from builder`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val snapshot = builder.toStorage()
builder.assertConsistency()
builder.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", builder.singleParent().parentProperty)
assertEquals("changed", builder.singleChild().parent.parentProperty)
assertEquals("parent", snapshot.singleParent().parentProperty)
assertEquals("parent", snapshot.singleChild().parent.parentProperty)
val parent2 = builder.addParentEntity("new")
builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data", builder.createReference(parent2))
}
builder.assertConsistency()
assertEquals("parent", snapshot.singleParent().parentProperty)
assertEquals(null, snapshot.singleChild().dataClass)
assertEquals(parent2, builder.singleChild().dataClass!!.parent.resolve(builder))
}
@Test
fun `modify optional parent property`() {
val builder = createEmptyBuilder()
val child = builder.addChildWithOptionalParentEntity(null)
Assert.assertNull(child.optionalParent)
val newParent = builder.addParentEntity()
assertEquals(emptyList<ChildWithOptionalParentEntity>(), newParent.optionalChildren.toList())
val newChild = builder.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, child) {
optionalParent = newParent
}
builder.assertConsistency()
assertEquals(newParent, newChild.optionalParent)
assertEquals(newChild, newParent.optionalChildren.single())
val veryNewChild = builder.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, newChild) {
optionalParent = null
}
Assert.assertNull(veryNewChild.optionalParent)
assertEquals(emptyList<ChildWithOptionalParentEntity>(), newParent.optionalChildren.toList())
}
@Test
fun `removing one to one parent`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.removeEntity(parentEntity)
val parents = builder.entities(OoParentEntity::class.java).toList()
val children = builder.entities(OoChildEntity::class.java).toList()
assertEmpty(parents)
assertEmpty(children)
}
@Test
fun `add one to one entities`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.assertConsistency()
}
@Test
@Ignore("Not property supported yet")
fun `add child to a single parent`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.addOoChildEntity(parentEntity)
builder.assertConsistency()
}
}
| apache-2.0 | 7a6126a91b4bae03569f324fa50058c0 | 39.351942 | 140 | 0.74388 | 5.013571 | false | true | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-reactive/src/Publish.kt | 1 | 15928 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.reactive
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.intrinsics.*
import kotlinx.coroutines.selects.*
import kotlinx.coroutines.sync.*
import org.reactivestreams.*
import kotlin.coroutines.*
/**
* Creates a cold reactive [Publisher] that runs a given [block] in a coroutine.
*
* Every time the returned flux is subscribed, it starts a new coroutine in the specified [context].
* The coroutine emits (via [Subscriber.onNext]) values with [send][ProducerScope.send],
* completes (via [Subscriber.onComplete]) when the coroutine completes or channel is explicitly closed, and emits
* errors (via [Subscriber.onError]) if the coroutine throws an exception or closes channel with a cause.
* Unsubscribing cancels the running coroutine.
*
* Invocations of [send][ProducerScope.send] are suspended appropriately when subscribers apply back-pressure and to
* ensure that [onNext][Subscriber.onNext] is not invoked concurrently.
*
* Coroutine context can be specified with [context] argument.
* If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is
* used.
*
* **Note: This is an experimental api.** Behaviour of publishers that work as children in a parent scope with respect
* to cancellation and error handling may change in the future.
*
* @throws IllegalArgumentException if the provided [context] contains a [Job] instance.
*/
public fun <T> publish(
context: CoroutineContext = EmptyCoroutineContext,
@BuilderInference block: suspend ProducerScope<T>.() -> Unit
): Publisher<T> {
require(context[Job] === null) { "Publisher context cannot contain job in it." +
"Its lifecycle should be managed via subscription. Had $context" }
return publishInternal(GlobalScope, context, DEFAULT_HANDLER, block)
}
/** @suppress For internal use from other reactive integration modules only */
@InternalCoroutinesApi
public fun <T> publishInternal(
scope: CoroutineScope, // support for legacy publish in scope
context: CoroutineContext,
exceptionOnCancelHandler: (Throwable, CoroutineContext) -> Unit,
block: suspend ProducerScope<T>.() -> Unit
): Publisher<T> = Publisher { subscriber ->
// specification requires NPE on null subscriber
if (subscriber == null) throw NullPointerException("Subscriber cannot be null")
val newContext = scope.newCoroutineContext(context)
val coroutine = PublisherCoroutine(newContext, subscriber, exceptionOnCancelHandler)
subscriber.onSubscribe(coroutine) // do it first (before starting coroutine), to avoid unnecessary suspensions
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
}
private const val CLOSED = -1L // closed, but have not signalled onCompleted/onError yet
private const val SIGNALLED = -2L // already signalled subscriber onCompleted/onError
private val DEFAULT_HANDLER: (Throwable, CoroutineContext) -> Unit = { t, ctx -> if (t !is CancellationException) handleCoroutineException(ctx, t) }
/** @suppress */
@Suppress("CONFLICTING_JVM_DECLARATIONS", "RETURN_TYPE_MISMATCH_ON_INHERITANCE")
@InternalCoroutinesApi
public class PublisherCoroutine<in T>(
parentContext: CoroutineContext,
private val subscriber: Subscriber<T>,
private val exceptionOnCancelHandler: (Throwable, CoroutineContext) -> Unit
) : AbstractCoroutine<Unit>(parentContext, false, true), ProducerScope<T>, Subscription, SelectClause2<T, SendChannel<T>> {
override val channel: SendChannel<T> get() = this
// Mutex is locked when either nRequested == 0 or while subscriber.onXXX is being invoked
private val mutex = Mutex(locked = true)
private val _nRequested = atomic(0L) // < 0 when closed (CLOSED or SIGNALLED)
@Volatile
private var cancelled = false // true after Subscription.cancel() is invoked
override val isClosedForSend: Boolean get() = !isActive
override fun close(cause: Throwable?): Boolean = cancelCoroutine(cause)
override fun invokeOnClose(handler: (Throwable?) -> Unit): Nothing =
throw UnsupportedOperationException("PublisherCoroutine doesn't support invokeOnClose")
override fun trySend(element: T): ChannelResult<Unit> =
if (!mutex.tryLock()) {
ChannelResult.failure()
} else {
when (val throwable = doLockedNext(element)) {
null -> ChannelResult.success(Unit)
else -> ChannelResult.closed(throwable)
}
}
public override suspend fun send(element: T) {
mutex.lock()
doLockedNext(element)?.let { throw it }
}
override val onSend: SelectClause2<T, SendChannel<T>>
get() = this
// registerSelectSend
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun <R> registerSelectClause2(select: SelectInstance<R>, element: T, block: suspend (SendChannel<T>) -> R) {
val clause = suspend {
doLockedNext(element)?.let { throw it }
block(this)
}
launch(start = CoroutineStart.UNDISPATCHED) {
mutex.lock()
// Already selected -- bail out
if (!select.trySelect()) {
mutex.unlock()
return@launch
}
clause.startCoroutineCancellable(select.completion)
}
}
/*
* This code is not trivial because of the following properties:
* 1. It ensures conformance to the reactive specification that mandates that onXXX invocations should not
* be concurrent. It uses Mutex to protect all onXXX invocation and ensure conformance even when multiple
* coroutines are invoking `send` function.
* 2. Normally, `onComplete/onError` notification is sent only when coroutine and all its children are complete.
* However, nothing prevents `publish` coroutine from leaking reference to it send channel to some
* globally-scoped coroutine that is invoking `send` outside of this context. Without extra precaution this may
* lead to `onNext` that is concurrent with `onComplete/onError`, so that is why signalling for
* `onComplete/onError` is also done under the same mutex.
* 3. The reactive specification forbids emitting more elements than requested, so `onNext` is forbidden until the
* subscriber actually requests some elements. This is implemented by the mutex being locked when emitting
* elements is not permitted (`_nRequested.value == 0`).
*/
/**
* Attempts to emit a value to the subscriber and, if back-pressure permits this, unlock the mutex.
*
* Requires that the caller has locked the mutex before this invocation.
*
* If the channel is closed, returns the corresponding [Throwable]; otherwise, returns `null` to denote success.
*
* @throws NullPointerException if the passed element is `null`
*/
private fun doLockedNext(elem: T): Throwable? {
if (elem == null) {
unlockAndCheckCompleted()
throw NullPointerException("Attempted to emit `null` inside a reactive publisher")
}
/** This guards against the case when the caller of this function managed to lock the mutex not because some
* elements were requested--and thus it is permitted to call `onNext`--but because the channel was closed.
*
* It may look like there is a race condition here between `isActive` and a concurrent cancellation, but it's
* okay for a cancellation to happen during `onNext`, as the reactive spec only requires that we *eventually*
* stop signalling the subscriber. */
if (!isActive) {
unlockAndCheckCompleted()
return getCancellationException()
}
// notify the subscriber
try {
subscriber.onNext(elem)
} catch (cause: Throwable) {
/** The reactive streams spec forbids the subscribers from throwing from [Subscriber.onNext] unless the
* element is `null`, which we check not to be the case. Therefore, we report this exception to the handler
* for uncaught exceptions and consider the subscription cancelled, as mandated by
* https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.3/README.md#2.13.
*
* Some reactive implementations, like RxJava or Reactor, are known to throw from [Subscriber.onNext] if the
* execution encounters an exception they consider to be "fatal", like [VirtualMachineError] or
* [ThreadDeath]. Us using the handler for the undeliverable exceptions to signal "fatal" exceptions is
* inconsistent with RxJava and Reactor, which attempt to bubble the exception up the call chain as soon as
* possible. However, we can't do much better here, as simply throwing from all methods indiscriminately
* would violate the contracts we place on them. */
cancelled = true
val causeDelivered = close(cause)
unlockAndCheckCompleted()
return if (causeDelivered) {
// `cause` is the reason this channel is closed
cause
} else {
// Someone else closed the channel during `onNext`. We report `cause` as an undeliverable exception.
exceptionOnCancelHandler(cause, context)
getCancellationException()
}
}
// now update nRequested
while (true) { // lock-free loop on nRequested
val current = _nRequested.value
if (current < 0) break // closed from inside onNext => unlock
if (current == Long.MAX_VALUE) break // no back-pressure => unlock
val updated = current - 1
if (_nRequested.compareAndSet(current, updated)) {
if (updated == 0L) {
// return to keep locked due to back-pressure
return null
}
break // unlock if updated > 0
}
}
unlockAndCheckCompleted()
return null
}
private fun unlockAndCheckCompleted() {
/*
* There is no sense to check completion before doing `unlock`, because completion might
* happen after this check and before `unlock` (see `signalCompleted` that does not do anything
* if it fails to acquire the lock that we are still holding).
* We have to recheck `isCompleted` after `unlock` anyway.
*/
mutex.unlock()
// check isCompleted and and try to regain lock to signal completion
if (isCompleted && mutex.tryLock()) {
doLockedSignalCompleted(completionCause, completionCauseHandled)
}
}
// assert: mutex.isLocked() & isCompleted
private fun doLockedSignalCompleted(cause: Throwable?, handled: Boolean) {
try {
if (_nRequested.value == SIGNALLED)
return
_nRequested.value = SIGNALLED // we'll signal onError/onCompleted (the final state, so no CAS needed)
// Specification requires that after the cancellation is requested we eventually stop calling onXXX
if (cancelled) {
// If the parent failed to handle this exception, then we must not lose the exception
if (cause != null && !handled) exceptionOnCancelHandler(cause, context)
return
}
if (cause == null) {
try {
subscriber.onComplete()
} catch (e: Throwable) {
handleCoroutineException(context, e)
}
} else {
try {
// This can't be the cancellation exception from `cancel`, as then `cancelled` would be `true`.
subscriber.onError(cause)
} catch (e: Throwable) {
if (e !== cause) {
cause.addSuppressed(e)
}
handleCoroutineException(context, cause)
}
}
} finally {
mutex.unlock()
}
}
override fun request(n: Long) {
if (n <= 0) {
// Specification requires to call onError with IAE for n <= 0
cancelCoroutine(IllegalArgumentException("non-positive subscription request $n"))
return
}
while (true) { // lock-free loop for nRequested
val cur = _nRequested.value
if (cur < 0) return // already closed for send, ignore requests, as mandated by the reactive streams spec
var upd = cur + n
if (upd < 0 || n == Long.MAX_VALUE)
upd = Long.MAX_VALUE
if (cur == upd) return // nothing to do
if (_nRequested.compareAndSet(cur, upd)) {
// unlock the mutex when we don't have back-pressure anymore
if (cur == 0L) {
/** In a sense, after a successful CAS, it is this invocation, not the coroutine itself, that owns
* the lock, given that `upd` is necessarily strictly positive. Thus, no other operation has the
* right to lower the value on [_nRequested], it can only grow or become [CLOSED]. Therefore, it is
* impossible for any other operations to assume that they own the lock without actually acquiring
* it. */
unlockAndCheckCompleted()
}
return
}
}
}
// assert: isCompleted
private fun signalCompleted(cause: Throwable?, handled: Boolean) {
while (true) { // lock-free loop for nRequested
val current = _nRequested.value
if (current == SIGNALLED) return // some other thread holding lock already signalled cancellation/completion
check(current >= 0) // no other thread could have marked it as CLOSED, because onCompleted[Exceptionally] is invoked once
if (!_nRequested.compareAndSet(current, CLOSED)) continue // retry on failed CAS
// Ok -- marked as CLOSED, now can unlock the mutex if it was locked due to backpressure
if (current == 0L) {
doLockedSignalCompleted(cause, handled)
} else {
// otherwise mutex was either not locked or locked in concurrent onNext... try lock it to signal completion
if (mutex.tryLock()) doLockedSignalCompleted(cause, handled)
// Note: if failed `tryLock`, then `doLockedNext` will signal after performing `unlock`
}
return // done anyway
}
}
override fun onCompleted(value: Unit) {
signalCompleted(null, false)
}
override fun onCancelled(cause: Throwable, handled: Boolean) {
signalCompleted(cause, handled)
}
override fun cancel() {
// Specification requires that after cancellation publisher stops signalling
// This flag distinguishes subscription cancellation request from the job crash
cancelled = true
super.cancel(null)
}
}
@Deprecated(
message = "CoroutineScope.publish is deprecated in favour of top-level publish",
level = DeprecationLevel.HIDDEN,
replaceWith = ReplaceWith("publish(context, block)")
) // Since 1.3.0, will be error in 1.3.1 and hidden in 1.4.0. Binary compatibility with Spring
public fun <T> CoroutineScope.publish(
context: CoroutineContext = EmptyCoroutineContext,
@BuilderInference block: suspend ProducerScope<T>.() -> Unit
): Publisher<T> = publishInternal(this, context, DEFAULT_HANDLER, block)
| apache-2.0 | 6b81ce82c4d00874521efa10bb6b13f3 | 47.560976 | 148 | 0.647351 | 4.905451 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-rx3/src/RxMaybe.kt | 1 | 2379 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.rx3
import io.reactivex.rxjava3.core.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* Creates cold [maybe][Maybe] that will run a given [block] in a coroutine and emits its result.
* If [block] result is `null`, [onComplete][MaybeObserver.onComplete] is invoked without a value.
* Every time the returned observable is subscribed, it starts a new coroutine.
* Unsubscribing cancels running coroutine.
* Coroutine context can be specified with [context] argument.
* If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
* Method throws [IllegalArgumentException] if provided [context] contains a [Job] instance.
*/
public fun <T> rxMaybe(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> T?
): Maybe<T> {
require(context[Job] === null) { "Maybe context cannot contain job in it." +
"Its lifecycle should be managed via Disposable handle. Had $context" }
return rxMaybeInternal(GlobalScope, context, block)
}
private fun <T> rxMaybeInternal(
scope: CoroutineScope, // support for legacy rxMaybe in scope
context: CoroutineContext,
block: suspend CoroutineScope.() -> T?
): Maybe<T> = Maybe.create { subscriber ->
val newContext = scope.newCoroutineContext(context)
val coroutine = RxMaybeCoroutine(newContext, subscriber)
subscriber.setCancellable(RxCancellable(coroutine))
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
}
private class RxMaybeCoroutine<T>(
parentContext: CoroutineContext,
private val subscriber: MaybeEmitter<T>
) : AbstractCoroutine<T>(parentContext, false, true) {
override fun onCompleted(value: T) {
try {
if (value == null) subscriber.onComplete() else subscriber.onSuccess(value)
} catch (e: Throwable) {
handleUndeliverableException(e, context)
}
}
override fun onCancelled(cause: Throwable, handled: Boolean) {
try {
if (subscriber.tryOnError(cause)) {
return
}
} catch (e: Throwable) {
cause.addSuppressed(e)
}
handleUndeliverableException(cause, context)
}
}
| apache-2.0 | cc0ac2abf45192cf8ac72c2f6de33806 | 37.370968 | 123 | 0.698193 | 4.365138 | false | false | false | false |
zdary/intellij-community | platform/credential-store/src/linuxSecretLibrary.kt | 5 | 9392 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.jna.DisposableMemory
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.text.nullize
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.function.Supplier
// Matching by name fails on locked keyring, because matches against `org.freedesktop.Secret.Generic`
// https://mail.gnome.org/archives/gnome-keyring-list/2015-November/msg00000.html
private const val SECRET_SCHEMA_DONT_MATCH_NAME = 2
private const val SECRET_SCHEMA_ATTRIBUTE_STRING = 0
private const val DBUS_ERROR_SERVICE_UNKNOWN = 2
private const val SECRET_ERROR_IS_LOCKED = 2
// explicitly create pointer to be explicitly dispose it to avoid sensitive data in the memory
internal fun stringPointer(data: ByteArray, clearInput: Boolean = false): DisposableMemory {
val pointer = DisposableMemory(data.size + 1L)
pointer.write(0, data, 0, data.size)
pointer.setByte(data.size.toLong(), 0.toByte())
if (clearInput) {
data.fill(0)
}
return pointer
}
// we use default collection, it seems no way to use custom
internal class SecretCredentialStore private constructor(schemeName: String) : CredentialStore {
private val serviceAttributeNamePointer by lazy { stringPointer("service".toByteArray()) }
private val accountAttributeNamePointer by lazy { stringPointer("account".toByteArray()) }
companion object {
// no need to load lazily - if store created, then it will be used
// and for clients better to get error earlier, in creation place
private val library = Native.load("secret-1", SecretLibrary::class.java)
private val DBUS_ERROR = library.g_dbus_error_quark()
private val SECRET_ERROR = library.secret_error_get_quark()
fun create(schemeName: String): SecretCredentialStore? {
if (!pingService()) return null
return SecretCredentialStore(schemeName)
}
private fun pingService(): Boolean {
var attr: DisposableMemory? = null
var dummySchema: Pointer? = null
try {
attr = stringPointer("ij-dummy-attribute".toByteArray())
dummySchema = library.secret_schema_new("IJ.dummy.ping.schema", SECRET_SCHEMA_DONT_MATCH_NAME,
attr, SECRET_SCHEMA_ATTRIBUTE_STRING,
null)
val errorRef = GErrorByRef()
library.secret_password_lookup_sync(dummySchema, null, errorRef, attr, attr)
val error = errorRef.getValue()
if (error == null) return true
if (isNoSecretService(error)) return false
}
finally {
attr?.close()
dummySchema?.let { library.secret_schema_unref(it) }
}
return true
}
private fun isNoSecretService(error: GError) = when(error.domain) {
DBUS_ERROR -> error.code == DBUS_ERROR_SERVICE_UNKNOWN
else -> false
}
}
private val schema by lazy {
library.secret_schema_new(schemeName, SECRET_SCHEMA_DONT_MATCH_NAME,
serviceAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING,
accountAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING,
null)
}
override fun get(attributes: CredentialAttributes): Credentials? {
val start = System.currentTimeMillis()
try {
val credentials = CompletableFuture.supplyAsync(Supplier {
val userName = attributes.userName.nullize()
checkError("secret_password_lookup_sync") { errorRef ->
val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray())
if (userName == null) {
library.secret_password_lookup_sync(schema, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, null)?.let {
// Secret Service doesn't allow to get attributes, so, we store joined data
return@Supplier splitData(it)
}
}
else {
library.secret_password_lookup_sync(schema, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(userName.toByteArray()),
null)?.let {
return@Supplier splitData(it)
}
}
}
}, AppExecutorUtil.getAppExecutorService())
.get(30 /* on Linux first access to keychain can cause system unlock dialog, so, allow user to input data */, TimeUnit.SECONDS)
val end = System.currentTimeMillis()
if (credentials == null && end - start > 300) {
//todo: use complex API instead
return ACCESS_TO_KEY_CHAIN_DENIED
}
return credentials
}
catch (e: TimeoutException) {
LOG.warn("storage unlock timeout")
return CANNOT_UNLOCK_KEYCHAIN
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray())
val accountName = attributes.userName.nullize() ?: credentials?.userName
val lookupName = if (attributes.serviceName == SERVICE_NAME_PREFIX) accountName else null
if (credentials.isEmpty()) {
clearPassword(serviceNamePointer, lookupName)
return
}
val passwordPointer = stringPointer(credentials!!.serialize(!attributes.isPasswordMemoryOnly), true)
checkError("secret_password_store_sync") { errorRef ->
try {
clearPassword(serviceNamePointer, null)
if (accountName == null) {
library.secret_password_store_sync(schema, null, serviceNamePointer, passwordPointer, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
null)
}
else {
library.secret_password_store_sync(schema, null, serviceNamePointer, passwordPointer, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(accountName.toByteArray()),
null)
}
}
finally {
passwordPointer.close()
}
}
}
private fun clearPassword(serviceNamePointer: DisposableMemory, accountName: String?) {
checkError("secret_password_clear_sync") { errorRef ->
if (accountName == null) {
library.secret_password_clear_sync(schema, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
null)
}
else {
library.secret_password_clear_sync(schema, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(accountName.toByteArray()),
null)
}
}
}
private inline fun <T> checkError(method: String, task: (errorRef: GErrorByRef) -> T): T {
val errorRef = GErrorByRef()
val result = task(errorRef)
val error = errorRef.getValue()
if (error != null) {
if (isNoSecretService(error)) {
LOG.warn("gnome-keyring not installed or kde doesn't support Secret Service API. $method error code ${error.code}, error message ${error.message}")
}
if (error.domain == SECRET_ERROR && error.code == SECRET_ERROR_IS_LOCKED) {
LOG.warn("Cancelled storage unlock: ${error.message}")
}
else {
LOG.error("$method error code ${error.code}, error message ${error.message}")
}
}
return result
}
}
// we use sync API to simplify - client will use postponed write
@Suppress("FunctionName")
private interface SecretLibrary : Library {
fun secret_schema_new(name: String, flags: Int, vararg attributes: Any?): Pointer
fun secret_schema_unref(schema: Pointer)
fun secret_password_store_sync(scheme: Pointer, collection: Pointer?, label: Pointer, password: Pointer, cancellable: Pointer?, error: GErrorByRef?, vararg attributes: Pointer?)
fun secret_password_lookup_sync(scheme: Pointer, cancellable: Pointer?, error: GErrorByRef?, vararg attributes: Pointer?): String?
fun secret_password_clear_sync(scheme: Pointer, cancellable: Pointer?, error: GErrorByRef?, vararg attributes: Pointer?)
fun g_dbus_error_quark(): Int
fun secret_error_get_quark(): Int
}
@Suppress("unused")
@Structure.FieldOrder("domain", "code", "message")
internal class GError(p: Pointer) : Structure(p) {
@JvmField var domain: Int? = null
@JvmField var code: Int? = null
@JvmField var message: String? = null
}
internal class GErrorByRef : com.sun.jna.ptr.ByReference(Native.POINTER_SIZE) {
init {
pointer.setPointer(0, Pointer.NULL)
}
fun getValue(): GError? = pointer.getPointer(0)?.takeIf { it != Pointer.NULL }?.let { GError (it) }?.apply { read() }
}
| apache-2.0 | f24ee8fde43ef229fdede56f0a623627 | 42.082569 | 179 | 0.649915 | 4.777213 | false | false | false | false |
zdary/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/string/GrStringTransformationFixFactory.kt | 12 | 3971 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.style.string
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.GroovyFix
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil
import org.jetbrains.plugins.groovy.lang.psi.util.StringKind
private val FIXES = StringKind.values().map { it to createStringTransformationFix(it) }.toMap()
fun getStringTransformationFix(targetKind: StringKind): GroovyFix = FIXES[targetKind]!!
private fun getCurrentKind(quote: String): StringKind? = when (quote) {
GrStringUtil.DOLLAR_SLASH -> StringKind.DOLLAR_SLASHY
GrStringUtil.SLASH -> StringKind.SLASHY
GrStringUtil.DOUBLE_QUOTES -> StringKind.DOUBLE_QUOTED
GrStringUtil.TRIPLE_QUOTES -> StringKind.TRIPLE_SINGLE_QUOTED
GrStringUtil.TRIPLE_DOUBLE_QUOTES -> StringKind.TRIPLE_DOUBLE_QUOTED
GrStringUtil.QUOTE -> StringKind.SINGLE_QUOTED
else -> null
}
private fun getQuoteByKind(kind: StringKind): String = when (kind) {
StringKind.SINGLE_QUOTED -> GrStringUtil.QUOTE
StringKind.TRIPLE_SINGLE_QUOTED -> GrStringUtil.TRIPLE_QUOTES
StringKind.DOUBLE_QUOTED -> GrStringUtil.DOUBLE_QUOTES
StringKind.TRIPLE_DOUBLE_QUOTED -> GrStringUtil.TRIPLE_DOUBLE_QUOTES
StringKind.SLASHY -> GrStringUtil.SLASH
StringKind.DOLLAR_SLASHY -> GrStringUtil.DOLLAR_SLASH
}
private fun createStringTransformationFix(targetKind: StringKind): GroovyFix = object : GroovyFix() {
override fun getFamilyName(): String {
return GroovyBundle.message("intention.family.name.fix.quotation")
}
override fun getName(): String = when (targetKind) {
StringKind.SINGLE_QUOTED -> GroovyBundle.message("intention.name.convert.to.single.quoted.string")
StringKind.TRIPLE_SINGLE_QUOTED -> GroovyBundle.message("intention.name.change.quotes.to.triple.single.quotes")
StringKind.DOUBLE_QUOTED -> GroovyBundle.message("intention.name.convert.to.double.quoted.string")
StringKind.TRIPLE_DOUBLE_QUOTED -> GroovyBundle.message("intention.name.change.quotes.to.triple.double.quotes")
StringKind.SLASHY -> GroovyBundle.message("intention.name.convert.to.slashy.string")
StringKind.DOLLAR_SLASHY -> GroovyBundle.message("intention.name.convert.to.dollar.slashy.string")
}
private fun escapeTextPart(innerKind: StringKind, text: String): String =
targetKind.escape(innerKind.unescape(text))
private fun getNewText(literal: GrLiteral): String {
val literalText = literal.text
val quote = GrStringUtil.getStartQuote(literalText)
val kind = getCurrentKind(quote) ?: return literalText
return if (literal is GrString) {
literal.allContentParts.joinToString("") { if (it is GrStringContent) escapeTextPart(kind, it.text) else it.text }
}
else {
escapeTextPart(kind, GrStringUtil.removeQuotes(literalText))
}
}
override fun doFix(project: Project, descriptor: ProblemDescriptor) {
val literal = descriptor.psiElement.parentOfType<GrLiteral>(true) ?: return
val newText = getNewText(literal)
val newQuote = getQuoteByKind(targetKind)
val endQuote = if (newQuote == GrStringUtil.DOLLAR_SLASH) GrStringUtil.SLASH_DOLLAR else newQuote
val newExpression = GroovyPsiElementFactory.getInstance(project).createExpressionFromText("$newQuote$newText$endQuote")
literal.replaceWithExpression(newExpression, true)
}
}
| apache-2.0 | cea4dc7d24296c242e5d9e5ce06bbb9f | 50.571429 | 140 | 0.788718 | 4.011111 | false | false | false | false |
zdary/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/application/impl/ExpirableExecutorTest.kt | 6 | 1892 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ExpirableExecutor
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.util.concurrency.AppExecutorUtil
import kotlinx.coroutines.*
import java.util.concurrent.Executor
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
class ExpirableExecutorTest : LightPlatformTestCase() {
fun `test coroutine on background thread`() = runBlocking {
checkBackgroundCoroutine(AppExecutorUtil.getAppExecutorService())
checkBackgroundCoroutine(AppExecutorUtil.createBoundedApplicationPoolExecutor("bounded", 1))
}
private suspend fun checkBackgroundCoroutine(executor: Executor) {
val appExecutor = ExpirableExecutor.on(executor)
GlobalScope.async(appExecutor.coroutineDispatchingContext()) {
assertFalse(ApplicationManager.getApplication().isDispatchThread)
}.join()
}
fun `test coroutine canceled once expired`() {
val disposable = Disposable { }.also { Disposer.register(testRootDisposable, it) }
val context = ExpirableExecutor.on(AppExecutorUtil.getAppExecutorService())
.expireWith(disposable)
.coroutineDispatchingContext()
val startSignal = Semaphore(0)
runBlocking {
val job = launch(context + CoroutineName("blabla")) {
@Suppress("BlockingMethodInNonBlockingContext")
startSignal.tryAcquire(10, TimeUnit.SECONDS)
this.ensureActive()
}
Disposer.dispose(disposable)
startSignal.release()
job.join()
assertTrue(job.isCompleted && job.isCancelled)
}
}
} | apache-2.0 | 0e1d1465f88d5def263409298f1587cf | 38.4375 | 140 | 0.770613 | 4.992084 | false | true | false | false |
leafclick/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/hasattr/PyHasAttrHelper.kt | 1 | 3818 | package com.jetbrains.python.psi.impl.references.hasattr
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.PlatformIcons
import com.jetbrains.python.PyNames
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.ResolveResultList
import com.jetbrains.python.psi.resolve.RatedResolveResult
object PyHasAttrHelper {
fun addHasAttrResolveResults(psiElement: PsiElement, referencedName: String, qualifier: PyExpression, ret: ResolveResultList) {
val hasAttrVariants = getHasAttrVariantsFromContext(psiElement, qualifier)
for (variant in hasAttrVariants.keys) {
if (variant == referencedName) {
ret.add(RatedResolveResult(RatedResolveResult.RATE_NORMAL, hasAttrVariants[variant]))
return
}
}
}
fun addHasAttrCompletionResults(psiElement: PsiElement, qualifier: PyExpression,
namesAlready: MutableSet<String>, variants: MutableCollection<Any>) {
for (variant in variants) {
if (variant is LookupElement) {
namesAlready.add(variant.lookupString)
}
else {
namesAlready.add(variant.toString())
}
}
for (variant in getHasAttrVariantsFromContext(psiElement, qualifier).keys) {
if (!namesAlready.contains(variant)) {
variants.add(LookupElementBuilder.create(variant)
.withTypeText(PyNames.HAS_ATTR)
.withIcon(PlatformIcons.FIELD_ICON))
namesAlready.add(variant)
}
}
}
private fun getHasAttrVariantsFromContext(psiElement: PsiElement, qualifier: PyExpression): Map<String, PsiElement> {
val result = hashMapOf<String, PsiElement>()
result.putAll(getHasAttrVariantsFromAnd(psiElement, qualifier))
result.putAll(getHasAttrVariantsFromConditions(psiElement, qualifier))
return result
}
private fun getHasAttrVariantsFromAnd(psiElement: PsiElement, qualifier: PyExpression): Map<String, PsiElement> {
val result = hashMapOf<String, PsiElement>()
val binaryExpr = PsiTreeUtil.getParentOfType(psiElement, PyBinaryExpression::class.java) ?: return result
if (!binaryExpr.isOperator(PyNames.AND)) return result
if (!PsiTreeUtil.isAncestor(binaryExpr.rightExpression, psiElement, false)) return result
result.putAll(getHasAttrVisitorResultOn(binaryExpr.leftExpression, qualifier))
return result
}
private fun getHasAttrVariantsFromConditions(psiElement: PsiElement, qualifier: PyExpression): Map<String, PsiElement> {
val result = hashMapOf<String, PsiElement>()
var curParent = PsiTreeUtil.getParentOfType(psiElement, PyIfPart::class.java, PyConditionalExpression::class.java)
while (curParent != null) {
val condition = when {
curParent is PyIfPart && PsiTreeUtil.isAncestor(curParent.statementList, psiElement, true) -> curParent.condition
curParent is PyConditionalExpression && PsiTreeUtil.isAncestor(curParent.truePart, psiElement, false) -> curParent.condition
else -> null
}
if (condition != null) {
result.putAll(getHasAttrVisitorResultOn(condition, qualifier))
}
curParent = PsiTreeUtil.getParentOfType(curParent, PyIfPart::class.java, PyConditionalExpression::class.java)
}
return result
}
private fun getHasAttrVisitorResultOn(psiElement: PsiElement, qualifier: PyExpression): Map<String, PsiElement> {
if (qualifier !is PyReferenceExpression) return hashMapOf()
val resolvedQualifier = qualifier.reference.resolve() ?: return hashMapOf()
val pyHasAttrVisitor = PyHasAttrVisitor(resolvedQualifier)
psiElement.accept(pyHasAttrVisitor)
return pyHasAttrVisitor.result
}
} | apache-2.0 | 3bc746301d537ec61a8ba13157eeb7ea | 42.896552 | 132 | 0.743059 | 4.673195 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/modcrafters/mclib/ingredients/implementations/NoIngredient.kt | 1 | 387 | package net.modcrafters.mclib.ingredients.implementations
import net.modcrafters.mclib.ingredients.IMachineIngredient
import net.modcrafters.mclib.ingredients.IngredientAmountMatch
object NoIngredient: IMachineIngredient {
override fun isMatch(ingredient: IMachineIngredient, amountMatch: IngredientAmountMatch) =
ingredient === NoIngredient
override val amount = 0
}
| mit | 5e44b4d5fbcf9e0ff30b5809a78f68dd | 34.181818 | 94 | 0.819121 | 4.662651 | false | false | false | false |
ktoolz/file-finder | core/src/main/kotlin/com/github/ktoolz/filefinder/matching/namespace.kt | 1 | 7614 | /*
* File-Finder - KToolZ
*
* Copyright (c) 2016
*
* 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.github.ktoolz.filefinder.matching
import com.github.ktoolz.filefinder.model.MatchResult
import javaslang.collection.List
import java.util.*
/**
* Computes a List of [MatchResult] elements out of a List, while searching for a Pattern.
*
* @param pattern a List of elements composing the pattern to search for
* @param combinations a List of the combinations of [pattern] we want to use for the research (because we want to tolerate some mistakes)
* @receiver a List of elements on which we actually want to search for matching elements
*
* @return a List of [MatchResult] which contains elements matching with our pattern research. They'll be used afterwards to compute the search results.
*/
fun <T> List<T>.matchers(pattern: List<T>, combinations: List<List<T>>): List<MatchResult<T>> {
/**
* Computes a List of [MatchResult] elements out of a List, keeping only the elements matching exactly the pattern which we're searching for.
*
* @param searchPattern the actual pattern we're searching for (exactly) in the provided List
* @param acc because it's recursive, an accumulator of the results we compute during the execution
* @receiver a List of elements on which we actually perform the research
*
* @return a List of [MatchResult] which contains the elements exactly matching with the pattern we provide
*/
tailrec fun <T> List<T>.matchExactly(searchPattern: List<T>,
acc: List<MatchResult<T>>): List<MatchResult<T>> =
when {
searchPattern.isEmpty -> acc
else -> {
val lookupItem = searchPattern.head()
val remainder = dropWhile { it != lookupItem }
if (remainder.isEmpty) {
// not found
List.empty<MatchResult<T>>()
} else {
// found
val distance = Optional.of(indexOf(lookupItem))
val matchResult = MatchResult(lookupItem, true, distance)
remainder.tail().matchExactly(searchPattern.tail(), acc.append(matchResult))
}
}
}
/**
* Computes a List of [MatchResult] elements out of a List, keeping the elements matching with the pattern we're searching for, with some fault tolerance.
* We're using combinations of the search pattern allowing the research to also accept up to 1 mistake or missing characters.
*
* @param searchPattern the pattern we're searching for in the provided List - this function will actually also use the combinations of that pattern.
* @receiver a List of elements on which we actually perform the research
*
* @return a List of [MatchResult] which contains the elements matching with the pattern we provide, with tolerance on mistakes :)
*/
fun List<T>.nGramsSearch(searchPattern: List<T>): List<MatchResult<T>> {
/**
* List of search results for all the combinations
*/
val ngramsMatchResults = combinations.toStream()
.map { matchExactly(it, List.empty()) }
.filter { it.nonEmpty() }
/**
* The best option we can find while searching for the pattern
*/
val bestMatchOption = ngramsMatchResults.headOption().getOrElse(List.empty())
/**
* Creates a [MatchResult] object for a not found element
* @receiver a part of the search pattern which isn't found while searching the list of files
*
* @return a [MatchResult] element stating that this part of the pattern isn't found
*/
fun T.notFound() = MatchResult(this, false, Optional.empty())
/**
* Computes the actual List of [MatchResult] by completing the found ones.
* As the N-Gram can contains less elements than the search query, replace missing elements
* by a 'not found' match result.
*
* @param searchPattern the pattern we're searching for in the provided List
* @param matchResults the results we found during the search process - those results may be incomplete cause
* they might contain less elements than the search query, as mentionned in the comment
* @param acc an accumulator for the recursive calls, containing the complete List we're actually building
*
* @return a List containing all the [MatchResult], matching with the actual length of the search pattern we provided
*/
fun addMissings(searchPattern: List<T>,
matchResults: List<MatchResult<T>>,
acc: List<MatchResult<T>>): List<MatchResult<T>> =
when {
searchPattern.isEmpty -> acc
matchResults.isEmpty -> addMissings(searchPattern.tail(),
matchResults,
acc.append(searchPattern.head().notFound()))
matchResults.head().element == searchPattern.head() -> addMissings(searchPattern.tail(),
matchResults.tail(),
acc.append(matchResults.head()))
else -> addMissings(searchPattern.tail(),
matchResults,
acc.append(searchPattern.head().notFound()))
}
// Hey! Look, this is actually what's returned by [nGramsSearch] in case you didn't notice ;p
return addMissings(searchPattern, bestMatchOption, List.empty())
}
return nGramsSearch(pattern)
}
/**
* Returns the matchers of a String from another one, and its combinations.
*
* @param pattern the pattern we're searching for in the receiver String
* @param combinations combinations of the pattern we will search for as well (used for fault tolerance)
* @receiver the String on which we want to compute the matching
*
* @return a List of [MatchResult] elements containing all the matchers elements for that research
*/
fun String.matchers(pattern: String, combinations: List<List<Char>>): List<MatchResult<Char>> =
List.ofAll(toCharArray()).matchers(List.ofAll(pattern.toCharArray()), combinations)
| mit | 1bb4862b254ee6a6184c43f749782982 | 56.681818 | 463 | 0.637641 | 5.072618 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/custom/BreathingProgress.kt | 1 | 3504 | package tech.salroid.filmy.ui.custom
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.FrameLayout
import tech.salroid.filmy.R
import kotlin.math.ceil
class BreathingProgress : FrameLayout {
constructor(context: Context) : super(context) {
init(context)
}
//XML Inflation
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
}
private fun init(context: Context) {
//createMainProgressBar
createProgress(context)
//invalidate and redraw the views.
invalidate()
requestLayout()
//nowShowBreathingAnimation
breathingAnimation()
}
private fun breathingAnimation() {
val breather = findViewById<View>(R.id.breather) as FrameLayout
animate(breather)
}
private fun createProgress(context: Context) {
val r = resources
val dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 50f, r.displayMetrics)
val widthPxForFixedRing = getPx(50)
val heightPxForFixedRing = getPx(50)
val fixedRingLayout = FrameLayout(context)
val layoutParams = LayoutParams(
widthPxForFixedRing,
heightPxForFixedRing,
Gravity.CENTER_HORIZONTAL or Gravity.CENTER_VERTICAL
)
fixedRingLayout.layoutParams = layoutParams
fixedRingLayout.setBackgroundResource(R.drawable.awesome_filmy_progress)
val widthPxForBreathingCircle = getPx(20)
val heightPxForBreathingCircle = getPx(20)
val breathingCircleLayout = FrameLayout(context)
val layoutParamsBreathing = LayoutParams(
widthPxForBreathingCircle,
heightPxForBreathingCircle,
Gravity.CENTER_HORIZONTAL or Gravity.CENTER_VERTICAL
)
breathingCircleLayout.layoutParams = layoutParamsBreathing
breathingCircleLayout.setBackgroundResource(R.drawable.filmy_circle)
breathingCircleLayout.id = R.id.breather
fixedRingLayout.addView(breathingCircleLayout)
this.addView(fixedRingLayout)
}
private fun getPx(dp: Int): Int {
val displayMetrics = DisplayMetrics()
(context as Activity).windowManager.defaultDisplay.getMetrics(displayMetrics)
val logicalDensity = displayMetrics.density
return ceil((dp * logicalDensity).toDouble()).toInt()
}
private fun animate(view: View) {
val mAnimation = ScaleAnimation(
0.5f,
1f,
0.5f,
1f,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
mAnimation.duration = 1000
mAnimation.repeatCount = -1
mAnimation.repeatMode = Animation.REVERSE
mAnimation.interpolator = AccelerateInterpolator()
mAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {}
override fun onAnimationRepeat(animation: Animation) {}
})
view.animation = mAnimation
}
} | apache-2.0 | e872a7f12cb2cec81b074be1afbd52c7 | 31.155963 | 93 | 0.68008 | 4.647215 | false | false | false | false |
eggeral/3d-playground | src/main/kotlin/glmatrix/Vec3.kt | 1 | 24776 | package glmatrix
import kotlin.js.Math
class Vec3() : GlMatrix() {
private val vector: Array<Double> = arrayOf(0.0, 0.0, 0.0)
public var x: Double
get() = this[0]
set(value) {
this[0] = value; }
public var y: Double
get() = this[1]
set(value) {
this[1] = value; }
public var z: Double
get() = this[2]
set(value) {
this[2] = value; }
constructor(componentX: Double, componentY: Double, componentZ: Double) : this() {
vector[0] = componentX
vector[1] = componentY
vector[2] = componentZ
}
operator fun get(index: Int): Double {
return vector[index]
}
operator fun set(index: Int, value: Double) {
vector[index] = value
}
/**
* Creates vec3ToClone new Vec3 initialized with values from an existing vector
*
* @param {Vec3} vec3ToClone vector to clone
* @returns {Vec3} vec3ToClone new 3D vector
*/
fun clone(): Vec3 {
return Vec3(this.vector[0], this.vector[1], this.vector[2])
}
/**
* Calculates the length of vec3ToCalculateLengthOf Vec3
*
* @param {Vec3} vec3ToCalculateLengthOf vector to calculate length of
* @returns {Number} length of vec3ToCalculateLengthOf
*/
fun length(): Double {
val x = this.vector[0]
val y = this.vector[1]
val z = this.vector[2]
return Math.sqrt(x * x + y * y + z * z)
}
/**
* Calculates the size of Vec3
*
* @returns {Number} elements of Vec3
*/
fun size(): Int {
return this.vector.size
}
/**
* Copy the values from one Vec3 to another
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} source the source vector
* @returns {Vec3} inOut
*/
fun copy(source: Vec3): Vec3 {
this.vector[0] = source[0]
this.vector[1] = source[1]
this.vector[2] = source[2]
return this
}
/**
* Adds two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} firstSummand the first operand
* @param {Vec3} secondSummand the second operand
* @returns {Vec3} inOut
*/
fun add(summand: Vec3): Vec3 {
this.vector[0] += summand[0]
this.vector[1] += summand[1]
this.vector[2] += summand[2]
return this
}
operator fun plus(summand: Vec3): Vec3 {
return clone().add(summand)
}
/**
* Subtracts vector subtrahend from vector minuend
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} minuend the first operand
* @param {Vec3} subtrahend the second operand
* @returns {Vec3} inOut
*/
fun subtract(subtrahend: Vec3): Vec3 {
this.vector[0] -= subtrahend[0]
this.vector[1] -= subtrahend[1]
this.vector[2] -= subtrahend[2]
return this
}
operator fun minus(subtrahend: Vec3): Vec3 {
return clone().subtract(subtrahend)
}
/**
* Multiplies two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} multiplier the first operand
* @param {Vec3} multiplicand the second operand
* @returns {Vec3} inOut
*/
fun multiply(multiplier: Vec3): Vec3 {
this.vector[0] *= multiplier[0]
this.vector[1] *= multiplier[1]
this.vector[2] *= multiplier[2]
return this
}
operator fun times(multiplier: Vec3): Vec3 {
return multiplier.clone().multiply(this)
}
/**
* Divides two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} dividend the first operand
* @param {Vec3} divisor the second operand
* @returns {Vec3} inOut
*/
fun divide(divisor: Vec3): Vec3 {
this.vector[0] /= divisor[0]
this.vector[1] /= divisor[1]
this.vector[2] /= divisor[2]
return this
}
operator fun div(divisor: Vec3): Vec3 {
return clone().divide(divisor)
}
/**
* Math.ceil the components of vec3ToCeil Vec3
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToCeil vector to ceil
* @returns {Vec3} inOut
*/
fun ceil(): IntArray {
val output = IntArray(3)
output[0] = Math.ceil(this.vector[0])
output[1] = Math.ceil(this.vector[1])
output[2] = Math.ceil(this.vector[2])
return output
}
/**
* Math.floor the components of vec3ToFloor Vec3
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToFloor vector to floor
* @returns {Vec3} inOut
*/
fun floor(): IntArray {
val output = IntArray(3)
output[0] = Math.floor(this.vector[0])
output[1] = Math.floor(this.vector[1])
output[2] = Math.floor(this.vector[2])
return output
}
/**
* Returns the minimum of two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @returns {Vec3} inOut
*/
fun min(operand: Vec3): Vec3 {
return Vec3(Math.min(this.vector[0], operand[0]),
Math.min(this.vector[1], operand[1]),
Math.min(this.vector[2], operand[2]))
}
/**
* Returns the maximum of two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @returns {Vec3} inOut
*/
fun max(operand: Vec3): Vec3 {
return Vec3(Math.max(this.vector[0], operand[0]),
Math.max(this.vector[1], operand[1]),
Math.max(this.vector[2], operand[2]))
}
/**
* Math.round the components of vec3ToRound Vec3
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToRound vector to round
* @returns {Vec3} inOut
*/
fun round(): Vec3 {
return Vec3((Math.round(this[0])).toDouble(),
(Math.round(this[1])).toDouble(),
(Math.round(this[2])).toDouble())
}
/**
* Scales vec3ToScale Vec3 by vec3ToScale scalar number
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToScale the vector to scale
* @param {Number} amountToScaleBy amount to scale the vector by
* @returns {Vec3} inOut
*/
fun scale(amountToScaleBy: Double): Vec3 {
val output = Vec3()
output[0] = this.vector[0] * amountToScaleBy
output[1] = this.vector[1] * amountToScaleBy
output[2] = this.vector[2] * amountToScaleBy
return output
}
/**
* Adds two Vec3's after scaling the second operand by firstSummand scalar value
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} firstSummand the first operand
* @param {Vec3} secondSummand the second operand
* @param {Number} amountToScale the amount to amountToScale secondSummand by before adding
* @returns {Vec3} inOut
*/
fun scaleAndAdd(summand: Vec3, amountToScale: Double): Vec3 {
val output = Vec3()
output[0] = this.vector[0] + (summand[0] * amountToScale)
output[1] = this.vector[1] + (summand[1] * amountToScale)
output[2] = this.vector[2] + (summand[2] * amountToScale)
return output
}
/**
* Calculates the euclidian distance between two Vec3's
*
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @returns {Number} distance between firstOperand and secondOperand
*/
fun distance(operand: Vec3): Double {
val x = this.vector[0] - operand[0]
val y = this.vector[1] - operand[1]
val z = this.vector[2] - operand[2]
return Math.sqrt(x * x + y * y + z * z)
}
/**
* Calculates the squared euclidian distance between two Vec3's
*
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @returns {Number} squared distance between firstOperand and secondOperand
*/
fun squaredDistance(operand: Vec3): Double {
val x = this.vector[0] - operand[0]
val y = this.vector[1] - operand[1]
val z = this.vector[2] - operand[2]
return x * x + y * y + z * z
}
/**
* Calculates the squared length of vec3ToCalculateSquaredLength Vec3
*
* @param {Vec3} vec3ToCalculateSquaredLength vector to calculate squared length of
* @returns {Number} squared length of vec3ToCalculateSquaredLength
*/
fun squaredLength(): Double {
val x = this.vector[0]
val y = this.vector[1]
val z = this.vector[2]
return x * x + y * y + z * z
}
/**
* Negates the components of vec3ToNegate Vec3
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToNegate vector to negate
* @returns {Vec3} inOut
*/
fun negate(): Vec3 {
val output = Vec3()
output[0] = -this.vector[0]
output[1] = -this.vector[1]
output[2] = -this.vector[2]
return output
}
/**
* Returns the inverse of the components of vec3ToInvert Vec3
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToInvert vector to invert
* @returns {Vec3} inOut
*/
fun inverse(): Vec3 {
val output = Vec3()
output[0] = 1.0 / this.vector[0]
output[1] = 1.0 / this.vector[1]
output[2] = 1.0 / this.vector[2]
return output
}
/**
* Normalize vec3ToNormalize Vec3
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToNormalize vector to normalize
* @returns {Vec3} inOut
*/
fun normalize(): Vec3 {
val output = Vec3()
val x = this.vector[0]
val y = this.vector[1]
val z = this.vector[2]
var len = x * x + y * y + z * z
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len)
output[0] = this.vector[0] * len
output[1] = this.vector[1] * len
output[2] = this.vector[2] * len
}
return output
}
/**
* Calculates the dot product of two Vec3's
*
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @returns {Number} dot product of firstOperand and secondOperand
*/
fun dot(operand: Vec3): Double {
return this.vector[0] * operand[0] + this.vector[1] * operand[1] + this.vector[2] * operand[2]
}
/**
* Computes the cross product of two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @returns {Vec3} inOut
*/
fun cross(operand: Vec3): Vec3 {
val output = Vec3()
val ax = this.vector[0]
val ay = this.vector[1]
val az = this.vector[2]
val bx = operand[0]
val by = operand[1]
val bz = operand[2]
output[0] = ay * bz - az * by
output[1] = az * bx - ax * bz
output[2] = ax * by - ay * bx
return output
}
/**
* Performs a linear interpolation between two Vec3's
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} firstOperand the first operand
* @param {Vec3} secondOperand the second operand
* @param {Number} interpolationAmount interpolation amount between the two inputs
* @returns {Vec3} inOut
*/
fun lerp(operand: Vec3, interpolationAmount: Double): Vec3 {
val output = Vec3()
val ax = this.vector[0]
val ay = this.vector[1]
val az = this.vector[2]
output[0] = ax + interpolationAmount * (operand[0] - ax)
output[1] = ay + interpolationAmount * (operand[1] - ay)
output[2] = az + interpolationAmount * (operand[2] - az)
return output
}
/**
* Performs a hermite interpolation with two control points
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} `this.vector` the first operand
* @param {Vec3} firstOperand the second operand
* @param {Vec3} secondOperand the third operand
* @param {Vec3} thirdOperand the fourth operand
* @param {Number} interpolationAmount interpolation amount between the two inputs
* @returns {Vec3} inOut
*/
fun hermite(firstOperand: Vec3, secondOperand: Vec3, thirdOperand: Vec3, interpolationAmount: Double): Vec3 {
val output = Vec3()
val factorTimes2 = interpolationAmount * interpolationAmount
val factor1 = factorTimes2 * (2 * interpolationAmount - 3) + 1
val factor2 = factorTimes2 * (interpolationAmount - 2) + interpolationAmount
val factor3 = factorTimes2 * (interpolationAmount - 1)
val factor4 = factorTimes2 * (3 - 2 * interpolationAmount)
output[0] = this.vector[0] * factor1 + firstOperand[0] * factor2 + secondOperand[0] * factor3 + thirdOperand[0] * factor4
output[1] = this.vector[1] * factor1 + firstOperand[1] * factor2 + secondOperand[1] * factor3 + thirdOperand[1] * factor4
output[2] = this.vector[2] * factor1 + firstOperand[2] * factor2 + secondOperand[2] * factor3 + thirdOperand[2] * factor4
return output
}
/**
* Performs a bezier interpolation with two control points
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} `this.vector` the first operand
* @param {Vec3} firstOperand the second operand
* @param {Vec3} secondOperand the third operand
* @param {Vec3} thirdOperand the fourth operand
* @param {Number} interpolationAmount interpolation amount between the two inputs
* @returns {Vec3} inOut
*/
fun bezier(firstOperand: Vec3, secondOperand: Vec3, thirdOperand: Vec3, interpolationAmount: Double): Vec3 {
val output = Vec3()
val inverseFactor = 1 - interpolationAmount
val inverseFactorTimesTwo = inverseFactor * inverseFactor
val factorTimes2 = interpolationAmount * interpolationAmount
val factor1 = inverseFactorTimesTwo * inverseFactor
val factor2 = 3 * interpolationAmount * inverseFactorTimesTwo
val factor3 = 3 * factorTimes2 * inverseFactor
val factor4 = factorTimes2 * interpolationAmount
output[0] = this.vector[0] * factor1 + firstOperand[0] * factor2 + secondOperand[0] * factor3 + thirdOperand[0] * factor4
output[1] = this.vector[1] * factor1 + firstOperand[1] * factor2 + secondOperand[1] * factor3 + thirdOperand[1] * factor4
output[2] = this.vector[2] * factor1 + firstOperand[2] * factor2 + secondOperand[2] * factor3 + thirdOperand[2] * factor4
return output
}
/**
* Generates a random vector with the given vectorScale
*
* @param {Vec3} inOut the receiving vector
* @param {Number} [vectorScale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {Vec3} inOut
*/
fun random(vectorScale: Double = 1.0): Vec3 {
val output = Vec3()
val r = RANDOM * 2.0 * Math.PI
val z = (RANDOM * 2.0) - 1.0
val zScale = Math.sqrt(1.0 - z * z) * vectorScale
output[0] = Math.cos(r) * zScale
output[1] = Math.sin(r) * zScale
output[2] = z * vectorScale
return output
}
/**
* Transforms the Vec3 with vec3ToTransform Mat4.
* 4th vector component is implicitly '1'
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToTransform the vector to transform
* @param {Mat4} mat4ToTransformWith matrix to transform with
* @returns {Vec3} inOut
*/
fun transformMat4(mat4ToTransformWith: DoubleArray): Vec3 {
val output = Vec3()
val x = this.vector[0]
val y = this.vector[1]
val z = this.vector[2]
var w = mat4ToTransformWith[3] * x + mat4ToTransformWith[7] * y + mat4ToTransformWith[11] * z + mat4ToTransformWith[15]
if (w < 0 || w > 1.0) {
w = 1.0
}
output[0] = (mat4ToTransformWith[0] * x + mat4ToTransformWith[4] * y + mat4ToTransformWith[8] * z + mat4ToTransformWith[12]) / w
output[1] = (mat4ToTransformWith[1] * x + mat4ToTransformWith[5] * y + mat4ToTransformWith[9] * z + mat4ToTransformWith[13]) / w
output[2] = (mat4ToTransformWith[2] * x + mat4ToTransformWith[6] * y + mat4ToTransformWith[10] * z + mat4ToTransformWith[14]) / w
return output
}
fun transformMat4(m: Mat4): Vec3 {
return transformMat4(m.toDoubleArray())
}
/**
* Transforms the Vec3 with vec3ToTransform Mat3.
*
* @param {Mat3} mat3ToTransformWith the 3x3 matrix to transform with
* @returns {Vec3} inOut
*/
fun transformMat3(mat3ToTransformWith: DoubleArray): Vec3 {
val output = Vec3()
val x = this.vector[0]
val y = this.vector[1]
val z = this.vector[2]
output[0] = x * mat3ToTransformWith[0] + y * mat3ToTransformWith[3] + z * mat3ToTransformWith[6]
output[1] = x * mat3ToTransformWith[1] + y * mat3ToTransformWith[4] + z * mat3ToTransformWith[7]
output[2] = x * mat3ToTransformWith[2] + y * mat3ToTransformWith[5] + z * mat3ToTransformWith[8]
return output
}
/**
* Transforms the Vec3 with vec3ToTransform Quat
*
* @param {Vec3} inOut the receiving vector
* @param {Vec3} vec3ToTransform the vector to transform
* @param {Quat} quatToTransformWith quaternion to transform with
* @returns {Vec3} inOut
*/
fun transformQuat(quatToTransformWith: Quat): Vec3 {
// benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
val output = Vec3()
val x = this.vector[0]
val y = this.vector[1]
val z = this.vector[2]
val qx = quatToTransformWith[0]
val qy = quatToTransformWith[1]
val qz = quatToTransformWith[2]
val qw = quatToTransformWith[3]
// calculate Quat * vec
val ix = qw * x + qy * z - qz * y
val iy = qw * y + qz * x - qx * z
val iz = qw * z + qx * y - qy * x
val iw = -qx * x - qy * y - qz * z
// calculate result * inverse Quat
output[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy
output[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz
output[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx
return output
}
/**
* Rotate vec3ToRotate 3D vector around the x-axis
* @param {Vec3} inOut The receiving Vec3
* @param {Vec3} vec3ToRotate The Vec3 point to rotate
* @param {Vec3} originOfRotation The origin of the rotation
* @param {Number} angleInRad The angle of rotation
* @returns {Vec3} inOut
*/
fun rotateX(originOfRotation: Array<Double>, angleInRad: Double): Vec3 {
val output = Vec3()
//Translate point to the origin
val p = arrayOf(
(this.vector[0] - originOfRotation[0]),
(this.vector[1] - originOfRotation[1]),
(this.vector[2] - originOfRotation[2])
)
//perform rotation
val r = arrayOf(
p[0],
(p[1] * Math.cos(angleInRad) - p[2] * Math.sin(angleInRad)),
(p[1] * Math.sin(angleInRad) + p[2] * Math.cos(angleInRad))
)
//translate to correct position
output[0] = r[0] + originOfRotation[0]
output[1] = r[1] + originOfRotation[1]
output[2] = r[2] + originOfRotation[2]
return output
}
/**
* Rotate vec3ToRotate 3D vector around the y-axis
* @param {Vec3} inOut The receiving Vec3
* @param {Vec3} vec3ToRotate The Vec3 point to rotate
* @param {Vec3} originOfRotation The origin of the rotation
* @param {Number} angleInRad The angle of rotation
* @returns {Vec3} inOut
*/
fun rotateY(originOfRotation: Array<Double>, angleInRad: Double): Vec3 {
val output = Vec3()
//Translate point to the origin
val p = arrayOf(
(this.vector[0] - originOfRotation[0]),
(this.vector[1] - originOfRotation[1]),
(this.vector[2] - originOfRotation[2])
)
//perform rotation
val r = arrayOf(
(p[2] * Math.sin(angleInRad) + p[0] * Math.cos(angleInRad)),
p[1],
(p[2] * Math.cos(angleInRad) - p[0] * Math.sin(angleInRad))
)
//translate to correct position
output[0] = r[0] + originOfRotation[0]
output[1] = r[1] + originOfRotation[1]
output[2] = r[2] + originOfRotation[2]
return output
}
/**
* Rotate vec3ToRotate 3D vector around the z-axis
* @param {Vec3} inOut The receiving Vec3
* @param {Vec3} vec3ToRotate The Vec3 point to rotate
* @param {Vec3} originOfRotation The origin of the rotation
* @param {Number} angleInRad The angle of rotation
* @returns {Vec3} inOut
*/
fun rotateZ(originOfRotation: Array<Double>, angleInRad: Double): Vec3 {
val output = Vec3()
//Translate point to the origin
val p = arrayOf(
(this.vector[0] - originOfRotation[0]),
(this.vector[1] - originOfRotation[1]),
(this.vector[2] - originOfRotation[2])
)
//perform rotation
val r = arrayOf(
(p[0] * Math.cos(angleInRad) - p[1] * Math.sin(angleInRad)),
(p[0] * Math.sin(angleInRad) + p[1] * Math.cos(angleInRad)),
p[2]
)
//translate to correct position
output[0] = r[0] + originOfRotation[0]
output[1] = r[1] + originOfRotation[1]
output[2] = r[2] + originOfRotation[2]
return output
}
/**
* Get the angle between two 3D vectors
* @param {Vec3} firstVec3 The first operand
* @param {Vec3} secondVec3 The second operand
* @returns {Number} The angle in radians
*/
fun angle(vector: Vec3): Double {
val tempA = Vec3(this.vector[0], this.vector[1], this.vector[2]).normalize()
val tempB = Vec3(vector[0], vector[1], vector[2]).normalize()
val cosine = tempA.dot(tempB)
if (cosine > 1.0) {
return 0.0
} else if (cosine < -1.0) {
return Math.PI
} else {
return Math.acos(cosine)
}
}
/**
* Returns a string representation of a vector
*
* @param {Vec3} a vector to represent as a string
* @returns {String} string representation of the vector
*/
override fun toString(): String {
return "Vec3(${this.vector[0]}, ${this.vector[1]}, ${this.vector[2]})"
}
/**
* Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
*
* @param {Vec3} firstVector The first vector.
* @param {Vec3} secondVector The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
fun exactEquals(vector: Vec3): Boolean {
return this.vector[0] == vector[0] && this.vector[1] == vector[1] && this.vector[2] == vector[2]
}
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {Vec3} firstVector The first vector.
* @param {Vec3} secondVector The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
fun equals(vector: Vec3): Boolean {
val a0 = this.vector[0]
val a1 = this.vector[1]
val a2 = this.vector[2]
val b0 = vector[0]
val b1 = vector[1]
val b2 = vector[2]
return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)))
}
/**
* Sets this vector to the position elements of the transformation matrix m.
*/
fun setFromMatrixPosition(m: Mat4): Vec3 {
return this.set(m.getTranslation())
}
fun set(x: Double, y: Double, z: Double): Vec3 {
this.x = x
this.y = y
this.z = z
return this
}
fun set(v: Vec3): Vec3 {
this.x = v.x
this.y = v.y
this.z = v.z
return this
}
}
| apache-2.0 | c573d07b2bb98f15118245cec6d6b3cb | 33.220994 | 137 | 0.583306 | 3.573118 | false | false | false | false |
AndroidX/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/list/LazyListHeaders.kt | 3 | 3639 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.foundation.lazy.list
import androidx.compose.ui.util.fastForEachIndexed
/**
* This method finds the sticky header in composedItems list or composes the header item if needed.
*
* @param composedVisibleItems list of items already composed and expected to be visible. if the
* header wasn't in this list but is needed the header will be added as the first item in this list.
* @param itemProvider the provider so we can compose a header if it wasn't composed already
* @param headerIndexes list of indexes of headers. Must be sorted.
* @param beforeContentPadding the padding before the first item in the list
*/
internal fun findOrComposeLazyListHeader(
composedVisibleItems: MutableList<LazyListPositionedItem>,
itemProvider: LazyMeasuredItemProvider,
headerIndexes: List<Int>,
beforeContentPadding: Int,
layoutWidth: Int,
layoutHeight: Int,
): LazyListPositionedItem? {
var currentHeaderOffset: Int = Int.MIN_VALUE
var nextHeaderOffset: Int = Int.MIN_VALUE
var currentHeaderListPosition = -1
var nextHeaderListPosition = -1
// we use visibleItemsInfo and not firstVisibleItemIndex as visibleItemsInfo list also
// contains all the items which are visible in the start content padding area
val firstVisible = composedVisibleItems.first().index
// find the header which can be displayed
for (index in headerIndexes.indices) {
if (headerIndexes[index] <= firstVisible) {
currentHeaderListPosition = headerIndexes[index]
nextHeaderListPosition = headerIndexes.getOrElse(index + 1) { -1 }
} else {
break
}
}
var indexInComposedVisibleItems = -1
composedVisibleItems.fastForEachIndexed { index, item ->
if (item.index == currentHeaderListPosition) {
indexInComposedVisibleItems = index
currentHeaderOffset = item.offset
} else {
if (item.index == nextHeaderListPosition) {
nextHeaderOffset = item.offset
}
}
}
if (currentHeaderListPosition == -1) {
// we have no headers needing special handling
return null
}
val measuredHeaderItem = itemProvider.getAndMeasure(DataIndex(currentHeaderListPosition))
var headerOffset = if (currentHeaderOffset != Int.MIN_VALUE) {
maxOf(-beforeContentPadding, currentHeaderOffset)
} else {
-beforeContentPadding
}
// if we have a next header overlapping with the current header, the next one will be
// pushing the current one away from the viewport.
if (nextHeaderOffset != Int.MIN_VALUE) {
headerOffset = minOf(headerOffset, nextHeaderOffset - measuredHeaderItem.size)
}
return measuredHeaderItem.position(headerOffset, layoutWidth, layoutHeight).also {
if (indexInComposedVisibleItems != -1) {
composedVisibleItems[indexInComposedVisibleItems] = it
} else {
composedVisibleItems.add(0, it)
}
}
}
| apache-2.0 | 0b16d500563b0fc5796662ba81118fcb | 38.129032 | 100 | 0.705963 | 4.864973 | false | false | false | false |
AndroidX/androidx | testutils/testutils-runtime/src/main/java/androidx/testutils/RecreatedActivity.kt | 3 | 2685 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.testutils
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.fragment.app.FragmentActivity
import org.junit.Assert
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Extension of [FragmentActivity] that keeps track of when it is recreated.
* In order to use this class, have your activity extend it and call
* [recreate] API.
*/
open class RecreatedActivity(
@LayoutRes contentLayoutId: Int = 0
) : FragmentActivity(contentLayoutId) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity = this
}
override fun onResume() {
super.onResume()
resumedLatch?.countDown()
}
override fun onDestroy() {
super.onDestroy()
destroyedLatch?.countDown()
activity = null
}
companion object {
@JvmStatic
var activity: RecreatedActivity? = null
@JvmStatic
internal var resumedLatch: CountDownLatch? = null
@JvmStatic
internal var destroyedLatch: CountDownLatch? = null
@JvmStatic
internal fun clearState() {
activity = null
resumedLatch = null
destroyedLatch = null
}
}
}
/**
* Restarts the [RecreatedActivity] and waits for the new activity to be resumed.
*
* @return The newly-restarted [RecreatedActivity]
*/
@Suppress("UNCHECKED_CAST", "DEPRECATION")
fun <T : RecreatedActivity> androidx.test.rule.ActivityTestRule<T>.recreate(): T {
// Now switch the orientation
RecreatedActivity.resumedLatch = CountDownLatch(1)
RecreatedActivity.destroyedLatch = CountDownLatch(1)
runOnUiThreadRethrow { activity.recreate() }
Assert.assertTrue(RecreatedActivity.resumedLatch!!.await(1, TimeUnit.SECONDS))
Assert.assertTrue(RecreatedActivity.destroyedLatch!!.await(1, TimeUnit.SECONDS))
val newActivity = RecreatedActivity.activity as T
waitForExecution()
RecreatedActivity.clearState()
return newActivity
}
| apache-2.0 | 0b2022907037e78dee3afdeeb9a26752 | 29.511364 | 84 | 0.707635 | 4.574106 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/cli/src/org/jetbrains/kotlin/tools/projectWizard/wizard/YamlWizard.kt | 6 | 2602 | // 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.tools.projectWizard.wizard
import org.jetbrains.kotlin.tools.projectWizard.YamlSettingsParser
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.core.service.IdeaIndependentWizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.Services
import org.jetbrains.kotlin.tools.projectWizard.core.service.ServicesManager
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardService
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin
import java.nio.file.Path
class YamlWizard(
private val yaml: String,
private val projectPath: Path,
createPlugins: (Context) -> List<Plugin>,
servicesManager: ServicesManager = CLI_SERVICES_MANAGER,
isUnitTestMode: Boolean
) : Wizard(createPlugins, servicesManager, isUnitTestMode) {
override fun apply(
services: List<WizardService>,
phases: Set<GenerationPhase>,
onTaskExecuting: (PipelineTask) -> Unit
): TaskResult<Unit> = computeM {
val (settingsValuesFromYaml) = context.read { parseYaml(yaml, pluginSettings) }
context.writeSettings {
settingsValuesFromYaml.forEach { (reference, value) -> reference.setValue(value) }
StructurePlugin.projectPath.reference.setValue(projectPath)
}
super.apply(services, phases, onTaskExecuting)
}
companion object {
val CLI_SERVICES_MANAGER = ServicesManager(Services.IDEA_INDEPENDENT_SERVICES) { services ->
services.firstOrNull { it is IdeaIndependentWizardService }
}
}
}
fun Reader.parseYaml(
yaml: String,
pluginSettings: List<PluginSetting<*, *>>
): TaskResult<Map<SettingReference<*, *>, Any>> {
val parsingData = ParsingState(TemplatesPlugin.templates.propertyValue, emptyMap())
val yamlParser = YamlSettingsParser(pluginSettings, parsingData)
return yamlParser.parseYamlText(yaml)
}
| apache-2.0 | f251277e2184daeaea94f5c6f6daaa70 | 45.464286 | 158 | 0.774404 | 4.517361 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/ui/lesson/note/base/BaseLessonNoteImplementation.kt | 1 | 3432 | package com.goldenpiedevs.schedule.app.ui.lesson.note.base
import android.graphics.Color
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.esafirm.imagepicker.features.ImagePicker
import com.esafirm.imagepicker.model.Image
import com.goldenpiedevs.schedule.app.core.dao.note.DaoNoteModel
import com.goldenpiedevs.schedule.app.core.dao.note.DaoNotePhoto
import com.goldenpiedevs.schedule.app.core.utils.preference.AppPreference
import com.goldenpiedevs.schedule.app.ui.base.BasePresenterImpl
import com.goldenpiedevs.schedule.app.ui.fragment.keeper.FragmentKeeperActivity
import com.goldenpiedevs.schedule.app.ui.lesson.note.adapter.NotePhotosAdapter
import com.goldenpiedevs.schedule.app.ui.lesson.note.photo.PhotoPreviewFragment
import org.jetbrains.anko.startActivity
open class BaseLessonNoteImplementation<T : BaseLessonNoteView> : BasePresenterImpl<T>(), BaseLessonNotePresenter<T> {
protected lateinit var noteModel: DaoNoteModel
protected lateinit var adapter: NotePhotosAdapter
var isInEditMode: Boolean = false
private var images = arrayListOf<Image>()
override fun setEditMode(inEditMode: Boolean) {
isInEditMode = inEditMode
}
override fun getNote(lessonId: Int) {
noteModel = DaoNoteModel.get(lessonId, AppPreference.groupId)
images = ArrayList(noteModel.photos.map {
Image(it.id, it.name, it.path)
})
adapter = NotePhotosAdapter(noteModel.photos, isInEditMode) {
it?.let { photo ->
if (isInEditMode) {
deletePhoto(photo)
} else {
showPhoto(photo)
}
} ?: run {
onAddPhotoClick()
}
}
view.setAdapter(adapter,
if (isInEditMode) GridLayoutManager(view.getContext(), calculateNoOfColumns(80f))
else LinearLayoutManager(view.getContext(), RecyclerView.HORIZONTAL, false))
view.setNoteText(noteModel.note)
}
private fun deletePhoto(notePhoto: DaoNotePhoto) {
images.remove(images.first { it.path == notePhoto.path })
onPhotosSelected(images)
}
private fun showPhoto(notePhoto: DaoNotePhoto) {
view.getContext().startActivity<FragmentKeeperActivity>(PhotoPreviewFragment.PHOTO_DATA to notePhoto)
}
private fun onAddPhotoClick() {
ImagePicker.create(view.getIt() as BaseLessonNoteFragment)
.folderMode(true)
.toolbarArrowColor(Color.WHITE)
.includeVideo(false)
.multi()
.origin(images)
.limit(10)
.showCamera(true)
.start()
}
override fun onPhotosSelected(list: ArrayList<Image>) {
this.images = list
adapter.updateData(list.map {
DaoNotePhoto().apply {
id = it.id
path = it.path
name = it.name
}
})
}
private fun calculateNoOfColumns(columnWidthDp: Float): Int {
val displayMetrics = view.getContext().resources.displayMetrics
val screenWidthDp = (displayMetrics.widthPixels - (72 * displayMetrics.density)) / displayMetrics.density
return (screenWidthDp / columnWidthDp + 0.5).toInt()
}
}
| apache-2.0 | ff4d88b005b31aa5ad86dd2db5517416 | 35.126316 | 118 | 0.668124 | 4.569907 | false | false | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/atmosphere/AtmosphereDemo.kt | 1 | 18972 | package de.fabmax.kool.demo.atmosphere
import de.fabmax.kool.AssetManager
import de.fabmax.kool.KoolContext
import de.fabmax.kool.demo.*
import de.fabmax.kool.demo.menu.DemoMenu
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.math.clamp
import de.fabmax.kool.math.toRad
import de.fabmax.kool.modules.atmosphere.OpticalDepthLutPass
import de.fabmax.kool.modules.ui2.*
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.deferred.DeferredPipeline
import de.fabmax.kool.pipeline.deferred.DeferredPipelineConfig
import de.fabmax.kool.pipeline.deferred.PbrSceneShader
import de.fabmax.kool.pipeline.shadermodel.*
import de.fabmax.kool.pipeline.shading.unlitShader
import de.fabmax.kool.scene.*
import de.fabmax.kool.toString
import de.fabmax.kool.util.*
import kotlin.math.cos
import kotlin.math.pow
class AtmosphereDemo : DemoScene("Atmosphere") {
val sunColor = Color.WHITE
val sun = Light().apply {
setDirectional(Vec3f.NEG_Z_AXIS)
setColor(sunColor, 5f)
}
private val sunIntensity = mutableStateOf(1f).onChange { updateSun() }
val time = mutableStateOf(0.5f)
var moonTime = 0f
private val isAnimateTime = mutableStateOf(true)
private val camHeightTxt = mutableStateOf("0 km")
val textures = mutableMapOf<String, Texture2d>()
val textures1d = mutableMapOf<String, Texture1d>()
lateinit var deferredPipeline: DeferredPipeline
val atmoShader = AtmosphericScatteringShader()
val earthGroup = Group("earth")
private lateinit var opticalDepthLutPass: OpticalDepthLutPass
private val shadows = mutableListOf<SimpleShadowMap>()
private val camTransform = EarthCamTransform(earthRadius)
private var sceneSetupComplete = false
private val atmoThickness = mutableStateOf(0f).onChange { updateAtmosphereThickness(it) }
private val atmoFalloff = mutableStateOf(0f).onChange { opticalDepthLutPass.densityFalloff = it }
private val scatteringR = mutableStateOf(0f).onChange { updateScatteringCoeffs(x = it) }
private val scatteringG = mutableStateOf(0f).onChange { updateScatteringCoeffs(y = it) }
private val scatteringB = mutableStateOf(0f).onChange { updateScatteringCoeffs(z = it) }
private val rayleighR = mutableStateOf(0f).onChange { updateRayleighColor(r = it) }
private val rayleighG = mutableStateOf(0f).onChange { updateRayleighColor(g = it) }
private val rayleighB = mutableStateOf(0f).onChange { updateRayleighColor(b = it) }
private val rayleighA = mutableStateOf(0f).onChange { updateRayleighColor(strength = it) }
private val mieStr = mutableStateOf(0f).onChange { updateMieColor(strength = it) }
private val mieG = mutableStateOf(0f).onChange { atmoShader.mieG = it }
val cameraHeight: Float
get() {
return mainScene.camera.globalPos.distance(Vec3f.ZERO) - earthRadius
}
override suspend fun AssetManager.loadResources(ctx: KoolContext) {
loadTex(texMilkyway, "${DemoLoader.assetStorageBase}/solarsystem/stars_bg.jpg")
loadTex(texSun, "${DemoLoader.assetStorageBase}/solarsystem/sun.png")
loadTex(texSunBg, "${DemoLoader.assetStorageBase}/solarsystem/sun_bg.png")
loadTex(texMoon, "${DemoLoader.assetStorageBase}/solarsystem/moon.jpg")
loadTex(EarthShader.texEarthDay, "${DemoLoader.assetStorageBase}/solarsystem/earth_day.jpg")
loadTex(EarthShader.texEarthNight, "${DemoLoader.assetStorageBase}/solarsystem/earth_night.jpg")
loadTex(EarthShader.texEarthNrm, "${DemoLoader.assetStorageBase}/solarsystem/earth_nrm.jpg")
loadTex(EarthShader.texOceanNrm, "${DemoLoader.assetStorageBase}/solarsystem/oceanNrm.jpg")
val heightMapProps = TextureProps(TexFormat.R, AddressMode.CLAMP_TO_EDGE, AddressMode.CLAMP_TO_EDGE, AddressMode.CLAMP_TO_EDGE)
loadTex(EarthShader.texEarthHeight, "${DemoLoader.assetStorageBase}/solarsystem/earth_height_8k.png", heightMapProps)
}
override fun lateInit(ctx: KoolContext) {
camTransform.apply {
+mainScene.camera
}
}
private suspend fun AssetManager.loadTex(key: String, path: String, props: TextureProps = TextureProps()) {
showLoadText("Loading texture \"$key\"...")
textures[key] = loadAndPrepareTexture(path, props)
}
override fun Scene.setupMainScene(ctx: KoolContext) {
opticalDepthLutPass = OpticalDepthLutPass()
addOffscreenPass(opticalDepthLutPass)
lighting.lights.clear()
lighting.lights += sun
shadows += SimpleShadowMap(this, 0)
val defCfg = DeferredPipelineConfig().apply {
isWithAmbientOcclusion = false
isWithScreenSpaceReflections = false
maxGlobalLights = 1
shadowMaps = shadows
pbrSceneShader = makeDeferredPbrShader(this)
isWithVignette = true
isWithChromaticAberration = true
}
deferredPipeline = DeferredPipeline(this, defCfg)
deferredPipeline.lightingPassShader.ambient(Color(0.05f, 0.05f, 0.05f).toLinear())
atmoShader.apply {
opticalDepthLut(opticalDepthLutPass.colorTexture)
surfaceRadius = earthRadius
atmosphereRadius = 6500f / kmPerUnit
scatteringCoeffs = Vec3f(0.75f, 1.10f, 1.35f)
rayleighColor = Color(0.5f, 0.5f, 1f, 1f)
mieColor = Color(1f, 0.35f, 0.35f, 0.5f)
mieG = 0.8f
scatteringCoeffStrength = 1.0f
}
deferredPipeline.onSwap += atmoShader
val shadowScene = Group().apply {
isFrustumChecked = false
+colorMesh("shadowEarth") {
isFrustumChecked = false
generate {
icoSphere {
steps = 5
radius = earthRadius * 1f
}
}
shader = unlitShader { }
}
}
earthGroup += shadowScene
shadows.forEach { shadow ->
//shadow.drawNode = deferredPipeline.contentGroup
shadow.drawNode = shadowScene
shadow.shadowBounds = earthGroup.bounds
//shadow.shadowBounds = deferredPipeline.contentGroup.bounds
}
onUpdate += {
if (!sceneSetupComplete) {
sceneSetupComplete = true
finalizeSceneSetup(deferredPipeline)
earthGroup -= shadowScene
}
(mainScene.camera as PerspectiveCamera).apply {
val h = globalPos.length() - earthRadius
position.set(Vec3f.ZERO)
lookAt.set(Vec3f.NEG_Z_AXIS)
clipNear = (h * 0.5f).clamp(0.003f, 5f)
clipFar = clipNear * 1000f
camHeightTxt.set("${(cameraHeight * kmPerUnit).toString(1)} km")
}
if (isAnimateTime.value) {
val dt = Time.deltaT / 120
// setting time slider value results in timer slider's onChange function being called which also sets time
time.set((time.value + dt) % 1f)
moonTime = (moonTime + dt / moonT)
}
}
onDispose += {
textures.values.forEach { it.dispose() }
textures1d.values.forEach { it.dispose() }
}
atmoFalloff.set(opticalDepthLutPass.densityFalloff)
atmoThickness.set((atmoShader.atmosphereRadius - earthRadius) * kmPerUnit)
scatteringR.set(atmoShader.scatteringCoeffs.x)
scatteringG.set(atmoShader.scatteringCoeffs.y)
scatteringB.set(atmoShader.scatteringCoeffs.z)
rayleighR.set(atmoShader.rayleighColor.r)
rayleighG.set(atmoShader.rayleighColor.g)
rayleighB.set(atmoShader.rayleighColor.b)
rayleighA.set(atmoShader.rayleighColor.a)
mieStr.set(atmoShader.mieColor.a)
mieG.set(atmoShader.mieG)
}
private fun makeDeferredPbrShader(cfg: DeferredPipelineConfig): PbrSceneShader {
val shaderCfg = PbrSceneShader.DeferredPbrConfig().apply {
isScrSpcAmbientOcclusion = cfg.isWithAmbientOcclusion
isScrSpcReflections = cfg.isWithScreenSpaceReflections
maxLights = cfg.maxGlobalLights
shadowMaps += shadows
useImageBasedLighting(cfg.environmentMaps)
}
val model = PbrSceneShader.defaultDeferredPbrModel(shaderCfg).apply {
fragmentStage {
val lightNd = findNodeByType<MultiLightNode>()!!
val pbrNd = findNodeByType<PbrMaterialNode>()!!
val lightGradientTex = texture1dNode("tLightGradient")
addNode(EarthLightColorNode(lightGradientTex, stage)).apply {
inWorldPos = pbrNd.inFragPos
inFragToLight = lightNd.outFragToLightDirection
inRadiance = lightNd.outRadiance
pbrNd.inRadiance = outRadiance
}
}
}
val lightGradientTex = GradientTexture(ColorGradient(
cos(90f.toRad()) to MdColor.ORANGE.mix(Color.WHITE, 0.6f).toLinear(),
cos(85f.toRad()) to MdColor.AMBER.mix(Color.WHITE, 0.6f).toLinear(),
cos(80f.toRad()) to Color.WHITE.toLinear(),
cos(0f.toRad()) to Color.WHITE.toLinear()
))
textures1d[EarthShader.texLightGradient] = lightGradientTex
return PbrSceneShader(shaderCfg, model).apply {
onPipelineCreated += { _, _, _ ->
model.findNode<Texture1dNode>("tLightGradient")?.sampler?.texture = lightGradientTex
}
}
}
private class EarthLightColorNode(val lightColorGradient: Texture1dNode, graph: ShaderGraph) : ShaderNode("earthLightColor", graph) {
lateinit var inWorldPos: ShaderNodeIoVar
lateinit var inFragToLight: ShaderNodeIoVar
lateinit var inRadiance: ShaderNodeIoVar
val outRadiance = ShaderNodeIoVar(ModelVar3f("${name}_outRadiance"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inWorldPos, inFragToLight, inRadiance)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("""
float ${name}_l = clamp(dot(normalize(${inWorldPos.ref3f()}), ${inFragToLight.ref3f()}), 0.0, 1.0);
${outRadiance.declare()} = ${inRadiance.ref3f()} * ${generator.sampleTexture1d(lightColorGradient.name, "${name}_l")}.rgb;
""")
}
}
private fun finalizeSceneSetup(deferredPipeline: DeferredPipeline) {
val skyPass = SkyPass(this)
atmoShader.skyColor(skyPass.colorTexture)
deferredPipeline.sceneContent.setupContent()
mainScene.apply {
+textureMesh {
isFrustumChecked = false
generate {
rect {
mirrorTexCoordsY()
}
}
shader = atmoShader
}
}
updateSun()
}
private fun Group.setupContent() {
+earthGroup.apply {
isFrustumChecked = false
+camTransform
val gridSystem = SphereGridSystem().apply {
val earthShader = EarthShader(textures)
earthShader.heightMap = textures[EarthShader.texEarthHeight]
earthShader.oceanNrmTex = textures[EarthShader.texOceanNrm]
shader = earthShader
onUpdate += {
updateTiles(mainScene.camera.globalPos)
val camHeight = cameraHeight * kmPerUnit
val colorMix = (camHeight / 100f).clamp()
earthShader.uWaterColor?.value?.set(waterColorLow.mix(waterColorHigh, colorMix))
earthShader.uNormalShift?.value?.set(
Time.gameTime.toFloat() * 0.0051f, Time.gameTime.toFloat() * 0.0037f,
Time.gameTime.toFloat() * -0.0071f, Time.gameTime.toFloat() * -0.0039f)
val dirToSun = MutableVec3f(sun.direction).scale(-1f)
earthShader.uDirToSun?.value?.let { uSunDir ->
uSunDir.set(dirToSun)
toLocalCoords(uSunDir, 0f)
}
atmoShader.dirToSun = dirToSun
}
}
+gridSystem
onUpdate += {
setIdentity()
rotate(earthAxisTilt, Vec3f.NEG_X_AXIS)
rotate(time.value * 360, Vec3f.Y_AXIS)
}
}
}
private fun UiScope.ColoredMenuSlider(
color: Color,
value: Float,
min: Float,
max: Float,
txtFormat: (Float) -> String = { it.toString(2) },
txtWidth: Dp = UiSizes.baseSize,
onChange: (Float) -> Unit
) {
Slider(value, min, max) {
modifier
.width(Grow.Std)
.alignY(AlignmentY.Center)
.margin(horizontal = sizes.gap)
.onChange(onChange)
.colors(color, color.withAlpha(0.4f), color.withAlpha(0.7f))
}
if (txtWidth.value > 0f) {
Text(txtFormat(value)) {
labelStyle()
modifier.width(txtWidth).textAlignX(AlignmentX.End)
}
}
}
override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface {
val lblW = UiSizes.baseSize * 1f
val txtW = UiSizes.baseSize * 0.85f
val timeFmt: (Float) -> String = {
val t = it * 24
val h = t.toInt()
val m = ((t % 1f) * 60).toInt()
val m0 = if (m < 10) "0" else ""
"$h:$m0$m"
}
MenuRow {
Text("Sun") { labelStyle(lblW) }
MenuSlider(sunIntensity.use(), 0.1f, 5f, txtWidth = txtW) { sunIntensity.set(it) }
}
MenuRow {
Text("Time") { labelStyle(lblW) }
MenuSlider(time.use(), 0f, 1f, timeFmt, txtWidth = txtW) {
time.set(it)
updateSun()
}
}
MenuRow { LabeledSwitch("Animate time", isAnimateTime) }
MenuRow {
Text("Camera height") { labelStyle(Grow.Std) }
Text(camHeightTxt.use()) { labelStyle() }
}
Text("Atmosphere") { sectionTitleStyle() }
MenuRow {
Text("Thickness") { labelStyle(UiSizes.baseSize * 1.75f) }
MenuSlider(
atmoThickness.use(),
10f,
1000f,
{ it.toString(0) },
txtWidth = txtW)
{ atmoThickness.set(it) }
}
MenuRow {
Text("Falloff") { labelStyle(UiSizes.baseSize * 1.75f) }
MenuSlider(atmoFalloff.use(), 0f, 15f, txtWidth = txtW) { atmoFalloff.set(it) }
}
Text("Scattering") { sectionTitleStyle() }
MenuRow {
Text("Red") { labelStyle(lblW) }
ColoredMenuSlider(MdColor.RED, scatteringR.use(), 0f, 4f, txtWidth = txtW) { scatteringR.set(it) }
}
MenuRow {
Text("Green") { labelStyle(lblW) }
ColoredMenuSlider(MdColor.GREEN, scatteringG.use(), 0f, 4f, txtWidth = txtW) { scatteringG.set(it) }
}
MenuRow {
Text("Blue") { labelStyle(lblW) }
ColoredMenuSlider(MdColor.BLUE, scatteringB.use(), 0f, 4f, txtWidth = txtW) { scatteringB.set(it) }
}
Text("Rayleigh") { sectionTitleStyle() }
MenuRow {
Text("Red") { labelStyle(lblW) }
ColoredMenuSlider(MdColor.RED, rayleighR.use(), 0f, 4f, txtWidth = txtW) { rayleighR.set(it) }
}
MenuRow {
Text("Green") { labelStyle(lblW) }
ColoredMenuSlider(MdColor.GREEN, rayleighG.use(), 0f, 4f, txtWidth = txtW) { rayleighG.set(it) }
}
MenuRow {
Text("Blue") { labelStyle(lblW) }
ColoredMenuSlider(MdColor.BLUE, rayleighB.use(), 0f, 4f, txtWidth = txtW) { rayleighB.set(it) }
}
MenuRow {
Text("Str") { labelStyle(lblW) }
MenuSlider(rayleighA.use(), 0f, 2f, txtWidth = txtW) { rayleighA.set(it) }
}
Text("Mie") { sectionTitleStyle() }
MenuRow {
Text("Str") { labelStyle(lblW) }
MenuSlider(mieStr.use(), 0f, 2f, txtWidth = txtW) { mieStr.set(it) }
}
MenuRow {
Text("g") { labelStyle(lblW) }
MenuSlider(mieG.use(), 0.5f, 0.999f, txtFormat = { it.toString(3) }, txtWidth = txtW) { mieG.set(it) }
}
}
private fun updateSun() {
val lightDir = MutableVec3f(0f, 0f, -1f)
atmoShader.dirToSun = lightDir
atmoShader.sunColor = sunColor.withAlpha(sunIntensity.value)
mainScene.lighting.lights[0].apply {
setDirectional(MutableVec3f(lightDir).scale(-1f))
setColor(sunColor, sunIntensity.value * 5)
}
}
private fun updateRayleighColor(r: Float = atmoShader.rayleighColor.r, g: Float = atmoShader.rayleighColor.g, b: Float = atmoShader.rayleighColor.b, strength: Float = atmoShader.rayleighColor.a) {
atmoShader.rayleighColor = Color(r, g, b, strength)
}
private fun updateMieColor(r: Float = atmoShader.mieColor.r, g: Float = atmoShader.mieColor.g, b: Float = atmoShader.mieColor.b, strength: Float = atmoShader.mieColor.a) {
atmoShader.mieColor = Color(r, g, b, strength)
}
private fun updateScatteringCoeffs(x: Float = atmoShader.scatteringCoeffs.x, y: Float = atmoShader.scatteringCoeffs.y, z: Float = atmoShader.scatteringCoeffs.z) {
atmoShader.scatteringCoeffs = Vec3f(x, y, z)
}
private fun updateAtmosphereThickness(newThickness: Float) {
val atmoRadius = earthRadius + newThickness / kmPerUnit
atmoShader.atmosphereRadius = atmoRadius
opticalDepthLutPass.atmosphereRadius = atmoRadius
}
companion object {
const val kmPerUnit = 100f
const val earthRadius = 6000f / kmPerUnit
const val earthAxisTilt = 15f //23.44f
const val moonRadius = 1750f / kmPerUnit
const val moonDistScale = 0.25f
const val moonDist = 384400 / kmPerUnit * moonDistScale
const val moonInclination = 5.145f
// scaled moon orbital period (according to kepler's 3rd law)
val keplerC = (moonDist / moonDistScale).pow(3) / 27.32f.pow(2)
val moonT = moonDist.pow(3) / keplerC
val waterColorLow = Color.fromHex("0D1F56").toLinear()
val waterColorHigh = Color.fromHex("020514").toLinear()
const val texMilkyway = "Milkyway"
const val texSun = "Sun"
const val texSunBg = "Sun Background"
const val texMoon = "Moon"
}
} | apache-2.0 | 3b1c3a790a71a37165afacfd8109c1de | 38.609603 | 200 | 0.606894 | 3.875792 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/SkillMemberActivity.kt | 1 | 2312 | package com.habitrpg.android.habitica.ui.activities
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.ui.adapter.social.PartyMemberRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.helpers.bindView
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_prefs.*
import javax.inject.Inject
class SkillMemberActivity : BaseActivity() {
private val recyclerView: RecyclerView by bindView(R.id.recyclerView)
private var viewAdapter: PartyMemberRecyclerViewAdapter? = null
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var userRepository: UserRepository
override fun getLayoutResId(): Int {
return R.layout.activity_skill_members
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(toolbar)
loadMemberList()
}
private fun loadMemberList() {
recyclerView.layoutManager = LinearLayoutManager(this)
viewAdapter = PartyMemberRecyclerViewAdapter(null, true)
viewAdapter?.getUserClickedEvents()?.subscribe(Consumer { userId ->
val resultIntent = Intent()
resultIntent.putExtra("member_id", userId)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}, RxErrorHandler.handleEmptyError())?.let { compositeSubscription.add(it) }
recyclerView.adapter = viewAdapter
compositeSubscription.add(userRepository.getUser()
.firstElement()
.flatMap { user -> socialRepository.getGroupMembers(user.party?.id ?: "").firstElement() }
.subscribe(Consumer { viewAdapter?.updateData(it) }, RxErrorHandler.handleEmptyError()))
}
}
| gpl-3.0 | d070b157aca25982b4f98f9f003030e7 | 38.186441 | 106 | 0.744377 | 5.137778 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/QuestDetailFragment.kt | 1 | 12229 | package com.habitrpg.android.habitica.ui.fragments.social
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.facebook.drawee.view.SimpleDraweeView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.inventory.Quest
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.*
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.functions.Consumer
import javax.inject.Inject
import javax.inject.Named
class QuestDetailFragment : BaseMainFragment() {
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var inventoryRepository: InventoryRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
private val questTitleView: TextView? by bindOptionalView(R.id.title_view)
private val questScrollImageView: SimpleDraweeView? by bindOptionalView(R.id.quest_scroll_image_view)
private val questLeaderView: TextView? by bindOptionalView(R.id.quest_leader_view)
private val questDescriptionView: TextView? by bindOptionalView(R.id.description_view)
private val questParticipantList: LinearLayout? by bindOptionalView(R.id.quest_participant_list)
private val participantHeader: TextView? by bindOptionalView(R.id.participants_header)
private val participantHeaderCount: TextView? by bindOptionalView(R.id.participants_header_count)
private val questParticipantResponseWrapper: ViewGroup? by bindOptionalView(R.id.quest_participant_response_wrapper)
private val questLeaderResponseWrapper: ViewGroup? by bindOptionalView(R.id.quest_leader_response_wrapper)
private val questAcceptButton: Button? by bindOptionalView(R.id.quest_accept_button)
private val questRejectButton: Button? by bindOptionalView(R.id.quest_reject_button)
private val questBeginButton: Button? by bindOptionalView(R.id.quest_begin_button)
private val questCancelButton: Button? by bindOptionalView(R.id.quest_cancel_button)
private val questAbortButton: Button? by bindOptionalView(R.id.quest_abort_button)
var partyId: String? = null
var questKey: String? = null
private var party: Group? = null
private var quest: Quest? = null
private var beginQuestMessage: String? = null
private val isQuestActive: Boolean
get() = quest?.active == true
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
this.hidesToolbar = true
return inflater.inflate(R.layout.fragment_quest_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val args = QuestDetailFragmentArgs.fromBundle(it)
partyId = args.partyID
questKey = args.questKey
}
resetViews()
questAcceptButton?.setOnClickListener { onQuestAccept() }
questRejectButton?.setOnClickListener { onQuestReject() }
questBeginButton?.setOnClickListener { onQuestBegin() }
questCancelButton?.setOnClickListener { onQuestCancel() }
questAbortButton?.setOnClickListener { onQuestAbort() }
}
override fun onResume() {
super.onResume()
compositeSubscription.add(socialRepository.getGroup(partyId)
.subscribe(Consumer { this.updateParty(it) }, RxErrorHandler.handleEmptyError()))
if (questKey != null) {
compositeSubscription.add(inventoryRepository.getQuestContent(questKey ?: "")
.subscribe(Consumer { this.updateQuestContent(it) }, RxErrorHandler.handleEmptyError()))
}
}
private fun updateParty(group: Group?) {
if (questTitleView == null || group == null || group.quest == null) {
return
}
party = group
quest = group.quest
setQuestParticipants(group.quest?.participants)
compositeSubscription.add(socialRepository.getMember(quest?.leader).firstElement().subscribe(Consumer { member ->
if (context != null && questLeaderView != null && member != null) {
questLeaderView?.text = context?.getString(R.string.quest_leader_header, member.displayName)
}
}, RxErrorHandler.handleEmptyError()))
if (questLeaderResponseWrapper != null) {
if (showParticipatantButtons()) {
questLeaderResponseWrapper?.visibility = View.GONE
questParticipantResponseWrapper?.visibility = View.VISIBLE
} else if (showLeaderButtons()) {
questParticipantResponseWrapper?.visibility = View.GONE
questLeaderResponseWrapper?.visibility = View.VISIBLE
if (isQuestActive) {
questBeginButton?.visibility = View.GONE
questCancelButton?.visibility = View.GONE
questAbortButton?.visibility = View.VISIBLE
} else {
questBeginButton?.visibility = View.VISIBLE
questCancelButton?.visibility = View.VISIBLE
questAbortButton?.visibility = View.GONE
}
} else {
questLeaderResponseWrapper?.visibility = View.GONE
questParticipantResponseWrapper?.visibility = View.GONE
}
}
}
private fun showLeaderButtons(): Boolean {
return userId == party?.quest?.leader || userId == party?.leaderID
}
private fun showParticipatantButtons(): Boolean {
return if (user == null || user?.party == null || user?.party?.quest == null) {
false
} else !isQuestActive && user?.party?.quest?.RSVPNeeded == true
}
private fun updateQuestContent(questContent: QuestContent) {
if (questTitleView == null || !questContent.isManaged) {
return
}
questTitleView?.text = questContent.text
questDescriptionView?.setMarkdown(questContent.notes)
DataBindingUtils.loadImage(questScrollImageView, "inventory_quest_scroll_" + questContent.key)
}
private fun setQuestParticipants(participants: List<Member>?) {
if (questParticipantList == null) {
return
}
questParticipantList?.removeAllViews()
val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
var participantCount = 0
for (participant in participants ?: emptyList()) {
if (quest?.active == true && participant.participatesInQuest == false) {
continue
}
val participantView = inflater?.inflate(R.layout.quest_participant, questParticipantList, false)
val textView = participantView?.findViewById<View>(R.id.participant_name) as? TextView
textView?.text = participant.displayName
val statusTextView = participantView?.findViewById<View>(R.id.status_view) as? TextView
if (quest?.active == false) {
context?.let {
when {
participant.participatesInQuest == null -> {
statusTextView?.setText(R.string.pending)
statusTextView?.setTextColor(ContextCompat.getColor(it, R.color.gray_200))
}
participant.participatesInQuest == true -> {
statusTextView?.setText(R.string.accepted)
statusTextView?.setTextColor(ContextCompat.getColor(it, R.color.green_100))
}
else -> {
statusTextView?.setText(R.string.declined)
statusTextView?.setTextColor(ContextCompat.getColor(it, R.color.red_100))
}
}
}
questParticipantList?.addView(participantView)
} else {
statusTextView?.visibility = View.GONE
if (participant.participatesInQuest == true) {
questParticipantList?.addView(participantView)
}
}
if (participant.participatesInQuest == true) {
participantCount += 1
}
}
if (quest?.active == true) {
participantHeader?.setText(R.string.participants)
participantHeaderCount?.text = participantCount.toString()
} else {
participantHeader?.setText(R.string.invitations)
participantHeaderCount?.text = participantCount.toString() + "/" + quest?.participants?.size
beginQuestMessage = getString(R.string.quest_begin_message, participantCount, quest?.participants?.size)
}
}
override fun onDestroyView() {
socialRepository.close()
userRepository.close()
inventoryRepository.close()
super.onDestroyView()
}
private fun onQuestAccept() {
partyId?.let { partyID ->
socialRepository.acceptQuest(user, partyID).subscribe(Consumer { }, RxErrorHandler.handleEmptyError())
}
}
private fun onQuestReject() {
partyId?.let { partyID ->
socialRepository.rejectQuest(user, partyID).subscribe(Consumer { }, RxErrorHandler.handleEmptyError())
}
}
private fun onQuestBegin() {
val context = context
if (context != null) {
val alert = HabiticaAlertDialog(context)
alert.setMessage(beginQuestMessage)
alert.addButton(R.string.yes, true) { _, _ ->
val party = party
if (party != null) {
socialRepository.forceStartQuest(party)
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError())
}
}
alert.addButton(R.string.no, false)
alert.show()
}
}
private fun onQuestCancel() {
context?.let {
val alert = HabiticaAlertDialog(it)
alert.setMessage(R.string.quest_cancel_message)
alert.addButton(R.string.yes, true) { _, _ ->
partyId?.let { partyID ->
@Suppress("DEPRECATION")
socialRepository.cancelQuest(partyID)
.subscribe(Consumer { getActivity()?.fragmentManager?.popBackStack() }, RxErrorHandler.handleEmptyError())
}
}
alert.addButton(R.string.no, false)
alert.show()
}
}
private fun onQuestAbort() {
val builder = AlertDialog.Builder(getActivity())
.setMessage(R.string.quest_abort_message)
.setPositiveButton(R.string.yes) { _, _ ->
partyId?.let { partyID ->
@Suppress("DEPRECATION")
socialRepository.abortQuest(partyID)
.subscribe(Consumer { getActivity()?.fragmentManager?.popBackStack() }, RxErrorHandler.handleEmptyError())
}
}.setNegativeButton(R.string.no) { _, _ -> }
builder.show()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
}
| gpl-3.0 | 81715accd2fafc9e82d301c9c212b946 | 42.989209 | 138 | 0.641344 | 5.03251 | false | false | false | false |
zdary/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/annotation/GrAnnotationMethodReference.kt | 17 | 3980 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.annotation
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.util.IncorrectOperationException
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrAnnotationCollector
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_TRANSFORM_ANNOTATION_COLLECTOR
import org.jetbrains.plugins.groovy.lang.resolve.ElementResolveResult
internal class GrAnnotationMethodReference(private val element: GrAnnotationNameValuePair) : GroovyReference {
override fun getElement(): PsiElement = element
override fun getRangeInElement(): TextRange {
val nameId = element.nameIdentifierGroovy!!
return nameId.textRange.shiftLeft(element.textRange.startOffset)
}
override fun getCanonicalText(): String = rangeInElement.substring(element.text)
override fun isReferenceTo(element: PsiElement): Boolean {
return element is PsiMethod && element.getManager().areElementsEquivalent(element, resolve())
}
override fun resolve(incomplete: Boolean): Collection<GroovyResolveResult> {
val annotation = PsiImplUtil.getAnnotation(element) ?: return emptyList()
val ref = annotation.classReference
val resolved = ref.resolve() as? PsiClass ?: return emptyList()
val name = element.name ?: DEFAULT_REFERENCED_METHOD_NAME
val collector = GrAnnotationCollector.findAnnotationCollector(resolved)
if (collector != null) {
return multiResolveFromAlias(annotation, name, collector)
}
else if (resolved.isAnnotationType) {
return resolved.findMethodsByName(name, false).map(::ElementResolveResult)
}
return emptyList()
}
private fun multiResolveFromAlias(alias: GrAnnotation, name: String, annotationCollector: PsiAnnotation): List<GroovyResolveResult> {
val annotations = mutableListOf<GrAnnotation>()
GrAnnotationCollector.collectAnnotations(annotations, alias, annotationCollector)
val result = mutableListOf<GroovyResolveResult>()
for (annotation in annotations) {
val clazz = annotation.classReference.resolve() as? PsiClass ?: continue
if (!clazz.isAnnotationType) continue
if (clazz.qualifiedName == GROOVY_TRANSFORM_ANNOTATION_COLLECTOR) continue
clazz.findMethodsByName(name, false).mapTo(result, ::ElementResolveResult)
}
return result
}
override fun handleElementRename(newElementName: String): PsiElement {
val nameElement = element.nameIdentifierGroovy
val newNameNode = GroovyPsiElementFactory.getInstance(element.project).createReferenceNameFromText(newElementName).node!!
if (nameElement != null) {
val node = nameElement.node
element.node.replaceChild(node, newNameNode)
}
else {
val anchorBefore = element.firstChild?.node
element.node.addLeaf(GroovyTokenTypes.mASSIGN, "=", anchorBefore)
element.node.addChild(newNameNode, anchorBefore)
}
return element
}
override fun bindToElement(element: PsiElement): PsiElement = throw IncorrectOperationException("NYI")
override fun isSoft(): Boolean = false
}
| apache-2.0 | 7f953bda17eb2756f83dfc4a14bf3eee | 46.951807 | 140 | 0.788693 | 4.835966 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/ui/LargeImageView.kt | 1 | 4406 | package com.zhou.android.ui
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.zhou.android.common.Tools
import java.io.IOException
import java.io.InputStream
import kotlin.math.abs
/**
* 鸿洋 LargeImage
* Created by zhou on 2020/5/30.
*/
class LargeImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: View(context, attrs, defStyleAttr) {
private var decoder: BitmapRegionDecoder? = null
private var options = BitmapFactory.Options().apply {
inPreferredConfig = Bitmap.Config.RGB_565
}
private val rect = Rect()
private var imageWidth = 0
private var imageHeight = 0
fun setImageStream(inputStream: InputStream) {
try {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(inputStream, null, options)
imageWidth = options.outWidth
imageHeight = options.outHeight
Log.d("zhou", "setImageStream image[$imageWidth, $imageHeight]")
decoder = BitmapRegionDecoder.newInstance(inputStream, false)
requestLayout()
invalidate()
} catch (e: IOException) {
e.printStackTrace()
} finally {
Tools.closeIO(inputStream)
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
Log.d("zhou", "measure image[$imageWidth, $imageHeight] view[$measuredWidth, $measuredHeight]")
if (imageWidth < 0 || imageHeight < 0)
return
//设定初始显示图片位置
if (measuredWidth > imageWidth) {
rect.left = 0
rect.right = imageWidth
} else {
rect.left = (imageWidth - measuredWidth) / 2
rect.right = rect.left + measuredWidth
}
if (measuredHeight > imageHeight) {
rect.top = 0
rect.bottom = imageHeight
} else {
rect.top = (imageHeight - measuredHeight) / 2
rect.bottom = rect.top + measuredHeight
}
}
override fun onDraw(canvas: Canvas) {
if (decoder == null) {
return
}
try {
val bitmap = decoder!!.decodeRegion(rect, options)
canvas.drawBitmap(bitmap, 0f, 0f, null)
} catch (e: Exception) {
e.printStackTrace()
}
}
private var lastX = 0f
private var lastY = 0f
private var downX = 0f
private var downY = 0f
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
lastX = event.rawX
lastY = event.rawY
downX = event.rawX
downY = event.rawY
}
MotionEvent.ACTION_MOVE -> {
val dx = event.rawX - lastX
val dy = event.rawY - lastY
updateRect(dx, dy)
lastX = event.rawX
lastY = event.rawY
}
MotionEvent.ACTION_UP -> {
if (abs(event.rawX - downX) < 50 && abs(event.rawY - downY) < 50) {
performClick()
}
}
}
return true
}
override fun performClick(): Boolean {
return super.performClick()
}
private fun updateRect(dx: Float, dy: Float) {
// Log.d("zhou", "update x:$dx, y:$dy")
val w = rect.width()
val h = rect.height()
rect.left = (rect.left - dx).toInt()
rect.right = (rect.right - dx).toInt()
rect.top = (rect.top - dy).toInt()
rect.bottom = (rect.bottom - dy).toInt()
if (rect.left < 0) {
rect.left = 0
rect.right = w
}
if (rect.top < 0) {
rect.top = 0
rect.bottom = h
}
if (rect.right > imageWidth) {
rect.right = imageWidth
rect.left = rect.right - w
}
if (rect.bottom > imageHeight) {
rect.bottom = imageHeight
rect.top = imageHeight - h
}
invalidate()
}
} | mit | b5fc5e2846c3df5df18c313b200bee7a | 27.096154 | 116 | 0.548608 | 4.52686 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/handlers/CastReceiverInsertHandler.kt | 1 | 2303 | // 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.completion.handlers
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
object CastReceiverInsertHandler {
fun postHandleInsert(context: InsertionContext, item: LookupElement) {
val expression =
PsiTreeUtil.findElementOfClassAtOffset(context.file, context.startOffset, KtSimpleNameExpression::class.java, false)
val qualifiedExpression = PsiTreeUtil.getParentOfType(expression, KtQualifiedExpression::class.java, true)
if (qualifiedExpression != null) {
val receiver = qualifiedExpression.receiverExpression
val descriptor = (item.`object` as? DeclarationLookupObject)?.descriptor as CallableDescriptor
val project = context.project
val thisObj =
if (descriptor.extensionReceiverParameter != null) descriptor.extensionReceiverParameter else descriptor.dispatchReceiverParameter
val fqName = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(thisObj!!.type.constructor.declarationDescriptor!!)
val parentCast = KtPsiFactory(project).createExpression("(expr as $fqName)") as KtParenthesizedExpression
val cast = parentCast.expression as KtBinaryExpressionWithTypeRHS
cast.left.replace(receiver)
val psiDocumentManager = PsiDocumentManager.getInstance(project)
psiDocumentManager.commitAllDocuments()
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
val expr = receiver.replace(parentCast) as KtParenthesizedExpression
ShortenReferences.DEFAULT.process((expr.expression as KtBinaryExpressionWithTypeRHS).right!!)
}
}
} | apache-2.0 | 7c73355abd50eceb0f165a73e3e596fc | 52.581395 | 158 | 0.767694 | 5.801008 | false | false | false | false |
siosio/intellij-community | java/java-features-trainer/src/com/intellij/java/ift/JavaLangSupport.kt | 1 | 4250 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.ift
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil
import com.intellij.openapi.roots.impl.LanguageLevelProjectExtensionImpl
import com.intellij.openapi.roots.ui.configuration.SdkLookup
import com.intellij.openapi.roots.ui.configuration.SdkLookupDecision
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.java.LanguageLevel
import com.intellij.util.lang.JavaVersion
import training.lang.AbstractLangSupport
import training.learn.LearnBundle
import training.project.ProjectUtils
import training.project.ReadMeCreator
import training.util.getFeedbackLink
import java.nio.file.Path
class JavaLangSupport : AbstractLangSupport() {
override val defaultProjectName = "IdeaLearningProject"
override val projectResourcePath = "learnProjects/java/LearnProject"
override val primaryLanguage: String = "JAVA"
override val defaultProductName: String = "IDEA"
override val filename: String = "Learning.java"
override val projectSandboxRelativePath: String = "Sample.java"
override val langCourseFeedback get() = getFeedbackLink(this, false)
override val readMeCreator = ReadMeCreator()
override fun installAndOpenLearningProject(projectPath: Path,
projectToClose: Project?,
postInitCallback: (learnProject: Project) -> Unit) {
super.installAndOpenLearningProject(projectPath, projectToClose) { project ->
findJavaSdkAsync(project) { sdk ->
if (sdk != null) {
applyProjectSdk(sdk, project)
}
postInitCallback(project)
}
}
}
private fun findJavaSdkAsync(project: Project, onSdkSearchCompleted: (Sdk?) -> Unit) {
val javaSdkType = JavaSdk.getInstance()
val notification = ProjectUtils.createSdkDownloadingNotification()
SdkLookup.newLookupBuilder()
.withSdkType(javaSdkType)
.withVersionFilter {
JavaVersion.tryParse(it)?.isAtLeast(6) == true
}
.onDownloadableSdkSuggested { sdkFix ->
val userDecision = invokeAndWaitIfNeeded {
Messages.showYesNoDialog(
LearnBundle.message("learn.project.initializing.jdk.download.message", sdkFix.downloadDescription),
LearnBundle.message("learn.project.initializing.jdk.download.title"),
null
)
}
if (userDecision == Messages.YES) {
notification.notify(project)
SdkLookupDecision.CONTINUE
}
else {
onSdkSearchCompleted(null)
SdkLookupDecision.STOP
}
}
.onSdkResolved { sdk ->
if (sdk != null && sdk.sdkType === javaSdkType) {
onSdkSearchCompleted(sdk)
DumbService.getInstance(project).runWhenSmart {
notification.expire()
}
}
}
.executeLookup()
}
override fun getSdkForProject(project: Project): Sdk? {
return null
}
override fun applyProjectSdk(sdk: Sdk, project: Project) {
val applySdkAction = {
runWriteAction { JavaSdkUtil.applyJdkToProject(project, sdk) }
}
runInEdt {
CommandProcessor.getInstance().executeCommand(project, applySdkAction, null, null)
}
}
override fun applyToProjectAfterConfigure(): (Project) -> Unit = { newProject ->
//Set language level for LearnProject
LanguageLevelProjectExtensionImpl.getInstanceImpl(newProject).currentLevel = LanguageLevel.JDK_1_6
}
override fun checkSdk(sdk: Sdk?, project: Project) {}
override fun blockProjectFileModification(project: Project, file: VirtualFile): Boolean {
return file.name != projectSandboxRelativePath
}
}
| apache-2.0 | 281b36c9fc607a1b06bad8cac38e2db8 | 35.956522 | 140 | 0.72 | 4.753915 | false | false | false | false |
JetBrains/kotlin-native | performance/objcinterop/src/main/kotlin-native/org/jetbrains/objCinteropBenchmarks/complexNumbers.kt | 4 | 4390 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.complexNumbers
import kotlinx.cinterop.*
import platform.posix.*
import kotlin.math.sqrt
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
import kotlin.random.Random
import platform.Foundation.*
import platform.darwin.*
actual typealias ComplexNumber = Complex
actual class ComplexNumbersBenchmark actual constructor() {
val complexNumbersSequence = generateNumbersSequence()
fun randomNumber() = Random.nextDouble(0.0, benchmarkSize.toDouble())
actual fun generateNumbersSequence(): List<Complex> {
val result = mutableListOf<Complex>()
for (i in 1..benchmarkSize) {
result.add(Complex(randomNumber(), randomNumber()))
}
return result
}
actual fun sumComplex() {
complexNumbersSequence.map { it.add(it) }.reduce { acc, it -> acc.add(it) }
}
actual fun subComplex() {
complexNumbersSequence.map { it.sub(it) }.reduce { acc, it -> acc.sub(it) }
}
actual fun classInheritance() {
class InvertedNumber(val value: Double) : CustomNumberProtocol, NSObject() {
override fun add(other: CustomNumberProtocol) : CustomNumberProtocol =
if (other is InvertedNumber)
InvertedNumber(-value + sqrt(other.value))
else
error("Expected object of InvertedNumber class")
override fun sub(other: CustomNumberProtocol) : CustomNumberProtocol =
if (other is InvertedNumber)
InvertedNumber(-value - sqrt(other.value))
else
error("Expected object of InvertedNumber class")
}
val result = InvertedNumber(0.0)
for (i in 1..benchmarkSize) {
result.add(InvertedNumber(randomNumber()))
result.sub(InvertedNumber(randomNumber()))
}
}
actual fun categoryMethods() {
complexNumbersSequence.map { it.mul(it) }.reduce { acc, it -> acc.mul(it) }
complexNumbersSequence.map { it.div(it) }.reduce { acc, it -> acc.mul(it) }
}
actual fun stringToObjC() {
complexNumbersSequence.forEach {
it.setFormat("%.1lf|%.1lf")
}
}
actual fun stringFromObjC() {
complexNumbersSequence.forEach {
it.description()?.split(" ")
}
}
private fun revert(number: Int, lg: Int): Int {
var result = 0
for (i in 0 until lg) {
if (number and (1 shl i) != 0) {
result = result or 1 shl (lg - i - 1)
}
}
return result
}
inline private fun fftRoutine(invert:Boolean = false): Array<Complex> {
var lg = 0
while ((1 shl lg) < complexNumbersSequence.size) {
lg++
}
val sequence = complexNumbersSequence.toTypedArray()
sequence.forEachIndexed { index, number ->
if (index < revert(index, lg) && revert(index, lg) < complexNumbersSequence.size) {
sequence[index] = sequence[revert(index, lg)].also { sequence[revert(index, lg)] = sequence[index] }
}
}
var length = 2
while (length < complexNumbersSequence.size) {
val angle = 2 * PI / length * if (invert) -1 else 1
val base = Complex(cos(angle), sin(angle))
for (i in 0 until complexNumbersSequence.size / 2 step length) {
var value = Complex(1.0, 1.0)
for (j in 0 until length/2) {
val first = sequence[i + j]
val second = sequence[i + j + length/2].mul(value)
sequence[i + j] = first.add(second) as Complex
sequence[i + j + length/2] = first.sub(second) as Complex
value = value.mul(base)
}
}
length = length shl 1
}
return sequence
}
actual fun fft() {
fftRoutine()
}
actual fun invertFft() {
val sequence = fftRoutine(true)
sequence.forEachIndexed { index, number ->
sequence[index] = number.div(Complex(sequence.size.toDouble(), 0.0))
}
}
}
| apache-2.0 | 499f97a88d8fc7bd461c37dcb94a322e | 31.761194 | 116 | 0.572437 | 4.303922 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/provider/GHPRStateDataProviderImpl.kt | 2 | 4728 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data.provider
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.messages.MessageBus
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityState
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRStateService
import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue
import org.jetbrains.plugins.github.util.completionOnEdt
import java.util.concurrent.CompletableFuture
class GHPRStateDataProviderImpl(private val stateService: GHPRStateService,
private val pullRequestId: GHPRIdentifier,
private val messageBus: MessageBus,
private val detailsData: GHPRDetailsDataProvider)
: GHPRStateDataProvider, Disposable {
private var lastKnownBaseBranch: String? = null
private var lastKnownBaseSha: String? = null
private var lastKnownHeadSha: String? = null
init {
detailsData.addDetailsLoadedListener(this) {
val details = detailsData.loadedDetails ?: return@addDetailsLoadedListener
if (lastKnownBaseBranch != null && lastKnownBaseBranch != details.baseRefName) {
baseBranchProtectionRulesRequestValue.drop()
reloadMergeabilityState()
}
lastKnownBaseBranch = details.baseRefName
if (lastKnownBaseSha != null && lastKnownBaseSha != details.baseRefOid &&
lastKnownHeadSha != null && lastKnownHeadSha != details.headRefOid) {
reloadMergeabilityState()
}
lastKnownBaseSha = details.baseRefOid
lastKnownHeadSha = details.headRefOid
}
}
private val baseBranchProtectionRulesRequestValue = LazyCancellableBackgroundProcessValue.create { indicator ->
detailsData.loadDetails().thenCompose {
stateService.loadBranchProtectionRules(indicator, pullRequestId, it.baseRefName)
}
}
private val mergeabilityStateRequestValue = LazyCancellableBackgroundProcessValue.create { indicator ->
val baseBranchProtectionRulesRequest = baseBranchProtectionRulesRequestValue.value
detailsData.loadDetails().thenCompose { details ->
baseBranchProtectionRulesRequest.thenCompose {
stateService.loadMergeabilityState(indicator, pullRequestId, details.headRefOid, details.url, it)
}
}
}
override fun loadMergeabilityState(): CompletableFuture<GHPRMergeabilityState> = mergeabilityStateRequestValue.value
override fun reloadMergeabilityState() {
if (baseBranchProtectionRulesRequestValue.lastLoadedValue == null)
baseBranchProtectionRulesRequestValue.drop()
mergeabilityStateRequestValue.drop()
}
override fun addMergeabilityStateListener(disposable: Disposable, listener: () -> Unit) =
mergeabilityStateRequestValue.addDropEventListener(disposable, listener)
override fun close(progressIndicator: ProgressIndicator): CompletableFuture<Unit> =
stateService.close(progressIndicator, pullRequestId).notifyState()
override fun reopen(progressIndicator: ProgressIndicator): CompletableFuture<Unit> =
stateService.reopen(progressIndicator, pullRequestId).notifyState()
override fun markReadyForReview(progressIndicator: ProgressIndicator): CompletableFuture<Unit> =
stateService.markReadyForReview(progressIndicator, pullRequestId).notifyState().completionOnEdt {
mergeabilityStateRequestValue.drop()
}
override fun merge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String)
: CompletableFuture<Unit> = stateService.merge(progressIndicator, pullRequestId, commitMessage, currentHeadRef).notifyState()
override fun rebaseMerge(progressIndicator: ProgressIndicator, currentHeadRef: String): CompletableFuture<Unit> =
stateService.rebaseMerge(progressIndicator, pullRequestId, currentHeadRef).notifyState()
override fun squashMerge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String)
: CompletableFuture<Unit> = stateService.squashMerge(progressIndicator, pullRequestId, commitMessage, currentHeadRef).notifyState()
private fun <T> CompletableFuture<T>.notifyState(): CompletableFuture<T> =
completionOnEdt {
detailsData.reloadDetails()
messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onStateChanged()
}
override fun dispose() {
mergeabilityStateRequestValue.drop()
baseBranchProtectionRulesRequestValue.drop()
}
} | apache-2.0 | d9c4db62682e5e2daf68a5104097d260 | 46.29 | 140 | 0.781726 | 5.689531 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextStoryScale.kt | 2 | 389 | package org.thoughtcrime.securesms.mediasend.v2.text
object TextStoryScale {
fun convertToScale(textScale: Int): Float {
if (textScale < 0) {
return 1f
}
val minimumScale = 0.5f
val maximumScale = 1.5f
val scaleRange = maximumScale - minimumScale
val percent = textScale / 100f
val scale = scaleRange * percent + minimumScale
return scale
}
}
| gpl-3.0 | 45580b3e3c03ed118ae8da2c3b55ed17 | 20.611111 | 52 | 0.678663 | 3.776699 | false | false | false | false |
androidx/androidx | compose/material/material/src/desktopMain/kotlin/androidx/compose/material/DesktopAlertDialog.desktop.kt | 3 | 9758 | /*
* 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.compose.material
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.rememberDialogState
import androidx.compose.ui.window.Dialog as CoreDialog
/**
* Alert dialog is a Dialog which interrupts the user with urgent information, details or actions.
*
* The dialog will position its buttons based on the available space. By default it will try to
* place them horizontally next to each other and fallback to horizontal placement if not enough
* space is available. There is also another version of this composable that has a slot for buttons
* to provide custom buttons layout.
*
* Sample of dialog:
* @sample androidx.compose.material.samples.AlertDialogSample
*
* @param onDismissRequest Callback that will be called when the user closes the dialog.
* @param confirmButton A button which is meant to confirm a proposed action, thus resolving
* what triggered the dialog. The dialog does not set up any events for this button so they need
* to be set up by the caller.
* @param modifier Modifier to be applied to the layout of the dialog.
* @param dismissButton A button which is meant to dismiss the dialog. The dialog does not set up
* any events for this button so they need to be set up by the caller.
* @param title The title of the Dialog which should specify the purpose of the Dialog. The title
* is not mandatory, because there may be sufficient information inside the [text]. Provided text
* style will be [Typography.subtitle1].
* @param text The text which presents the details regarding the Dialog's purpose. Provided text
* style will be [Typography.body2].
* @param shape Defines the Dialog's shape
* @param backgroundColor The background color of the dialog.
* @param contentColor The preferred content color provided by this dialog to its children.
* @param dialogProvider Defines how to create dialog in which will be placed AlertDialog's content.
*/
@Composable
@ExperimentalMaterialApi
fun AlertDialog(
onDismissRequest: () -> Unit,
confirmButton: @Composable () -> Unit,
modifier: Modifier = Modifier,
dismissButton: @Composable (() -> Unit)? = null,
title: @Composable (() -> Unit)? = null,
text: @Composable (() -> Unit)? = null,
shape: Shape = MaterialTheme.shapes.medium,
backgroundColor: Color = MaterialTheme.colors.surface,
contentColor: Color = contentColorFor(backgroundColor),
dialogProvider: AlertDialogProvider = PopupAlertDialogProvider
) {
AlertDialog(
onDismissRequest = onDismissRequest,
buttons = {
// TODO: move the modifiers to FlowRow when it supports a modifier parameter
Box(Modifier.fillMaxWidth().padding(all = 8.dp)) {
AlertDialogFlowRow(
mainAxisSpacing = 8.dp,
crossAxisSpacing = 12.dp
) {
dismissButton?.invoke()
confirmButton()
}
}
},
modifier = modifier,
title = title,
text = text,
shape = shape,
backgroundColor = backgroundColor,
contentColor = contentColor,
dialogProvider = dialogProvider
)
}
/**
* Alert dialog is a Dialog which interrupts the user with urgent information, details or actions.
*
* This function can be used to fully customize the button area, e.g. with:
*
* @sample androidx.compose.material.samples.CustomAlertDialogSample
*
* @param onDismissRequest Callback that will be called when the user closes the dialog.
* @param buttons Function that emits the layout with the buttons.
* @param modifier Modifier to be applied to the layout of the dialog.
* @param title The title of the Dialog which should specify the purpose of the Dialog. The title
* is not mandatory, because there may be sufficient information inside the [text]. Provided text
* style will be [Typography.subtitle1].
* @param text The text which presents the details regarding the Dialog's purpose. Provided text
* style will be [Typography.body2].
* @param shape Defines the Dialog's shape.
* @param backgroundColor The background color of the dialog.
* @param contentColor The preferred content color provided by this dialog to its children.
* @param dialogProvider Defines how to create dialog in which will be placed AlertDialog's content.
*/
@Composable
@ExperimentalMaterialApi
fun AlertDialog(
onDismissRequest: () -> Unit,
buttons: @Composable () -> Unit,
modifier: Modifier = Modifier,
title: (@Composable () -> Unit)? = null,
text: @Composable (() -> Unit)? = null,
shape: Shape = MaterialTheme.shapes.medium,
backgroundColor: Color = MaterialTheme.colors.surface,
contentColor: Color = contentColorFor(backgroundColor),
dialogProvider: AlertDialogProvider = PopupAlertDialogProvider
) {
with(dialogProvider) {
AlertDialog(onDismissRequest = onDismissRequest) {
AlertDialogContent(
buttons = buttons,
modifier = modifier.width(IntrinsicSize.Min),
title = title,
text = text,
shape = shape,
backgroundColor = backgroundColor,
contentColor = contentColor
)
}
}
}
/**
* Defines how to create dialog in which will be placed AlertDialog's content.
*/
@ExperimentalMaterialApi
interface AlertDialogProvider {
/**
* Dialog which will be used to place AlertDialog's [content].
*
* @param onDismissRequest Callback that will be called when the user closes the dialog
* @param content Content of the dialog
*/
@Composable
fun AlertDialog(
onDismissRequest: () -> Unit,
content: @Composable () -> Unit
)
}
// TODO(https://github.com/JetBrains/compose-jb/issues/933): is it right to use Popup to show a
// dialog?
/**
* Shows Alert dialog as popup in the middle of the window.
*/
@ExperimentalMaterialApi
object PopupAlertDialogProvider : AlertDialogProvider {
@Composable
override fun AlertDialog(
onDismissRequest: () -> Unit,
content: @Composable () -> Unit
) {
// Popups on the desktop are by default embedded in the component in which
// they are defined and aligned within its bounds. But an [AlertDialog] needs
// to be aligned within the window, not the parent component, so we cannot use
// [alignment] property of [Popup] and have to use [Box] that fills all the
// available space. Also [Box] provides a dismiss request feature when clicked
// outside of the [AlertDialog] content.
Popup(
popupPositionProvider = object : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset = IntOffset.Zero
},
focusable = true,
onDismissRequest = onDismissRequest,
) {
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(onDismissRequest) {
detectTapGestures(onPress = { onDismissRequest() })
},
contentAlignment = Alignment.Center
) {
Surface(elevation = 24.dp) {
content()
}
}
}
}
}
/**
* Shows Alert dialog as undecorated draggable window.
*/
@ExperimentalMaterialApi
object UndecoratedWindowAlertDialogProvider : AlertDialogProvider {
@Composable
override fun AlertDialog(
onDismissRequest: () -> Unit,
content: @Composable () -> Unit
) {
CoreDialog(
onCloseRequest = onDismissRequest,
state = rememberDialogState(width = Dp.Unspecified, height = Dp.Unspecified),
undecorated = true,
resizable = false
) {
WindowDraggableArea {
content()
}
}
}
} | apache-2.0 | 65badbb77da70b5c156b1b2dbafab932 | 39.160494 | 100 | 0.684567 | 4.948276 | false | false | false | false |
oldcwj/iPing | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RadioGroupDialog.kt | 1 | 2249 | package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.support.v7.app.AlertDialog
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.onGlobalLayout
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.models.RadioItem
import kotlinx.android.synthetic.main.dialog_radio_group.view.*
import java.util.*
class RadioGroupDialog(val activity: Activity, val items: ArrayList<RadioItem>, val checkedItemId: Int, val titleId: Int = 0, val callback: (newValue: Any) -> Unit) :
RadioGroup.OnCheckedChangeListener {
val dialog: AlertDialog
var wasInit = false
var selectedItemId = -1
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_radio_group, null)
view.dialog_radio_group.apply {
setOnCheckedChangeListener(this@RadioGroupDialog)
for (i in 0 until items.size) {
val radioButton = (activity.layoutInflater.inflate(R.layout.radio_button, null) as RadioButton).apply {
text = items[i].title
isChecked = items[i].id == checkedItemId
id = i
}
if (items[i].id == checkedItemId) {
selectedItemId = i
}
addView(radioButton, RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
}
}
dialog = AlertDialog.Builder(activity)
.create().apply {
activity.setupDialogStuff(view, this, titleId)
}
if (selectedItemId != -1) {
view.dialog_radio_holder.apply {
onGlobalLayout {
scrollY = view.dialog_radio_group.findViewById<View>(selectedItemId).bottom - height
}
}
}
wasInit = true
}
override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
if (wasInit) {
callback(items[checkedId].value)
dialog.dismiss()
}
}
}
| gpl-3.0 | 239b7a0de9e2f7d6286018a3c49c5475 | 35.274194 | 166 | 0.638951 | 4.785106 | false | false | false | false |
GunoH/intellij-community | plugins/hg4idea/src/org/zmlx/hg4idea/ignore/HgIgnoredFileContentProvider.kt | 7 | 6164 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.zmlx.hg4idea.ignore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vcs.actions.VcsContextFactory
import com.intellij.openapi.vcs.changes.IgnoreSettingsType
import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider
import com.intellij.openapi.vcs.changes.IgnoredFileDescriptor
import com.intellij.openapi.vcs.changes.IgnoredFileProvider
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcsUtil.VcsUtil
import org.zmlx.hg4idea.HgVcs
import org.zmlx.hg4idea.command.HgStatusCommand
import org.zmlx.hg4idea.repo.HgRepositoryFiles.HGIGNORE
private val LOG = logger<HgIgnoredFileContentProvider>()
class HgIgnoredFileContentProvider(private val project: Project) : IgnoredFileContentProvider {
override fun getSupportedVcs(): VcsKey = HgVcs.getKey()
override fun getFileName() = HGIGNORE
override fun buildIgnoreFileContent(ignoreFileRoot: VirtualFile, ignoredFileProviders: Array<IgnoredFileProvider>): String {
val hgRepoRoot = VcsUtil.getVcsRootFor(project, ignoreFileRoot)
if (hgRepoRoot == null || hgRepoRoot != ignoreFileRoot) return "" //generate .hgignore only in hg root
val content = StringBuilder()
val lineSeparator = System.lineSeparator()
val untrackedFiles = getUntrackedFiles(hgRepoRoot, ignoreFileRoot)
if (untrackedFiles.isEmpty()) return "" //if there is no untracked files this mean nothing to ignore
for (provider in ignoredFileProviders) {
val ignoredFiles = provider.getIgnoredFiles(project).ignoreBeansToRelativePaths(ignoreFileRoot, untrackedFiles)
if (ignoredFiles.isEmpty()) continue
if (content.isNotEmpty()) {
content.append(lineSeparator).append(lineSeparator)
}
val description = provider.ignoredGroupDescription
if (description.isNotBlank()) {
content.append(buildIgnoreGroupDescription(provider))
content.append(lineSeparator)
}
content.append(ignoredFiles.joinToString(lineSeparator))
}
return if (content.isNotEmpty()) "syntax: glob$lineSeparator$lineSeparator$content" else ""
}
private fun getUntrackedFiles(hgRepoRoot: VirtualFile, ignoreFileRoot: VirtualFile): Set<VirtualFile> =
try {
HashSet(
HgStatusCommand.Builder(false).unknown(true).removed(true).build(project).getFiles(hgRepoRoot)
.filter { VfsUtil.isAncestor(ignoreFileRoot, it, true) }
)
}
catch (e: VcsException) {
LOG.warn("Cannot get untracked files: ", e)
emptySet()
}
private fun Iterable<IgnoredFileDescriptor>.ignoreBeansToRelativePaths(ignoreFileRoot: VirtualFile,
untrackedFiles: Set<VirtualFile>): List<String> {
val vcsRoot = VcsUtil.getVcsRootFor(project, ignoreFileRoot)
val vcsContextFactory = VcsContextFactory.getInstance()
return filter { ignoredBean ->
when (ignoredBean.type) {
IgnoreSettingsType.UNDER_DIR -> shouldIgnoreUnderDir(ignoredBean, untrackedFiles, ignoreFileRoot, vcsRoot, vcsContextFactory)
IgnoreSettingsType.FILE -> shouldIgnoreFile(ignoredBean, untrackedFiles, ignoreFileRoot, vcsRoot, vcsContextFactory)
IgnoreSettingsType.MASK -> shouldIgnoreByMask(ignoredBean, untrackedFiles)
}
}.map { ignoredBean ->
when (ignoredBean.type) {
IgnoreSettingsType.MASK -> ignoredBean.mask!!
IgnoreSettingsType.UNDER_DIR -> buildIgnoreEntryContent(ignoreFileRoot, ignoredBean)
IgnoreSettingsType.FILE -> buildIgnoreEntryContent(ignoreFileRoot, ignoredBean)
}
}
}
private fun shouldIgnoreUnderDir(ignoredBean: IgnoredFileDescriptor,
untrackedFiles: Set<VirtualFile>,
ignoreFileRoot: VirtualFile,
vcsRoot: VirtualFile?,
vcsContextFactory: VcsContextFactory) =
FileUtil.exists(ignoredBean.path)
&& untrackedFiles.any { FileUtil.isAncestor(ignoredBean.path!!, it.path, true) }
&& FileUtil.isAncestor(ignoreFileRoot.path, ignoredBean.path!!, false)
&& Comparing.equal(vcsRoot, VcsUtil.getVcsRootFor(project, vcsContextFactory.createFilePath(ignoredBean.path!!, true)))
private fun shouldIgnoreFile(ignoredBean: IgnoredFileDescriptor,
untrackedFiles: Set<VirtualFile>,
ignoreFileRoot: VirtualFile,
vcsRoot: VirtualFile?,
vcsContextFactory: VcsContextFactory) =
FileUtil.exists(ignoredBean.path)
&& untrackedFiles.any { ignoredBean.matchesFile(it) }
&& FileUtil.isAncestor(ignoreFileRoot.path, ignoredBean.path!!, false)
&& Comparing.equal(vcsRoot, VcsUtil.getVcsRootFor(project, vcsContextFactory.createFilePath(ignoredBean.path!!, false)))
private fun shouldIgnoreByMask(ignoredBean: IgnoredFileDescriptor, untrackedFiles: Set<VirtualFile>) =
untrackedFiles.any { ignoredBean.matchesFile(it) }
override fun buildUnignoreContent(ignorePattern: String) = throw UnsupportedOperationException()
override fun buildIgnoreGroupDescription(ignoredFileProvider: IgnoredFileProvider) =
prependCommentHashCharacterIfNeeded(ignoredFileProvider.ignoredGroupDescription)
override fun buildIgnoreEntryContent(ignoreEntryRoot: VirtualFile, ignoredFileDescriptor: IgnoredFileDescriptor) =
FileUtil.getRelativePath(ignoreEntryRoot.path, ignoredFileDescriptor.path!!, '/') ?: ""
override fun supportIgnoreFileNotInVcsRoot() = false
private fun prependCommentHashCharacterIfNeeded(description: @NlsSafe String): @NlsSafe String =
if (description.startsWith("#")) description else "# $description"
} | apache-2.0 | b7f2fcc4837f72ba12a70fb88b208ac2 | 47.928571 | 133 | 0.735561 | 4.842105 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/navbar/ide/NavBarVmImpl.kt | 1 | 9208 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.navbar.ide
import com.intellij.codeInsight.navigation.actions.navigateRequest
import com.intellij.ide.navbar.NavBarItem
import com.intellij.ide.navbar.NavBarItemPresentation
import com.intellij.ide.navbar.impl.children
import com.intellij.ide.navbar.vm.NavBarItemVm
import com.intellij.ide.navbar.vm.NavBarVm
import com.intellij.ide.navbar.vm.NavBarVm.SelectionShift
import com.intellij.model.Pointer
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.readAction
import com.intellij.openapi.project.Project
import com.intellij.util.flow.zipWithPrevious
import com.intellij.util.ui.EDT
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST
import kotlinx.coroutines.flow.*
internal class NavBarVmImpl(
private val cs: CoroutineScope,
private val project: Project,
initialItems: List<NavBarVmItem>,
activityFlow: Flow<Unit>,
) : NavBarVm {
init {
require(initialItems.isNotEmpty())
}
private val _items: MutableStateFlow<List<NavBarItemVmImpl>> = MutableStateFlow(initialItems.mapIndexed(::NavBarItemVmImpl))
private val _selectedIndex: MutableStateFlow<Int> = MutableStateFlow(-1)
private val _popupRequests: MutableSharedFlow<Int> = MutableSharedFlow(extraBufferCapacity = 1, onBufferOverflow = DROP_OLDEST)
private val _popup: MutableStateFlow<NavBarPopupVmImpl?> = MutableStateFlow(null)
init {
cs.launch {
activityFlow.collectLatest {
val items = focusModel(project)
if (items.isNotEmpty()) {
_items.value = items.mapIndexed(::NavBarItemVmImpl)
_selectedIndex.value = -1
check(_popupRequests.tryEmit(-1))
_popup.value = null
}
}
}
cs.launch {
handleSelectionChange()
}
cs.launch {
handlePopupRequests()
}
}
override val items: StateFlow<List<NavBarItemVm>> = _items.asStateFlow()
override val selectedIndex: StateFlow<Int> = _selectedIndex.asStateFlow()
override val popup: StateFlow<NavBarPopupVmImpl?> = _popup.asStateFlow()
override fun selection(): List<Pointer<out NavBarItem>> {
EDT.assertIsEdt()
val popup = _popup.value
if (popup != null) {
return popup.selectedItems.map { it.pointer }
}
else {
val selectedIndex = _selectedIndex.value
val items = _items.value
if (selectedIndex in items.indices) {
return listOf(items[selectedIndex].item.pointer)
}
}
return emptyList()
}
override fun shiftSelectionTo(shift: SelectionShift) {
when (shift) {
SelectionShift.FIRST -> _selectedIndex.value = 0
SelectionShift.PREV -> _selectedIndex.update { (it - 1 + items.value.size).mod(items.value.size) }
SelectionShift.NEXT -> _selectedIndex.update { (it + 1 + items.value.size).mod(items.value.size) }
SelectionShift.LAST -> _selectedIndex.value = items.value.lastIndex
}
}
override fun selectTail() {
val items = items.value
val i = (items.size - 2).coerceAtLeast(0)
items[i].select()
}
override fun showPopup() {
check(_popupRequests.tryEmit(_selectedIndex.value))
}
private suspend fun handleSelectionChange() {
_items.collectLatest { items: List<NavBarItemVmImpl> ->
_selectedIndex.zipWithPrevious().collect { (unselected, selected) ->
if (unselected >= 0) {
items[unselected].selected.value = false
}
if (selected >= 0) {
items[selected].selected.value = true
}
if (_popup.value != null) {
check(_popupRequests.tryEmit(selected))
}
}
}
}
private suspend fun handlePopupRequests() {
_popupRequests.collectLatest {
handlePopupRequest(it)
}
}
private suspend fun handlePopupRequest(index: Int) {
_popup.value = null // hide previous popup
if (index < 0) {
return
}
val items = _items.value
val children = items[index].item.children() ?: return
if (children.isEmpty()) {
return
}
val nextItem = items.getOrNull(index + 1)?.item
popupLoop(items.slice(0..index).map { it.item }, NavBarPopupVmImpl(
items = children,
initialSelectedItemIndex = children.indexOf(nextItem),
))
}
private suspend fun popupLoop(items: List<NavBarVmItem>, popup: NavBarPopupVmImpl) {
_popup.value = popup
val selectedChild = try {
popup.result.await()
}
catch (ce: CancellationException) {
_popup.value = null
throw ce
}
val expandResult = autoExpand(selectedChild)
?: return
when (expandResult) {
is ExpandResult.NavigateTo -> {
navigateTo(project, expandResult.target)
return
}
is ExpandResult.NextPopup -> {
val newItems = items + expandResult.expanded
val lastIndex = newItems.indices.last
val newItemVms = newItems.mapIndexed(::NavBarItemVmImpl).also {
it[lastIndex].selected.value = true
}
_items.value = newItemVms
_selectedIndex.value = lastIndex
popupLoop(newItems, NavBarPopupVmImpl(
items = expandResult.children,
initialSelectedItemIndex = -1,
))
}
}
}
private inner class NavBarItemVmImpl(
val index: Int,
val item: NavBarVmItem,
) : NavBarItemVm {
override val presentation: NavBarItemPresentation get() = item.presentation
override val isModuleContentRoot: Boolean get() = item.isModuleContentRoot
override val isFirst: Boolean get() = index == 0
override val isLast: Boolean get() = index == items.value.lastIndex
override val selected: MutableStateFlow<Boolean> = MutableStateFlow(false)
override fun isNextSelected(): Boolean {
return index == _selectedIndex.value - 1
}
override fun isInactive(): Boolean {
return _selectedIndex.value != -1 && _selectedIndex.value < index
}
override fun select() {
_selectedIndex.value = index
}
override fun showPopup() {
[email protected]()
}
override fun activate() {
cs.launch {
navigateTo(project, item)
}
}
}
}
private sealed interface ExpandResult {
class NavigateTo(val target: NavBarVmItem) : ExpandResult
class NextPopup(val expanded: List<NavBarVmItem>, val children: List<NavBarVmItem>) : ExpandResult
}
private suspend fun autoExpand(child: NavBarVmItem): ExpandResult? {
var expanded = emptyList<NavBarVmItem>()
var currentItem = child
var (children, navigateOnClick) = currentItem.fetch(childrenSelector, NavBarItem::navigateOnClick) ?: return null
if (children.isEmpty() || navigateOnClick) {
return ExpandResult.NavigateTo(currentItem)
}
while (true) {
// [currentItem] -- is being evaluated
// [expanded] -- list of the elements starting from [child] argument and up to [currentItem]. Both exclusively
// [children] -- children of the [currentItem]
// [showPopup] -- if [currentItem]'s children should be shown as a popup
// No automatic navigation in this cycle!
// It is only allowed as reaction to a users click
// at the popup item, i.e. at first iteration before while-cycle
when (children.size) {
0 -> {
// No children, [currentItem] is an only leaf on its branch, but no auto navigation allowed
// So returning the previous state
return ExpandResult.NextPopup(expanded, listOf(currentItem))
}
1 -> {
if (navigateOnClick) {
// [currentItem] is navigation target regardless of its children count, but no auto navigation allowed
// So returning the previous state
return ExpandResult.NextPopup(expanded, listOf(currentItem))
}
else {
// Performing auto-expand, keeping invariant
expanded = expanded + currentItem
currentItem = children.single()
val fetch = currentItem.fetch(childrenSelector, NavBarItem::navigateOnClick) ?: return null
children = fetch.first
navigateOnClick = fetch.second
}
}
else -> {
// [currentItem] has several children, so return it with current [expanded] trace.
return ExpandResult.NextPopup(expanded + currentItem, children)
}
}
}
}
private suspend fun navigateTo(project: Project, item: NavBarVmItem) {
val navigationRequest = item.fetch(NavBarItem::navigationRequest)
?: return
withContext(Dispatchers.EDT) {
navigateRequest(project, navigationRequest)
}
}
private suspend fun NavBarVmItem.children(): List<NavBarVmItem>? {
return fetch(childrenSelector)
}
private suspend fun <T> NavBarVmItem.fetch(selector: NavBarItem.() -> T): T? {
return readAction {
pointer.dereference()?.selector()
}
}
private suspend fun <T1, T2> NavBarVmItem.fetch(
selector1: NavBarItem.() -> T1,
selector2: NavBarItem.() -> T2
): Pair<T1, T2>? = fetch { Pair(selector1(), selector2()) }
private val childrenSelector: NavBarItem.() -> List<NavBarVmItem> = {
children().toVmItems()
}
| apache-2.0 | 0d709d4beded7ceceb285fdc19f75bf2 | 30.861592 | 129 | 0.675065 | 4.298786 | false | false | false | false |
GunoH/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/AttachDialogCollectItemsUtil.kt | 2 | 3729 | package com.intellij.xdebugger.impl.ui.attach.dialog
import com.intellij.execution.ExecutionException
import com.intellij.execution.process.ProcessInfo
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.xdebugger.attach.XAttachDebuggerProvider
import com.intellij.xdebugger.attach.XAttachHost
import com.intellij.xdebugger.attach.XAttachPresentationGroup
import com.intellij.xdebugger.impl.actions.AttachToProcessActionBase
import com.intellij.xdebugger.impl.actions.AttachToProcessActionBase.AttachToProcessItem
import com.intellij.xdebugger.impl.ui.attach.dialog.diagnostics.ProcessesFetchingProblemException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ensureActive
import kotlin.coroutines.coroutineContext
private val logger = Logger.getInstance("AttachDialogCollectItemsUtil")
internal suspend fun collectAttachProcessItemsGroupByProcessInfo(
project: Project,
host: XAttachHost,
attachDebuggerProviders: List<XAttachDebuggerProvider>): AttachItemsInfo {
try {
val processes = host.processList
val debuggerProviders = attachDebuggerProviders.filter { it.isAttachHostApplicable(host) }
val dataHolder = UserDataHolderBase()
val allItems = mutableListOf<AttachToProcessItem>()
val processesToAttachItems = processes.associateWith { processInfo ->
coroutineContext.ensureActive()
val providersWithItems = mutableMapOf<XAttachPresentationGroup<*>, MutableList<AttachToProcessItem>>()
for (debuggerProvider in debuggerProviders) {
val itemsFromProvider = debuggerProvider.getAvailableDebuggers(project, host, processInfo, dataHolder).map {
AttachToProcessItem(debuggerProvider.presentationGroup, false, host, processInfo, listOf(it), project, dataHolder)
}
if (itemsFromProvider.any()) {
providersWithItems.putIfAbsent(debuggerProvider.presentationGroup, itemsFromProvider.toMutableList())?.addAll(itemsFromProvider)
allItems.addAll(itemsFromProvider)
}
}
AttachDialogProcessItem.create(processInfo, providersWithItems, dataHolder)
}
val recentItems = getRecentItems(allItems, processesToAttachItems, host, project, dataHolder)
return AttachItemsInfo(processesToAttachItems.values.toList(), recentItems, dataHolder)
}
catch (processesFetchingProblemException: ProcessesFetchingProblemException) {
throw processesFetchingProblemException
}
catch (cancellationException: CancellationException) {
throw cancellationException
}
catch (executionException: ExecutionException) {
return AttachItemsInfo.EMPTY
}
catch (t: Throwable) {
logger.error(t)
return AttachItemsInfo.EMPTY
}
}
private fun getRecentItems(currentItems: List<AttachToProcessItem>,
currentDialogItems: Map<ProcessInfo, AttachDialogProcessItem>,
host: XAttachHost,
project: Project,
dataHolder: UserDataHolderBase): List<AttachDialogRecentItem> {
return AttachToProcessActionBase.getRecentItems(currentItems, host, project, dataHolder).groupBy { it.processInfo.pid }.mapNotNull { groupedItems ->
val firstItem = groupedItems.value.first()
val processInfo = firstItem.processInfo
val dialogItem = currentDialogItems[processInfo]
if (dialogItem == null) {
logger.error("Unable to get all available debuggers for the recent item $processInfo")
return@mapNotNull null
}
return@mapNotNull AttachDialogRecentItem(dialogItem, groupedItems.value.sortedBy { it.group.order }.flatMap { it.debuggers })
}
}
| apache-2.0 | a887f2e1e7981480d952030bef25d514 | 42.870588 | 150 | 0.77447 | 5.157676 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.