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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/item/ItemTypeRegistry.kt | 1 | 31715 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.item
import org.lanternpowered.api.block.BlockTypes
import org.lanternpowered.api.data.Keys
import org.lanternpowered.api.effect.potion.PotionEffectTypes
import org.lanternpowered.api.effect.potion.potionEffectOf
import org.lanternpowered.api.entity.EntityType
import org.lanternpowered.api.entity.EntityTypes
import org.lanternpowered.api.item.ItemType
import org.lanternpowered.api.item.ItemTypes
import org.lanternpowered.api.item.inventory.ItemStack
import org.lanternpowered.api.item.inventory.equipment.EquipmentType
import org.lanternpowered.api.item.inventory.equipment.EquipmentTypes
import org.lanternpowered.api.item.inventory.itemStackOf
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.minecraftKey
import org.lanternpowered.api.registry.catalogTypeRegistry
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.data.key.LanternKeys
import org.lanternpowered.server.data.key.registerApplicablePotionEffects
import org.lanternpowered.server.data.key.registerUseDuration
import org.lanternpowered.server.data.type.LanternDyeColor
import org.lanternpowered.server.effect.potion.LanternPotionType
import org.lanternpowered.server.item.ItemKeys
import org.lanternpowered.server.item.ItemTypeBuilder
import org.lanternpowered.server.item.behavior.vanilla.ArmorQuickEquipInteractionBehavior
import org.lanternpowered.server.item.behavior.vanilla.ConsumableInteractionBehavior
import org.lanternpowered.server.item.behavior.vanilla.OpenHeldBookBehavior
import org.lanternpowered.server.item.behavior.vanilla.ShieldInteractionBehavior
import org.lanternpowered.server.item.behavior.vanilla.WallOrStandingPlacementBehavior
import org.lanternpowered.server.item.behavior.vanilla.consumable.PotionEffectsProvider
import org.lanternpowered.server.item.itemTypeOf
import org.lanternpowered.server.item.property.BowProjectile
import org.lanternpowered.server.registry.type.block.BlockTypeRegistry
import org.spongepowered.api.data.type.ArmorMaterial
import org.spongepowered.api.data.type.ArmorMaterials
import org.spongepowered.api.data.type.DyeColor
import org.spongepowered.api.data.type.DyeColors
import org.spongepowered.api.data.type.ToolType
import org.spongepowered.api.data.type.ToolTypes
import org.spongepowered.api.data.type.WoodType
import org.spongepowered.api.data.type.WoodTypes
import org.spongepowered.api.effect.sound.music.MusicDisc
import org.spongepowered.api.effect.sound.music.MusicDiscs
import org.spongepowered.api.entity.projectile.Projectile
import org.spongepowered.api.entity.vehicle.minecart.MinecartEntity
import org.spongepowered.api.fluid.FluidStackSnapshot
import org.spongepowered.api.fluid.FluidType
import org.spongepowered.api.fluid.FluidTypes
import java.util.Collections
import java.util.function.Supplier
import kotlin.random.Random
val ItemTypeRegistry = catalogTypeRegistry<ItemType> {
fun register(key: NamespacedKey, fn: ItemTypeBuilder.() -> Unit = {}) =
register(itemTypeOf(key, fn))
fun ItemTypeBuilder.durable(maxDurability: Int) {
maxStackQuantity(1)
keys {
register(Keys.MAX_DURABILITY, maxDurability)
}
stackKeys {
register(Keys.ITEM_DURABILITY, 0)
register(Keys.IS_UNBREAKABLE, true) // TODO: True until durability is implemented
}
}
fun ItemTypeBuilder.tool(useLimit: Int, toolType: ToolType) {
durable(useLimit)
keys {
register(Keys.TOOL_TYPE, toolType)
register(LanternKeys.IS_DUAL_WIELDABLE, true)
}
}
fun ItemTypeBuilder.tool(useLimit: Int, toolType: Supplier<out ToolType>) {
tool(useLimit, toolType.get())
}
fun ItemTypeBuilder.woodenTool(useLimit: Int = 60) {
tool(useLimit, ToolTypes.WOOD)
}
fun ItemTypeBuilder.stoneTool(useLimit: Int = 132) {
tool(useLimit, ToolTypes.STONE)
}
fun ItemTypeBuilder.ironTool(useLimit: Int = 251) {
tool(useLimit, ToolTypes.IRON)
}
fun ItemTypeBuilder.goldenTool(useLimit: Int = 33) {
tool(useLimit, ToolTypes.GOLD)
}
fun ItemTypeBuilder.diamondTool(useLimit: Int = 1562) {
tool(useLimit, ToolTypes.DIAMOND)
}
fun ItemTypeBuilder.armor(
useLimit: Int,
armorMaterial: Supplier<out ArmorMaterial>,
equipmentType: Supplier<out EquipmentType>) {
durable(useLimit)
keys {
register(Keys.ARMOR_MATERIAL, armorMaterial)
register(Keys.EQUIPMENT_TYPE, equipmentType)
}
behaviors {
add(ArmorQuickEquipInteractionBehavior())
}
}
fun ItemTypeBuilder.leatherArmor(useLimit: Int, equipmentType: Supplier<out EquipmentType>) {
armor(useLimit, ArmorMaterials.LEATHER, equipmentType)
stackKeys {
register(Keys.COLOR)
}
}
fun ItemTypeBuilder.ironArmor(useLimit: Int, equipmentType: Supplier<out EquipmentType>) {
armor(useLimit, ArmorMaterials.IRON, equipmentType)
}
fun ItemTypeBuilder.chainmailArmor(useLimit: Int, equipmentType: Supplier<out EquipmentType>) {
armor(useLimit, ArmorMaterials.CHAINMAIL, equipmentType)
}
fun ItemTypeBuilder.goldenArmor(useLimit: Int, equipmentType: Supplier<out EquipmentType>) {
armor(useLimit, ArmorMaterials.GOLD, equipmentType)
}
fun ItemTypeBuilder.diamondArmor(useLimit: Int, equipmentType: Supplier<out EquipmentType>) {
armor(useLimit, ArmorMaterials.DIAMOND, equipmentType)
}
fun ItemTypeBuilder.food(food: Double, saturation: Double,
consumeDuration: Int = 32,
consumeBehavior: ConsumableInteractionBehavior.() -> Unit = {}) {
keys {
registerUseDuration(consumeDuration)
register(Keys.REPLENISHED_FOOD, food)
register(Keys.REPLENISHED_SATURATION, saturation)
}
behaviors {
add(ConsumableInteractionBehavior().apply(consumeBehavior))
}
}
fun ItemTypeBuilder.fluidBucket(fluidType: FluidType) {
maxStackQuantity(1)
stackKeys {
register(Keys.FLUID_ITEM_STACK, FluidStackSnapshot.builder()
.fluid(fluidType)
.volume(1000)
.build())
}
}
fun ItemTypeBuilder.fluidBucket(fluidType: Supplier<out FluidType>) =
fluidBucket(fluidType.get())
fun ItemTypeBuilder.dyeColor(dyeColor: DyeColor) {
keys {
register(ItemKeys.DYE_COLOR, dyeColor)
}
}
fun registerMinecarts() {
fun registerMinecart(key: NamespacedKey, entityType: Supplier<out EntityType<out MinecartEntity>>) {
register(key) {
maxStackQuantity(1)
}
}
registerMinecart(minecraftKey("minecart"), EntityTypes.MINECART)
registerMinecart(minecraftKey("chest_minecart"), EntityTypes.CHEST_MINECART)
registerMinecart(minecraftKey("furnace_minecart"), EntityTypes.FURNACE_MINECART)
registerMinecart(minecraftKey("tnt_minecart"), EntityTypes.TNT_MINECART)
registerMinecart(minecraftKey("hopper_minecart"), EntityTypes.HOPPER_MINECART)
registerMinecart(minecraftKey("command_block_minecart"), EntityTypes.COMMAND_BLOCK_MINECART)
registerMinecart(minecraftKey("spawner_minecart"), EntityTypes.COMMAND_BLOCK_MINECART)
}
fun registerBanners() {
for (dyeColor in LanternDyeColor.values()) {
val dyeId = dyeColor.key.value
register(minecraftKey("${dyeId}_banner")) {
maxStackQuantity(16)
stackKeys {
register(Keys.DYE_COLOR, DyeColors.WHITE)
register(Keys.BANNER_PATTERN_LAYERS, listOf())
}
behaviors {
val wallType = { BlockTypeRegistry.require(minecraftKey("${dyeId}_wall_banner")) }
val standingType = { BlockTypeRegistry.require(minecraftKey("${dyeId}_banner")) }
add(WallOrStandingPlacementBehavior.ofTypes(wallType, standingType))
}
}
}
}
fun registerDyeColors() {
for (dyeColor in LanternDyeColor.values()) {
register(minecraftKey("${dyeColor.key.value}_dye")) {
keys {
register(ItemKeys.DYE_COLOR, dyeColor)
}
}
}
}
fun ItemTypeBuilder.potionEffects(translation: LanternPotionType.() -> Text) {
val defaultTranslation = translatableTextOf("item.potion.name")
name {
get(Keys.POTION_TYPE).map { translation(it as LanternPotionType) }.orElse(defaultTranslation)
}
stackKeys {
register(Keys.COLOR)
register(Keys.POTION_EFFECTS)
register(Keys.POTION_TYPE)
}
}
fun registerPotions() {
register(minecraftKey("potion")) {
potionEffects { this.normalTranslation }
maxStackQuantity(1)
keys {
registerUseDuration(32)
register(ItemKeys.IS_ALWAYS_CONSUMABLE, true)
}
stackKeys {
registerApplicablePotionEffects(PotionEffectsProvider)
}
behaviors {
add(ConsumableInteractionBehavior().apply {
restItem { itemStackOf(ItemTypes.GLASS_BOTTLE) }
})
}
}
register(minecraftKey("splash_potion")) {
potionEffects { this.splashTranslation }
maxStackQuantity(1)
}
register(minecraftKey("lingering_potion")) {
potionEffects { this.lingeringTranslation }
maxStackQuantity(1)
}
}
fun registerBooks() {
register(minecraftKey("writable_book")) {
maxStackQuantity(1)
stackKeys {
register(Keys.PLAIN_PAGES)
}
}
register(minecraftKey("written_book")) {
maxStackQuantity(1)
stackKeys {
register(Keys.PAGES)
register(Keys.AUTHOR)
register(Keys.GENERATION)
}
behaviors {
add(OpenHeldBookBehavior())
}
}
register(minecraftKey("enchanted_book")) {
maxStackQuantity(1)
stackKeys {
register(Keys.STORED_ENCHANTMENTS)
}
}
register(minecraftKey("knowledge_book"))
}
fun ItemTypeBuilder.headwear() {
keys {
register(Keys.EQUIPMENT_TYPE, EquipmentTypes.HEAD)
}
}
fun registerSkullsAndHeads() {
register(minecraftKey("skeleton_skull")) {
headwear()
}
register(minecraftKey("wither_skeleton_skull")) {
headwear()
}
register(minecraftKey("player_head")) {
headwear()
stackKeys {
register(Keys.SKIN_PROFILE_PROPERTY)
}
}
register(minecraftKey("creeper_head")) {
headwear()
}
register(minecraftKey("dragon_head")) {
headwear()
}
}
fun registerFireworks() {
register(minecraftKey("firework_rocket")) {
stackKeys {
register(Keys.FIREWORK_EFFECTS, Collections.emptyList())
register(Keys.FIREWORK_FLIGHT_MODIFIER, 1)
}
}
register(minecraftKey("firework_star")) {
maxStackQuantity(1)
stackKeys {
register(Keys.FIREWORK_EFFECTS, Collections.emptyList())
}
}
}
fun registerHorseArmor() {
register(minecraftKey("iron_horse_armor")) {
maxStackQuantity(1)
}
register(minecraftKey("golden_horse_armor")) {
maxStackQuantity(1)
}
register(minecraftKey("diamond_horse_armor")) {
maxStackQuantity(1)
}
}
fun registerDoors() {
fun registerWoodenDoor(key: NamespacedKey, woodType: Supplier<out WoodType>) {
register(key) {
keys {
register(ItemKeys.WOOD_TYPE, woodType)
}
}
}
registerWoodenDoor(minecraftKey("oak_door"), WoodTypes.OAK)
registerWoodenDoor(minecraftKey("spruce_door"), WoodTypes.SPRUCE)
registerWoodenDoor(minecraftKey("birch_door"), WoodTypes.BIRCH)
registerWoodenDoor(minecraftKey("jungle_door"), WoodTypes.JUNGLE)
registerWoodenDoor(minecraftKey("acacia_door"), WoodTypes.ACACIA)
registerWoodenDoor(minecraftKey("dark_oak_door"), WoodTypes.DARK_OAK)
}
fun registerBoats() {
fun registerBoat(key: NamespacedKey, woodType: Supplier<out WoodType>) {
register(key) {
maxStackQuantity(1)
keys {
register(ItemKeys.WOOD_TYPE, woodType)
}
}
}
registerBoat(minecraftKey("oak_boat"), WoodTypes.OAK)
registerBoat(minecraftKey("spruce_boat"), WoodTypes.SPRUCE)
registerBoat(minecraftKey("birch_boat"), WoodTypes.BIRCH)
registerBoat(minecraftKey("jungle_boat"), WoodTypes.JUNGLE)
registerBoat(minecraftKey("acacia_boat"), WoodTypes.ACACIA)
registerBoat(minecraftKey("dark_oak_boat"), WoodTypes.DARK_OAK)
}
fun <P : Projectile> ItemTypeBuilder.arrow(
entityType: Supplier<out EntityType<P>>, fn: P.(itemStack: ItemStack) -> Unit = {}) {
keys {
register(ItemKeys.BOW_PROJECTILE_PROVIDER, BowProjectile(entityType.get(), fn))
}
}
fun registerArrows() {
register(minecraftKey("arrow")) {
arrow(EntityTypes.ARROW)
}
register(minecraftKey("tipped_arrow")) {
arrow(EntityTypes.ARROW) { stack ->
copyFrom(stack)
}
potionEffects { this.tippedArrowTranslation }
}
register(minecraftKey("spectral_arrow")) {
arrow(EntityTypes.SPECTRAL_ARROW)
}
}
fun registerMusicDiscs() {
fun registerMusicDisc(key: NamespacedKey, musicDisc: Supplier<out MusicDisc>) {
register(key) {
maxStackQuantity(1)
keys {
register(Keys.MUSIC_DISC, musicDisc)
}
}
}
registerMusicDisc(minecraftKey("music_disc_13"), MusicDiscs.THIRTEEN)
registerMusicDisc(minecraftKey("music_disc_cat"), MusicDiscs.CAT)
registerMusicDisc(minecraftKey("music_disc_blocks"), MusicDiscs.BLOCKS)
registerMusicDisc(minecraftKey("music_disc_chirp"), MusicDiscs.CHIRP)
registerMusicDisc(minecraftKey("music_disc_far"), MusicDiscs.FAR)
registerMusicDisc(minecraftKey("music_disc_mall"), MusicDiscs.MALL)
registerMusicDisc(minecraftKey("music_disc_mellohi"), MusicDiscs.MELLOHI)
registerMusicDisc(minecraftKey("music_disc_stal"), MusicDiscs.STAL)
registerMusicDisc(minecraftKey("music_disc_strad"), MusicDiscs.STRAD)
registerMusicDisc(minecraftKey("music_disc_ward"), MusicDiscs.WARD)
registerMusicDisc(minecraftKey("music_disc_11"), MusicDiscs.ELEVEN)
registerMusicDisc(minecraftKey("music_disc_wait"), MusicDiscs.WAIT)
}
register(minecraftKey("air"))
register(minecraftKey("iron_sword")) {
ironTool()
}
register(minecraftKey("iron_shovel")) {
ironTool()
}
register(minecraftKey("iron_pickaxe")) {
ironTool()
}
register(minecraftKey("iron_axe")) {
ironTool()
}
register(minecraftKey("iron_hoe")) {
ironTool()
}
register(minecraftKey("wooden_sword")) {
woodenTool()
}
register(minecraftKey("wooden_shovel")) {
woodenTool()
}
register(minecraftKey("wooden_pickaxe")) {
woodenTool()
}
register(minecraftKey("wooden_axe")) {
woodenTool()
}
register(minecraftKey("wooden_hoe")) {
woodenTool()
}
register(minecraftKey("stone_sword")) {
stoneTool()
}
register(minecraftKey("stone_shovel")) {
stoneTool()
}
register(minecraftKey("stone_pickaxe")) {
stoneTool()
}
register(minecraftKey("stone_axe")) {
stoneTool()
}
register(minecraftKey("stone_hoe")) {
stoneTool()
}
register(minecraftKey("diamond_sword")) {
diamondTool()
}
register(minecraftKey("diamond_shovel")) {
diamondTool()
}
register(minecraftKey("diamond_pickaxe")) {
diamondTool()
}
register(minecraftKey("diamond_axe")) {
diamondTool()
}
register(minecraftKey("diamond_hoe")) {
diamondTool()
}
register(minecraftKey("golden_sword")) {
goldenTool()
}
register(minecraftKey("golden_shovel")) {
goldenTool()
}
register(minecraftKey("golden_pickaxe")) {
goldenTool()
}
register(minecraftKey("golden_axe")) {
goldenTool()
}
register(minecraftKey("golden_hoe")) {
goldenTool()
}
register(minecraftKey("leather_helmet")) {
leatherArmor(useLimit = 56, equipmentType = EquipmentTypes.HEAD)
}
register(minecraftKey("leather_chestplate")) {
leatherArmor(useLimit = 81, equipmentType = EquipmentTypes.CHEST)
}
register(minecraftKey("leather_leggings")) {
leatherArmor(useLimit = 76, equipmentType = EquipmentTypes.LEGS)
}
register(minecraftKey("leather_boots")) {
leatherArmor(useLimit = 56, equipmentType = EquipmentTypes.FEET)
}
register(minecraftKey("chainmail_helmet")) {
chainmailArmor(useLimit = 166, equipmentType = EquipmentTypes.HEAD)
}
register(minecraftKey("chainmail_chestplate")) {
chainmailArmor(useLimit = 241, equipmentType = EquipmentTypes.CHEST)
}
register(minecraftKey("chainmail_leggings")) {
chainmailArmor(useLimit = 226, equipmentType = EquipmentTypes.LEGS)
}
register(minecraftKey("chainmail_boots")) {
chainmailArmor(useLimit = 196, equipmentType = EquipmentTypes.FEET)
}
register(minecraftKey("iron_helmet")) {
ironArmor(useLimit = 166, equipmentType = EquipmentTypes.HEAD)
}
register(minecraftKey("iron_chestplate")) {
ironArmor(useLimit = 241, equipmentType = EquipmentTypes.CHEST)
}
register(minecraftKey("iron_leggings")) {
ironArmor(useLimit = 226, equipmentType = EquipmentTypes.LEGS)
}
register(minecraftKey("iron_boots")) {
ironArmor(useLimit = 196, equipmentType = EquipmentTypes.FEET)
}
register(minecraftKey("diamond_helmet")) {
diamondArmor(useLimit = 364, equipmentType = EquipmentTypes.HEAD)
}
register(minecraftKey("diamond_chestplate")) {
diamondArmor(useLimit = 529, equipmentType = EquipmentTypes.CHEST)
}
register(minecraftKey("diamond_leggings")) {
diamondArmor(useLimit = 496, equipmentType = EquipmentTypes.LEGS)
}
register(minecraftKey("diamond_boots")) {
diamondArmor(useLimit = 430, equipmentType = EquipmentTypes.FEET)
}
register(minecraftKey("golden_helmet")) {
goldenArmor(useLimit = 78, equipmentType = EquipmentTypes.HEAD)
}
register(minecraftKey("golden_chestplate")) {
goldenArmor(useLimit = 113, equipmentType = EquipmentTypes.CHEST)
}
register(minecraftKey("golden_leggings")) {
goldenArmor(useLimit = 76, equipmentType = EquipmentTypes.LEGS)
}
register(minecraftKey("golden_boots")) {
goldenArmor(useLimit = 66, equipmentType = EquipmentTypes.FEET)
}
register(minecraftKey("flint_and_steel")) {
durable(65)
}
register(minecraftKey("fishing_rod")) {
durable(65)
}
register(minecraftKey("shears")) {
durable(238)
}
register(minecraftKey("bow")) {
durable(385)
keys {
registerUseDuration(0..72000)
}
}
register(minecraftKey("oak_sign")) {
maxStackQuantity(16)
behaviors {
add(WallOrStandingPlacementBehavior.ofTypes(BlockTypes.OAK_WALL_SIGN, BlockTypes.OAK_SIGN))
}
}
register(minecraftKey("bucket")) {
maxStackQuantity(16)
}
register(minecraftKey("water_bucket")) {
fluidBucket(FluidTypes.WATER)
}
register(minecraftKey("lava_bucket")) {
fluidBucket(FluidTypes.LAVA)
}
register(minecraftKey("saddle")) {
maxStackQuantity(1)
}
register(minecraftKey("snowball")) {
maxStackQuantity(16)
}
register(minecraftKey("egg")) {
maxStackQuantity(16)
}
register(minecraftKey("compass")) {
maxStackQuantity(1)
}
register(minecraftKey("clock")) {
maxStackQuantity(1)
}
register(minecraftKey("oak_boat")) {
maxStackQuantity(1)
}
register(minecraftKey("cake")) {
maxStackQuantity(1)
}
register(minecraftKey("filled_map")) {
maxStackQuantity(1)
}
register(minecraftKey("carrot_on_a_stick")) {
maxStackQuantity(1)
}
register(minecraftKey("cookie")) {
food(food = 2.0, saturation = 0.4)
}
register(minecraftKey("melon_slice")) {
food(food = 2.0, saturation = 1.2)
}
register(minecraftKey("apple")) {
food(food = 3.0, saturation = 2.4)
}
register(minecraftKey("golden_apple")) {
food(food = 4.0, saturation = 9.6)
keys {
registerApplicablePotionEffects(
potionEffectOf(PotionEffectTypes.REGENERATION, amplifier = 1, duration = 100),
potionEffectOf(PotionEffectTypes.ABSORPTION, amplifier = 0, duration = 2400)
)
register(ItemKeys.IS_ALWAYS_CONSUMABLE, true)
}
}
register(minecraftKey("enchanted_golden_apple")) {
food(food = 4.0, saturation = 9.6)
keys {
registerApplicablePotionEffects(
potionEffectOf(PotionEffectTypes.REGENERATION, amplifier = 1, duration = 400),
potionEffectOf(PotionEffectTypes.RESISTANCE, amplifier = 0, duration = 6000),
potionEffectOf(PotionEffectTypes.FIRE_RESISTANCE, amplifier = 0, duration = 6000),
potionEffectOf(PotionEffectTypes.ABSORPTION, amplifier = 3, duration = 2400)
)
register(ItemKeys.IS_ALWAYS_CONSUMABLE, true)
}
}
register(minecraftKey("mushroom_stew")) {
maxStackQuantity(1)
food(food = 6.0, saturation = 7.2)
}
register(minecraftKey("bread")) {
food(food = 5.0, saturation = 6.0)
}
register(minecraftKey("porkchop")) {
food(food = 6.0, saturation = 0.3)
}
register(minecraftKey("cooked_porkchop")) {
food(food = 8.0, saturation = 12.8)
}
register(minecraftKey("beef")) {
food(food = 3.0, saturation = 1.8)
}
register(minecraftKey("cooked_beef")) {
food(food = 8.0, saturation = 12.8)
}
register(minecraftKey("mutton")) {
food(food = 2.0, saturation = 1.2)
}
register(minecraftKey("cooked_mutton")) {
food(food = 6.0, saturation = 9.6)
}
register(minecraftKey("rabbit")) {
food(food = 3.0, saturation = 1.8)
}
register(minecraftKey("cooked_rabbit")) {
food(food = 5.0, saturation = 6.0)
}
register(minecraftKey("rabbit_stew")) {
maxStackQuantity(1)
food(food = 10.0, saturation = 12.0) {
restItem { itemStackOf(ItemTypes.BOWL) }
}
}
register(minecraftKey("chicken")) {
food(food = 2.0, saturation = 1.2) {
val hungerEffect = potionEffectOf(PotionEffectTypes.HUNGER, amplifier = 0, duration = 600)
consumer { player, _, _ ->
if (Random.nextInt(100) < 40) { // 40% chance of getting hunger effect
player.offerSingle(Keys.POTION_EFFECTS, hungerEffect)
}
}
}
}
register(minecraftKey("cooked_chicken")) {
food(food = 6.0, saturation = 7.2)
}
register(minecraftKey("rotten_flesh")) {
food(food = 4.0, saturation = 0.8) {
val hungerEffect = potionEffectOf(PotionEffectTypes.HUNGER, amplifier = 0, duration = 600)
consumer { player, _, _ ->
if (Random.nextInt(100) < 80) { // 80% chance of getting hunger effect
player.offerSingle(Keys.POTION_EFFECTS, hungerEffect)
}
}
}
}
register(minecraftKey("cod")) {
food(food = 2.0, saturation = 0.4)
}
register(minecraftKey("cooked_cod")) {
food(food = 5.0, saturation = 6.0)
}
register(minecraftKey("salmon")) {
food(food = 2.0, saturation = 0.4)
}
register(minecraftKey("cooked_salmon")) {
food(food = 6.0, saturation = 9.6)
}
register(minecraftKey("tropical_fish")) {
food(food = 1.0, saturation = 0.2)
}
register(minecraftKey("pufferfish")) {
food(food = 1.0, saturation = 0.2)
keys {
registerApplicablePotionEffects(
potionEffectOf(PotionEffectTypes.POISON, amplifier = 3, duration = 1200),
potionEffectOf(PotionEffectTypes.HUNGER, amplifier = 2, duration = 300),
potionEffectOf(PotionEffectTypes.NAUSEA, amplifier = 1, duration = 300)
)
}
}
register(minecraftKey("spider_eye")) {
food(food = 2.0, saturation = 3.2)
keys {
registerApplicablePotionEffects(
potionEffectOf(PotionEffectTypes.POISON, amplifier = 0, duration = 100)
)
}
}
register(minecraftKey("carrot")) {
food(food = 3.0, saturation = 3.6)
}
register(minecraftKey("potato")) {
food(food = 1.0, saturation = 0.6)
}
register(minecraftKey("baked_potato")) {
food(food = 5.0, saturation = 6.0)
}
register(minecraftKey("poisonous_potato")) {
food(food = 2.0, saturation = 1.2)
keys {
registerApplicablePotionEffects(
potionEffectOf(PotionEffectTypes.POISON, amplifier = 0, duration = 100)
)
}
}
register(minecraftKey("beetroot")) {
maxStackQuantity(1)
food(food = 1.0, saturation = 1.2)
}
register(minecraftKey("beetroot_soup")) {
food(food = 6.0, saturation = 7.2) {
restItem { itemStackOf(ItemTypes.BOWL) }
}
}
register(minecraftKey("golden_carrot")) {
food(food = 6.0, saturation = 14.4)
}
register(minecraftKey("pumpkin_pie")) {
food(food = 8.0, saturation = 4.8)
}
register(minecraftKey("chorus_fruit")) {
food(food = 4.0, saturation = 2.4) {
// TODO: Add random teleport consumer behavior
}
keys {
register(ItemKeys.IS_ALWAYS_CONSUMABLE, true)
}
}
register(minecraftKey("milk_bucket")) {
maxStackQuantity(1)
keys {
registerUseDuration(32)
register(ItemKeys.IS_ALWAYS_CONSUMABLE, true)
}
behaviors {
add(ConsumableInteractionBehavior().apply {
consumer { player, _, _ ->
player.offer(Keys.POTION_EFFECTS, emptyList())
}
restItem { itemStackOf(ItemTypes.BUCKET) }
})
}
}
register(minecraftKey("shield")) {
durable(336)
behaviors {
add(ShieldInteractionBehavior())
}
}
register(minecraftKey("elytra")) {
durable(432)
keys {
register(Keys.EQUIPMENT_TYPE, EquipmentTypes.CHEST)
}
behaviors {
add(ArmorQuickEquipInteractionBehavior())
}
}
register(minecraftKey("totem_of_undying")) {
maxStackQuantity(1)
}
register(minecraftKey("coal"))
register(minecraftKey("charcoal"))
register(minecraftKey("diamond"))
register(minecraftKey("iron_ingot"))
register(minecraftKey("gold_ingot"))
register(minecraftKey("stick"))
register(minecraftKey("bowl"))
register(minecraftKey("string"))
register(minecraftKey("feather"))
register(minecraftKey("gunpowder"))
register(minecraftKey("wheat_seeds"))
register(minecraftKey("wheat"))
register(minecraftKey("flint"))
register(minecraftKey("painting"))
register(minecraftKey("iron_door"))
register(minecraftKey("redstone"))
register(minecraftKey("leather"))
register(minecraftKey("brick"))
register(minecraftKey("clay_ball"))
register(minecraftKey("paper"))
register(minecraftKey("book"))
register(minecraftKey("slime_ball"))
register(minecraftKey("glowstone_dust"))
register(minecraftKey("inc_sac"))
register(minecraftKey("lapis_lazuli"))
register(minecraftKey("cocoa_beans"))
register(minecraftKey("bone_meal"))
register(minecraftKey("bone"))
register(minecraftKey("sugar"))
register(minecraftKey("repeater"))
register(minecraftKey("pumpkin_seeds"))
register(minecraftKey("melon_seeds"))
register(minecraftKey("ender_pearl"))
register(minecraftKey("blaze_rod"))
register(minecraftKey("ghast_tear"))
register(minecraftKey("gold_nugget"))
register(minecraftKey("nether_wart"))
register(minecraftKey("glass_bottle"))
register(minecraftKey("fermented_spider_eye"))
register(minecraftKey("blaze_powder"))
register(minecraftKey("magma_cream"))
register(minecraftKey("brewing_stand"))
register(minecraftKey("cauldron"))
register(minecraftKey("ender_eye"))
register(minecraftKey("glistering_melon_slice"))
register(minecraftKey("experience_bottle"))
register(minecraftKey("fire_charge"))
register(minecraftKey("emerald"))
register(minecraftKey("item_frame"))
register(minecraftKey("flower_pot"))
register(minecraftKey("map"))
register(minecraftKey("nether_star"))
register(minecraftKey("comparator"))
register(minecraftKey("nether_brick"))
register(minecraftKey("quartz"))
register(minecraftKey("prismarine_shard"))
register(minecraftKey("prismarine_crystals"))
register(minecraftKey("rabbit_foot"))
register(minecraftKey("rabbit_hide"))
register(minecraftKey("armor_stand"))
register(minecraftKey("lead"))
register(minecraftKey("name_tag"))
register(minecraftKey("end_crystal"))
register(minecraftKey("popped_chorus_fruit"))
register(minecraftKey("beetroot_seeds"))
register(minecraftKey("dragon_breath"))
register(minecraftKey("shulker_shell"))
register(minecraftKey("iron_nugget"))
register(minecraftKey("debug_stick"))
registerMinecarts()
registerDyeColors()
registerPotions()
registerBooks()
registerSkullsAndHeads()
registerFireworks()
registerBanners()
registerHorseArmor()
registerDoors()
registerBoats()
registerArrows()
registerMusicDiscs()
}
| mit | 68309ec43ad370ea873ce57f1bee8229 | 31.865285 | 108 | 0.627621 | 4.244513 | false | false | false | false |
stronganizer/stronganizer-android | Stronganizer/app/src/main/java/com/stronganizer/android/SmoothActionBarDrawerToggle.kt | 1 | 950 | package com.stronganizer.android
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.Toolbar
/**
* Created by valio_stoyanov on 8/5/17.
*/
class SmoothActionBarDrawerToggle(
activity: BaseNavigationDrawerActivity,
drawerLayout: DrawerLayout,
toolbar: Toolbar,
openDrawerContentDescRes: Int,
closeDrawerContentDescRes: Int
): ActionBarDrawerToggle(
activity, drawerLayout, toolbar,
openDrawerContentDescRes, closeDrawerContentDescRes) {
private var runnable: Runnable? = null
override fun onDrawerStateChanged(newState: Int) {
super.onDrawerStateChanged(newState)
if (newState == DrawerLayout.STATE_IDLE) {
runnable?.run()
runnable = null
}
}
fun runWhenIdle(task: Runnable) {
runnable = task
}
} | apache-2.0 | b0a00d86674503c9105eeb041dc1a95a | 26.970588 | 66 | 0.666316 | 4.846939 | false | false | false | false |
kropp/intellij-makefile | src/main/kotlin/name/kropp/intellij/makefile/toolWindow/MakefileFileNode.kt | 1 | 868 | package name.kropp.intellij.makefile.toolWindow
import com.intellij.psi.*
import name.kropp.intellij.makefile.*
import java.util.*
import java.util.Collections.*
import javax.swing.*
import javax.swing.tree.*
class MakefileFileNode(val psiFile: PsiFile, private val targets: List<MakefileTargetNode>) : MakefileTreeNode(psiFile.name) {
init {
for (target in targets) {
target.parent = this
}
}
internal lateinit var parent: MakefileRootNode
override val icon: Icon
get() = MakefileIcon
override fun children(): Enumeration<out TreeNode>? = enumeration(targets)
override fun isLeaf() = false
override fun getChildCount() = targets.size
override fun getParent() = parent
override fun getChildAt(i: Int) = targets[i]
override fun getIndex(node: TreeNode) = targets.indexOf(node)
override fun getAllowsChildren() = true
} | mit | 475462a3b14f8d0e7e6b0754aebd2546 | 23.828571 | 126 | 0.738479 | 4.193237 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/action/InsertEditorAction.kt | 1 | 1760 | package nl.hannahsten.texifyidea.action
import com.intellij.openapi.editor.CaretModel
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import javax.swing.Icon
/**
* @author Hannah Schellekens
*/
@Suppress("ComponentNotRegistered")
open class InsertEditorAction(
/**
* The name of the action.
*/
name: String,
/**
* The icon of the action.
*/
icon: Icon?,
/**
* The text to insert before the selection.
*/
before: String?,
/**
* The text to insert after the selection.
*/
after: String?
) : EditorAction(name, icon) {
/**
* What to insert before the selection.
*/
private val before: String = before ?: ""
/**
* What to insert after the selection.
*/
private val after: String = after ?: ""
override fun actionPerformed(file: VirtualFile, project: Project, textEditor: TextEditor) {
val editor = textEditor.editor
val document = editor.document
val selection = editor.selectionModel
val start = selection.selectionStart
val end = selection.selectionEnd
runWriteAction(project) { insert(document, start, end, editor.caretModel) }
}
private fun insert(document: Document, start: Int, end: Int, caretModel: CaretModel) {
document.insertString(end, this.after)
document.insertString(start, this.before)
val caretPosition = if (start == end) {
start + this.before.length
}
else {
end + this.before.length + this.after.length
}
caretModel.moveToOffset(caretPosition)
}
}
| mit | 60d9108f28389a80457a4b1e8bbb3215 | 25.666667 | 95 | 0.644886 | 4.455696 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/integrations/crafttweaker/PoweredThingiesTweaker.kt | 1 | 2628 | package net.ndrei.teslapoweredthingies.integrations.crafttweaker
import crafttweaker.annotations.ZenRegister
import net.ndrei.teslacorelib.annotations.InitializeDuringConstruction
import net.ndrei.teslapoweredthingies.machines.compoundmaker.CompoundMakerTweaker
import net.ndrei.teslapoweredthingies.machines.fluidburner.FluidBurnerCoolantTweaker
import net.ndrei.teslapoweredthingies.machines.fluidburner.FluidBurnerFuelTweaker
import net.ndrei.teslapoweredthingies.machines.fluidcompoundproducer.FluidCompoundProducerTweaker
import net.ndrei.teslapoweredthingies.machines.incinerator.IncineratorTweaker
import net.ndrei.teslapoweredthingies.machines.itemcompoundproducer.ItemCompoundProducerTweaker
import net.ndrei.teslapoweredthingies.machines.itemliquefier.ItemLiquefierTweaker
import net.ndrei.teslapoweredthingies.machines.powdermaker.PowderMakerTweaker
import net.ndrei.teslapoweredthingies.machines.poweredkiln.PoweredKilnTweaker
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@ZenRegister
@ZenClass("mods.poweredthingies.Tweaker")
@Suppress("unused")
@InitializeDuringConstruction
object PoweredThingiesTweaker {
private val compoundTweakerInstance by lazy { CompoundMakerTweaker() }
private val fluidBurnerCoolantInstance by lazy { FluidBurnerCoolantTweaker() }
private val fluidBurnerFuelInstance by lazy { FluidBurnerFuelTweaker() }
private val fluidCompoundTweakerInstance by lazy { FluidCompoundProducerTweaker() }
private val incineratorInstance by lazy { IncineratorTweaker() }
private val itemCompoundProducerInstance by lazy { ItemCompoundProducerTweaker() }
private val itemLiquefierInstance by lazy { ItemLiquefierTweaker() }
private val powderMakerInstance by lazy { PowderMakerTweaker() }
private val poweredKilnInstance by lazy { PoweredKilnTweaker() }
@ZenMethod @JvmStatic fun compoundTweaker() = this.compoundTweakerInstance
@ZenMethod @JvmStatic fun fluidBurnerCoolantTweaker() = this.fluidBurnerCoolantInstance
@ZenMethod @JvmStatic fun fluidBurnerFuelTweaker() = this.fluidBurnerFuelInstance
@ZenMethod @JvmStatic fun fluidCompoundTweaker() = this.fluidCompoundTweakerInstance
@ZenMethod @JvmStatic fun incineratorTweaker() = this.incineratorInstance
@ZenMethod @JvmStatic fun itemCompoundProducerTweaker() = this.itemCompoundProducerInstance
@ZenMethod @JvmStatic fun itemLiquefierTweaker() = this.itemLiquefierInstance
@ZenMethod @JvmStatic fun powderMakerTweaker() = this.powderMakerInstance
@ZenMethod @JvmStatic fun poweredKilnTweaker() = this.poweredKilnInstance
}
| mit | 1942d0eec87e64f1acea550509ee72fc | 63.097561 | 97 | 0.846271 | 4.469388 | false | false | false | false |
googlecodelabs/androidthings-surveybox | step2-gpio/android/app/src/main/java/com/example/surveybox/DatabaseManager.kt | 2 | 2727 | /*
* Copyright 2018, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.surveybox
import android.util.Log
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
/**
* Handles connection to Firebase
*/
class DatabaseManager {
private val TAG = DatabaseManager::class.java.simpleName
private val DEFAULT_NAME = "default"
private var currentDeviceInfo: DeviceInfo? = null
private var currentEvent = "default"
private var currentRoom = "default"
private val database: FirebaseDatabase
get() = FirebaseDatabase.getInstance()
init {
database.setPersistenceEnabled(true)
getFirebaseEvent()
}
private fun getFirebaseEvent() {
val deviceData = database.reference.child("devices").child("default")
deviceData.keepSynced(true)
Log.d(TAG, "Try to get current event")
deviceData.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
Log.d(TAG, "getCurrentEvent:success")
currentDeviceInfo = dataSnapshot.getValue(DeviceInfo::class.java)
currentEvent = currentDeviceInfo?.current_event ?: "default"
currentRoom = currentDeviceInfo?.current_room ?: "default"
if (currentEvent == "none") {
currentEvent = "default"
}
if (currentRoom == "none") {
currentRoom = "default"
}
Log.d(TAG, "current event is: $currentEvent")
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d(TAG, "DeviceDataListener:failure")
currentEvent = "default"
}
})
}
fun addButtonPress(button: Int) {
database.reference
.child("data")
.child(currentEvent)
.push()
.setValue(ButtonPress("default", currentRoom, button))
}
}
| apache-2.0 | 77a89f8907d2ed08b97732b907b92f1e | 31.464286 | 81 | 0.643198 | 4.878354 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/SingleSourceAllocation.kt | 1 | 15028 | /*
* Copyright @ 2020 - present 8x8, 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 org.jitsi.videobridge.cc.allocation
import org.jitsi.nlj.RtpLayerDesc
import org.jitsi.nlj.RtpLayerDesc.Companion.indexString
import org.jitsi.utils.logging.DiagnosticContext
import org.jitsi.utils.logging.TimeSeriesLogger
import org.jitsi.videobridge.cc.config.BitrateControllerConfig
import org.jitsi.videobridge.cc.config.BitrateControllerConfig.Companion.onstagePreferredFramerate
import org.jitsi.videobridge.cc.config.BitrateControllerConfig.Companion.onstagePreferredHeightPx
import org.jitsi.videobridge.util.VideoType
import java.lang.Integer.max
import java.time.Clock
/**
* A bitrate allocation that pertains to a specific source. This is the internal representation used in the allocation
* algorithm, as opposed to [SingleAllocation] which is the end result.
*
* @author George Politis
*/
internal class SingleSourceAllocation(
val endpoint: MediaSourceContainer,
/** The constraints to use while allocating bandwidth to this endpoint. */
val constraints: VideoConstraints,
/** Whether the endpoint is on stage. */
private val onStage: Boolean,
diagnosticContext: DiagnosticContext,
clock: Clock
) {
/**
* The immutable list of layers to be considered when allocating bandwidth.
*/
val layers: Layers = selectLayers(endpoint, onStage, constraints, clock.instant().toEpochMilli())
/**
* The index (into [layers] of the current target layer). It can be improved in the `improve()` step, if there is
* enough bandwidth.
*/
var targetIdx = -1
init {
if (timeSeriesLogger.isTraceEnabled) {
val ratesTimeSeriesPoint = diagnosticContext.makeTimeSeriesPoint("layers_considered")
.addField("remote_endpoint_id", endpoint.id)
for ((l, bitrate) in layers.layers) {
ratesTimeSeriesPoint.addField(
"${indexString(l.index)}_${l.height}p_${l.frameRate}fps_bps",
bitrate
)
}
timeSeriesLogger.trace(ratesTimeSeriesPoint)
}
}
fun isOnStage() = onStage
fun hasReachedPreferred(): Boolean = targetIdx >= layers.preferredIndex
/**
* Implements an "improve" step, incrementing [.targetIdx] to the next layer if there is sufficient
* bandwidth. Note that this works eagerly up until the "preferred" layer (if any), and as a single step from
* then on.
*
* @param maxBps the bandwidth available.
*/
fun improve(maxBps: Long, allowOversending: Boolean) {
if (layers.isEmpty()) {
return
}
if (targetIdx == -1 && layers.preferredIndex > -1 && onStage) {
// Boost on stage participant to preferred, if there's enough bw.
for (i in layers.indices) {
if (i > layers.preferredIndex || maxBps < layers[i].bitrate) {
break
}
targetIdx = i
}
} else {
// Try the next element in the ratedIndices array.
if (targetIdx + 1 < layers.size && layers[targetIdx + 1].bitrate < maxBps) {
targetIdx++
}
}
if (targetIdx > -1) {
// If there's a higher layer available with a lower bitrate, skip to it.
//
// For example, if 1080p@15fps is configured as a better subjective quality than 720p@30fps (i.e. it sits
// on a higher index in the ratedIndices array) and the bitrate that we measure for the 1080p stream is less
// than the bitrate that we measure for the 720p stream, then we "jump over" the 720p stream and immediately
// select the 1080p stream.
//
// TODO further: Should we just prune the list of layers we consider to not include such layers?
for (i in layers.size - 1 downTo targetIdx + 1) {
if (layers[i].bitrate <= layers[targetIdx].bitrate) {
targetIdx = i
}
}
}
// If oversending is allowed, look for a better layer which doesn't exceed maxBps by more than
// `maxOversendBitrate`.
if (allowOversending && layers.oversendIndex >= 0 && targetIdx < layers.oversendIndex) {
for (i in layers.oversendIndex downTo targetIdx + 1) {
if (layers[i].bitrate <= maxBps + BitrateControllerConfig.maxOversendBitrateBps()) {
targetIdx = i
}
}
}
}
/**
* The source is suspended if we've not selected a layer AND the source has active layers.
*
* TODO: this is not exactly correct because it only looks at the layers we consider. E.g. if the receiver set
* a maxHeight=0 constraint for an endpoint, it will appear suspended. This is not critical, because this val is
* only used for logging.
*/
val isSuspended: Boolean
get() = targetIdx == -1 && layers.isNotEmpty() && layers[0].bitrate > 0
/**
* Gets the target bitrate (in bps) for this endpoint allocation, i.e. the bitrate of the currently chosen layer.
*/
val targetBitrate: Long
get() = targetLayer?.bitrate?.toLong() ?: 0
private val targetLayer: LayerSnapshot?
get() = layers.getOrNull(targetIdx)
/**
* Gets the ideal bitrate (in bps) for this endpoint allocation, i.e. the bitrate of the layer the bridge would
* forward if there were no (bandwidth) constraints.
*/
val idealBitrate: Long
get() = layers.idealLayer?.bitrate?.toLong() ?: 0
/**
* Exposed for testing only.
*/
val preferredLayer: RtpLayerDesc?
get() = layers.preferredLayer?.layer
/**
* Exposed for testing only.
*/
val oversendLayer: RtpLayerDesc?
get() = layers.oversendLayer?.layer
/**
* Creates the final immutable result of this allocation. Should be called once the allocation algorithm has
* completed.
*/
val result: SingleAllocation
get() = SingleAllocation(
endpoint,
targetLayer?.layer,
layers.idealLayer?.layer
)
override fun toString(): String {
return (
"[id=" + endpoint.id +
" constraints=" + constraints +
" ratedPreferredIdx=" + layers.preferredIndex +
" ratedTargetIdx=" + targetIdx
)
}
companion object {
private val timeSeriesLogger = TimeSeriesLogger.getTimeSeriesLogger(BandwidthAllocator::class.java)
}
}
/**
* Saves the bitrate of a specific [RtpLayerDesc] at a specific point in time.
*/
data class LayerSnapshot(val layer: RtpLayerDesc, val bitrate: Double)
/**
* An immutable representation of the layers to be considered when allocating bandwidth for an endpoint. The order is
* ascending by preference (and not necessarily bitrate).
*/
data class Layers(
val layers: List<LayerSnapshot>,
/** The index of the "preferred" layer, i.e. the layer up to which we allocate eagerly. */
val preferredIndex: Int,
/**
* The index of the layer which will be selected if oversending is enabled. If set to -1, oversending is disabled.
*/
val oversendIndex: Int
) : List<LayerSnapshot> by layers {
val preferredLayer = layers.getOrNull(preferredIndex)
val oversendLayer = layers.getOrNull(oversendIndex)
val idealLayer = layers.lastOrNull()
companion object {
val noLayers = Layers(emptyList(), -1, -1)
}
}
/**
* Gets the "preferred" height and frame rate based on the constraints signaled from the receiver.
*
* For participants with sufficient maxHeight we favor frame rate over resolution. We consider all
* temporal layers for resolutions lower than the preferred, but for resolutions >= preferred, we only
* consider frame rates at least as high as the preferred. In practice this means we consider
* 180p/7.5fps, 180p/15fps, 180p/30fps, 360p/30fps and 720p/30fps.
*/
private fun getPreferred(constraints: VideoConstraints): Pair<Int, Double> {
return if (constraints.maxHeight > 180) {
Pair(onstagePreferredHeightPx(), onstagePreferredFramerate())
} else {
noPreferredHeightAndFrameRate
}
}
private val noPreferredHeightAndFrameRate = Pair(-1, -1.0)
/**
* Selects from the layers of a [MediaSourceContainer] the ones which should be considered when allocating bandwidth for
* an endpoint. Also selects the indices of the "preferred" and "oversend" layers.
*
* @param endpoint the [MediaSourceContainer] that describes the available layers.
* @param constraints the constraints signaled for the endpoint.
* @return the ordered list of [endpoint]'s layers which should be considered when allocating bandwidth, as well as the
* indices of the "preferred" and "oversend" layers.
*/
private fun selectLayers(
/** The endpoint which is the source of the stream(s). */
endpoint: MediaSourceContainer,
onStage: Boolean,
/** The constraints that the receiver specified for [endpoint]. */
constraints: VideoConstraints,
nowMs: Long
): Layers {
val source = endpoint.mediaSource
if (constraints.maxHeight <= 0 || source == null || !source.hasRtpLayers()) {
return Layers.noLayers
}
val layers = source.rtpLayers.map { LayerSnapshot(it, it.getBitrateBps(nowMs)) }
return when (endpoint.videoType) {
VideoType.CAMERA -> selectLayersForCamera(layers, constraints)
VideoType.NONE -> Layers.noLayers
VideoType.DESKTOP, VideoType.DESKTOP_HIGH_FPS -> selectLayersForScreensharing(layers, constraints, onStage)
}
}
/**
* Selects from a list of layers the ones which should be considered when allocating bandwidth, as well as the
* "preferred" and "oversend" layers. Logic specific to screensharing: we prioritize resolution over framerate,
* prioritize the highest layer over other endpoints (by setting the highest layer as "preferred"), and allow
* oversending up to the highest resolution (with low frame rate).
*/
private fun selectLayersForScreensharing(
layers: List<LayerSnapshot>,
constraints: VideoConstraints,
onStage: Boolean
): Layers {
var activeLayers = layers.filter { it.bitrate > 0 }
// No active layers usually happens when the source has just been signaled and we haven't received
// any packets yet. Add the layers here, so one gets selected and we can start forwarding sooner.
if (activeLayers.isEmpty()) activeLayers = layers
// We select all layers that satisfy the constraints.
var selectedLayers =
if (constraints.maxHeight < 0) {
activeLayers
} else {
activeLayers.filter { it.layer.height <= constraints.maxHeight }
}
// If no layers satisfy the constraints, we use the layers with the lowest resolution.
if (selectedLayers.isEmpty()) {
val minHeight = activeLayers.map { it.layer.height }.minOrNull() ?: return Layers.noLayers
selectedLayers = activeLayers.filter { it.layer.height == minHeight }
// This recognizes the structure used with VP9 (multiple encodings with the same resolution and unknown frame
// rate). In this case, we only want the low quality layer.
if (selectedLayers.isNotEmpty() && selectedLayers[0].layer.frameRate < 0) {
selectedLayers = listOf(selectedLayers[0])
}
}
val oversendIdx = if (onStage && BitrateControllerConfig.allowOversendOnStage()) {
val maxHeight = selectedLayers.map { it.layer.height }.maxOrNull() ?: return Layers.noLayers
selectedLayers.firstIndexWhich { it.layer.height == maxHeight }
} else {
-1
}
return Layers(selectedLayers, selectedLayers.size - 1, oversendIdx)
}
/** Return the index of the first item in the list which satisfies a predicate, or -1 if none do. */
private fun <T> List<T>.firstIndexWhich(predicate: (T) -> Boolean): Int {
forEachIndexed { index, item ->
if (predicate(item)) return index
}
return -1
}
/**
* Selects from a list of layers the ones which should be considered when allocating bandwidth, as well as the
* "preferred" and "oversend" layers. Logic specific to a camera stream: once the "preferred" height is reached we
* require a high frame rate, with preconfigured values for the "preferred" height and frame rate, and we do not allow
* oversending.
*/
private fun selectLayersForCamera(
layers: List<LayerSnapshot>,
constraints: VideoConstraints,
): Layers {
val minHeight = layers.map { it.layer.height }.minOrNull() ?: return Layers.noLayers
val noActiveLayers = layers.none { (_, bitrate) -> bitrate > 0 }
val (preferredHeight, preferredFps) = getPreferred(constraints)
val ratesList: MutableList<LayerSnapshot> = ArrayList()
// Initialize the list of layers to be considered. These are the layers that satisfy the constraints, with
// a couple of exceptions (see comments below).
for (layerSnapshot in layers) {
val layer = layerSnapshot.layer
val lessThanPreferredHeight = layer.height < preferredHeight
val lessThanOrEqualMaxHeight = layer.height <= constraints.maxHeight
// If frame rate is unknown, consider it to be sufficient.
val atLeastPreferredFps = layer.frameRate < 0 || layer.frameRate >= preferredFps
if (lessThanPreferredHeight ||
(lessThanOrEqualMaxHeight && atLeastPreferredFps) ||
layer.height == minHeight
) {
// No active layers usually happens when the source has just been signaled and we haven't received
// any packets yet. Add the layers here, so one gets selected and we can start forwarding sooner.
if (noActiveLayers || layerSnapshot.bitrate > 0) {
ratesList.add(layerSnapshot)
}
}
}
val effectivePreferredHeight = max(preferredHeight, minHeight)
val preferredIndex = ratesList.lastIndexWhich { it.layer.height <= effectivePreferredHeight }
return Layers(ratesList, preferredIndex, -1)
}
/**
* Returns the index of the last element of this list which satisfies the given predicate, or -1 if no elements do.
*/
private fun <T> List<T>.lastIndexWhich(predicate: (T) -> Boolean): Int {
var lastIndex = -1
forEachIndexed { i, e -> if (predicate(e)) lastIndex = i }
return lastIndex
}
| apache-2.0 | 105f7f5e08888e330ee027953f30df7b | 40.399449 | 120 | 0.670748 | 4.45406 | false | false | false | false |
CineCor/CinecorAndroid | app/src/main/java/com/cinecor/android/cinemas/movies/ui/MoviesFragment.kt | 1 | 2910 | package com.cinecor.android.cinemas.movies.ui
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.cinecor.android.R
import com.cinecor.android.data.model.Cinema
import com.cinecor.android.data.model.Movie
import com.cinecor.android.common.ui.BaseFragment
import com.cinecor.android.common.viewmodel.CinemaViewModel
import com.cinecor.android.common.viewmodel.CinemaViewModelFactory
import com.cinecor.android.moviedetail.ui.MovieDetailActivity
import com.cinecor.android.utils.IntentUtils
import kotlinx.android.synthetic.main.fragment_list_movies.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.support.v4.toast
import javax.inject.Inject
class MoviesFragment : BaseFragment(), Observer<Cinema>, MoviesAdapter.OnMovieClickListener {
companion object {
@JvmStatic fun getInstance(cinemaId: Int?): Fragment {
val fragment = MoviesFragment()
val args = Bundle()
args.putInt(IntentUtils.ARG_CINEMA_ID, cinemaId ?: -1)
fragment.arguments = args
return fragment
}
}
@Inject lateinit var factory: CinemaViewModelFactory
@Inject lateinit var adapter: MoviesAdapter
private lateinit var viewModel: CinemaViewModel
private var cinemaId = -1
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_list_movies, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
list.setHasFixedSize(true)
list.layoutManager = LinearLayoutManager(context)
list.adapter = adapter
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
cinemaId = arguments.getInt(IntentUtils.ARG_CINEMA_ID, -1)
viewModel = ViewModelProviders.of(activity, factory).get(CinemaViewModel::class.java)
viewModel.getCinema(cinemaId).observe(this, this)
}
override fun onChanged(cinema: Cinema?) {
cinema?.movies?.let { adapter.updateMovies(it) } ?: toast("Error loading Cinemas")
}
override fun onMovieClicked(movie: Movie, image: ImageView) {
val intent = activity.intentFor<MovieDetailActivity>(IntentUtils.ARG_CINEMA_ID to cinemaId, IntentUtils.ARG_MOVIE_ID to movie.id)
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, image, "backdrop").toBundle()
startActivity(intent, options)
}
}
| gpl-3.0 | 91f8a612b8fd2dd83e83ed62fc8d1157 | 39.416667 | 137 | 0.754639 | 4.415781 | false | false | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/comm/CommViewModel.kt | 1 | 794 | package com.didichuxing.doraemondemo.comm
import androidx.lifecycle.*
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:3/11/21-16:12
* 描 述:
* 修订历史:
* ================================================
*/
class CommViewModel(private val state: SavedStateHandle) : ViewModel() {
companion object {
const val KEY_TITLE = "title"
}
var title: String?
get() {
return state.get(KEY_TITLE)
}
set(value) {
state.set(KEY_TITLE, value)
}
fun getTitle(): LiveData<String> {
return state.getLiveData<String>(KEY_TITLE, "DoKit")
}
fun saveTitle(title: String) {
state.set(KEY_TITLE, title)
}
} | apache-2.0 | 966ccb37f193cbc0e97aa3c056ebc2e9 | 19.805556 | 72 | 0.485294 | 3.85567 | false | false | false | false |
arturbosch/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/documentation/LicenceHeaderLoaderExtensionSpec.kt | 1 | 1341 | package io.gitlab.arturbosch.detekt.rules.documentation
import io.github.detekt.test.utils.NullPrintStream
import io.github.detekt.test.utils.resource
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.SetupContext
import io.gitlab.arturbosch.detekt.api.UnstableApi
import org.assertj.core.api.Assertions.assertThatCode
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.PrintStream
import java.net.URI
@OptIn(UnstableApi::class)
class LicenceHeaderLoaderExtensionSpec : Spek({
describe("Licence header extension - #2503") {
it("should not crash when using resources") {
assertThatCode {
LicenceHeaderLoaderExtension().init(object : SetupContext {
override val configUris: Collection<URI> = listOf(resource("extensions/config.yml"))
override val config: Config = Config.empty
override val outputChannel: PrintStream = NullPrintStream()
override val errorChannel: PrintStream = NullPrintStream()
override val properties: Map<String, Any?> = HashMap()
override fun register(key: String, value: Any) = Unit
})
}.doesNotThrowAnyException()
}
}
})
| apache-2.0 | 280da7d264986110cdd1383e92b84d5a | 40.90625 | 104 | 0.690529 | 4.640138 | false | true | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/EditPlaceTask.kt | 1 | 1776 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.tools.places
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.StringParameter
import uk.co.nickthecoder.paratask.parameters.compound.ResourceParameter
open class EditPlaceTask(protected val place: PlaceInFile, name: String = "editPlace")
: AbstractTask() {
final override val taskD = TaskDescription(name)
val labelP = StringParameter("label", required = false, value = place.label)
val resourceP = ResourceParameter("resource", value = place.resource)
var resource by resourceP
init {
taskD.addParameters(labelP, resourceP)
}
override fun run() {
val index = place.placesFile.places.indexOf(place)
place.placesFile.places.remove(place)
val newPlace = PlaceInFile(place.placesFile, resource!!, labelP.value)
if (index >= 0) {
place.placesFile.places.add(index, newPlace)
} else {
place.placesFile.places.add(newPlace)
}
place.placesFile.save()
}
}
| gpl-3.0 | 83dde72a1042d5effe486792543631b1 | 33.153846 | 86 | 0.734234 | 4.218527 | false | false | false | false |
marciogranzotto/mqtt-painel-kotlin | app/src/main/java/com/granzotto/mqttpainel/adapters/EquipmentCardAdapter.kt | 1 | 2141 | package com.granzotto.mqttpainel.adapters
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.granzotto.mqttpainel.BuildConfig
import com.granzotto.mqttpainel.R
import com.granzotto.mqttpainel.models.EquipmentObj
import com.granzotto.mqttpainel.utils.extensions.inflate
import com.pawegio.kandroid.i
import io.realm.RealmResults
import kotlinx.android.synthetic.main.equipment_cell.view.*
class EquipmentCardAdapter(var items: RealmResults<EquipmentObj>, private val listener: EquipmentListener): RecyclerView.Adapter<EquipmentCardViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EquipmentCardViewHolder {
val v = inflate(R.layout.equipment_cell, parent)
return EquipmentCardViewHolder(v)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: EquipmentCardViewHolder, position: Int) {
items[position]?.let { holder.bindViewHolder(it, listener) }
}
}
class EquipmentCardViewHolder(val view: View): RecyclerView.ViewHolder(view) {
fun bindViewHolder(equipmentObj: EquipmentObj, listener: EquipmentListener) {
i { "default alpha: ${itemView.alpha}" }
itemView.stateSwitch.setOnCheckedChangeListener(null)
itemView.progressWheel.visibility = View.GONE
itemView.title.text = equipmentObj.name
itemView.subTitle.text = equipmentObj.topic
itemView.stateSwitch.isChecked = equipmentObj.getValueAsBoolean()
itemView.stateSwitch.setOnCheckedChangeListener { _, isChecked ->
if (BuildConfig.DEBUG) i { "State changed for ${equipmentObj.name}! Now it's $isChecked" }
itemView.progressWheel.visibility = View.VISIBLE
itemView.progressWheel.spin()
listener.onStateChanged(equipmentObj, isChecked)
}
itemView.setOnClickListener { listener.onEquipmentClicked(equipmentObj) }
}
}
interface EquipmentListener {
fun onStateChanged(equipment: EquipmentObj, state: Boolean)
fun onEquipmentClicked(equipment: EquipmentObj)
} | gpl-3.0 | 87bb8ebfeafb17bcfd094c519b58cb21 | 37.25 | 157 | 0.749183 | 4.469729 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/support/ConnectorStatus.kt | 1 | 670 | package net.nemerosa.ontrack.model.support
/**
* Status of a connector.
*/
data class ConnectorStatus(
val description: ConnectorDescription,
val type: ConnectorStatusType,
val error: String?
) {
companion object {
fun ok(connector: ConnectorDescription) = ConnectorStatus(
description = connector,
type = ConnectorStatusType.UP,
error = null
)
fun error(connector: ConnectorDescription, ex: Exception) = ConnectorStatus(
description = connector,
type = ConnectorStatusType.DOWN,
error = ex.message
)
}
} | mit | 59d34ed57a45b48e5c2f02240826999a | 24.807692 | 84 | 0.589552 | 5.193798 | false | false | false | false |
nextcloud/android | app/src/androidTest/java/com/owncloud/android/utils/FileExportUtilsIT.kt | 1 | 2545 | /*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2022 Tobias Kaminsky
* Copyright (C) 2022 Nextcloud GmbH
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.utils
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
class FileExportUtilsIT : AbstractIT() {
@Test
fun exportFile() {
val file = createFile("export.txt", 10)
val sut = FileExportUtils()
val expectedFile = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
File("/sdcard/Downloads/export.txt")
} else {
File("/storage/emulated/0/Download/export.txt")
}
assertFalse(expectedFile.exists())
sut.exportFile("export.txt", "/text/plain", targetContext.contentResolver, null, file)
assertTrue(expectedFile.exists())
assertEquals(file.length(), expectedFile.length())
assertTrue(expectedFile.delete())
}
@Test
fun exportOCFile() {
val file = createFile("export.txt", 10)
val ocFile = OCFile("/export.txt").apply {
storagePath = file.absolutePath
}
val sut = FileExportUtils()
val expectedFile = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
File("/sdcard/Downloads/export.txt")
} else {
File("/storage/emulated/0/Download/export.txt")
}
assertFalse(expectedFile.exists())
sut.exportFile("export.txt", "/text/plain", targetContext.contentResolver, ocFile, null)
assertTrue(expectedFile.exists())
assertEquals(file.length(), expectedFile.length())
assertTrue(expectedFile.delete())
}
}
| gpl-2.0 | c8cd4406293f18a58cf73da5cbff8020 | 31.628205 | 102 | 0.680157 | 4.291737 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/torrentslistfragment/TorrentsAdapter.kt | 1 | 16924 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tremotesf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.equeim.tremotesf.ui.torrentslistfragment
import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.view.*
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.view.ActionMode
import androidx.recyclerview.widget.DiffUtil
import org.equeim.libtremotesf.TorrentData
import org.equeim.tremotesf.R
import org.equeim.tremotesf.databinding.TorrentListItemBinding
import org.equeim.tremotesf.databinding.TorrentListItemCompactBinding
import org.equeim.tremotesf.rpc.GlobalRpc
import org.equeim.tremotesf.torrentfile.rpc.Torrent
import org.equeim.tremotesf.ui.SelectionTracker
import org.equeim.tremotesf.ui.utils.*
import java.lang.ref.WeakReference
class TorrentsAdapter(
private val fragment: TorrentsListFragment,
private val compactView: Boolean,
private val multilineName: Boolean
) :
StateRestoringListAdapter<Torrent, TorrentsAdapter.BaseTorrentsViewHolder>(Callback()) {
private val selectionTracker = SelectionTracker.createForIntKeys(
this,
true,
fragment,
{ ActionModeCallback(this, it) },
R.plurals.torrents_selected
) {
getItem(it).id
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseTorrentsViewHolder {
if (compactView) {
return TorrentsViewHolderCompact(
multilineName,
TorrentListItemCompactBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
return TorrentsViewHolder(
multilineName,
TorrentListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: BaseTorrentsViewHolder, position: Int) {
holder.update()
}
fun update(torrents: List<Torrent>) {
submitList(torrents) {
selectionTracker.commitAdapterUpdate()
}
}
override fun allowStateRestoring(): Boolean {
return GlobalRpc.isConnected.value
}
override fun onStateRestored() {
selectionTracker.restoreInstanceState()
}
inner class TorrentsViewHolder(
multilineName: Boolean,
private val binding: TorrentListItemBinding
) : BaseTorrentsViewHolder(multilineName, binding.root) {
override fun update() {
val oldTorrent = torrent
super.update()
val torrent = this.torrent ?: return
with(binding) {
if (torrent.isFinished) {
if (oldTorrent?.isFinished != torrent.isFinished ||
oldTorrent.sizeWhenDone != torrent.sizeWhenDone ||
oldTorrent.totalUploaded != torrent.totalUploaded
) {
sizeTextView.text =
context.getString(
R.string.uploaded_string,
FormatUtils.formatByteSize(context, torrent.sizeWhenDone),
FormatUtils.formatByteSize(context, torrent.totalUploaded)
)
}
} else {
if (oldTorrent?.isFinished != torrent.isFinished ||
oldTorrent.completedSize != torrent.completedSize ||
oldTorrent.sizeWhenDone != torrent.sizeWhenDone
) {
sizeTextView.text = context.getString(
R.string.completed_string,
FormatUtils.formatByteSize(context, torrent.completedSize),
FormatUtils.formatByteSize(context, torrent.sizeWhenDone),
DecimalFormats.generic.format(torrent.percentDone * 100)
)
}
}
if (oldTorrent?.eta != torrent.eta) {
etaTextView.text = FormatUtils.formatDuration(context, torrent.eta)
}
progressBar.progress = (torrent.percentDone * 100).toInt()
if (oldTorrent?.downloadSpeed != torrent.downloadSpeed) {
downloadSpeedTextView.text = context.getString(
R.string.download_speed_string,
FormatUtils.formatByteSpeed(
context,
torrent.downloadSpeed
)
)
}
if (oldTorrent?.uploadSpeed != torrent.uploadSpeed) {
uploadSpeedTextView.text = context.getString(
R.string.upload_speed_string,
FormatUtils.formatByteSpeed(
context,
torrent.uploadSpeed
)
)
}
torrent.getStatusStringIfChanged(oldTorrent, context)?.let {
statusTextView.text = it
}
}
}
override fun updateSelectionState(isSelected: Boolean) {
binding.root.isChecked = isSelected
}
}
inner class TorrentsViewHolderCompact(
multilineName: Boolean,
private val binding: TorrentListItemCompactBinding
) : BaseTorrentsViewHolder(multilineName, binding.root) {
override fun update() {
val oldTorrent = torrent
super.update()
val torrent = this.torrent ?: return
val speedLabelsWereEmpty = downloadSpeedTextView.text.isEmpty() && uploadSpeedTextView.text.isEmpty()
if (oldTorrent?.downloadSpeed != torrent.downloadSpeed) {
downloadSpeedTextView.text = if (torrent.downloadSpeed == 0L) {
""
} else {
context.getString(
R.string.download_speed_string,
FormatUtils.formatByteSpeed(
context,
torrent.downloadSpeed
)
)
}
}
if (oldTorrent?.uploadSpeed != torrent.uploadSpeed) {
uploadSpeedTextView.text = if (torrent.uploadSpeed == 0L) {
""
} else {
context.getString(
R.string.upload_speed_string,
FormatUtils.formatByteSpeed(
context,
torrent.uploadSpeed
)
)
}
}
val speedLabelsAreEmpty = downloadSpeedTextView.text.isEmpty() && uploadSpeedTextView.text.isEmpty()
if (speedLabelsWereEmpty != speedLabelsAreEmpty ||
!(oldTorrent?.percentDone fuzzyEquals torrent.percentDone)
) {
binding.progressTextView.text = context.getString(
if (torrent.downloadSpeed != 0L || torrent.uploadSpeed != 0L) R.string.progress_string_with_dot else R.string.progress_string,
DecimalFormats.generic.format(torrent.percentDone * 100)
)
}
}
}
open inner class BaseTorrentsViewHolder(
multilineName: Boolean,
itemView: View
) : SelectionTracker.ViewHolder<Int>(selectionTracker, itemView) {
protected var torrent: Torrent? = null
private set
protected val context: Context = itemView.context
private val nameTextView = itemView.findViewById<TextView>(R.id.name_text_view)!!
@DrawableRes
private var iconResId = 0
protected val downloadSpeedTextView =
itemView.findViewById<TextView>(R.id.download_speed_text_view)!!
protected val uploadSpeedTextView =
itemView.findViewById<TextView>(R.id.upload_speed_text_view)!!
init {
if (!multilineName) {
nameTextView.ellipsize = TextUtils.TruncateAt.END
nameTextView.maxLines = 1
nameTextView.isSingleLine = true
}
}
override fun update() {
super.update()
val torrent = bindingAdapterPositionOrNull?.let(::getItem) ?: return
val oldTorrent = this.torrent
this.torrent = torrent
if (oldTorrent?.name != torrent.name) {
nameTextView.text = torrent.name
}
val resId = when (torrent.status) {
TorrentData.Status.Paused -> R.drawable.ic_pause_24dp
TorrentData.Status.Downloading,
TorrentData.Status.StalledDownloading,
TorrentData.Status.QueuedForDownloading -> R.drawable.ic_arrow_downward_24dp
TorrentData.Status.Seeding,
TorrentData.Status.StalledSeeding,
TorrentData.Status.QueuedForSeeding -> R.drawable.ic_arrow_upward_24dp
TorrentData.Status.Checking,
TorrentData.Status.QueuedForChecking -> R.drawable.ic_refresh_24dp
TorrentData.Status.Errored -> R.drawable.ic_error_24dp
else -> 0
}
if (resId != iconResId) {
nameTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(resId, 0, 0, 0)
iconResId = resId
}
}
override fun onClick(view: View) {
val torrent = this.torrent ?: return
fragment.navigate(
TorrentsListFragmentDirections.toTorrentPropertiesFragment(
torrent.hashString,
torrent.name
)
)
}
}
private class ActionModeCallback(
adapter: TorrentsAdapter,
selectionTracker: SelectionTracker<Int>
) :
SelectionTracker.ActionModeCallback<Int>(selectionTracker) {
private val adapter = WeakReference(adapter)
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.torrents_context_menu, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
super.onPrepareActionMode(mode, menu)
if (selectionTracker?.selectedCount == 1) {
val startEnabled = when (adapter.get()?.getFirstSelectedTorrent()?.status) {
TorrentData.Status.Paused,
TorrentData.Status.Errored -> true
else -> false
}
for (id in intArrayOf(R.id.start, R.id.start_now)) {
menu.findItem(id).isEnabled = startEnabled
}
menu.findItem(R.id.pause).isEnabled = !startEnabled
} else {
menu.setGroupEnabled(0, true)
}
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
if (super.onActionItemClicked(mode, item)) {
return true
}
val selectionTracker = this.selectionTracker ?: return false
val adapter = this.adapter.get() ?: return false
val getTorrentIds = {
selectionTracker.selectedKeys.toIntArray()
}
when (item.itemId) {
R.id.start -> GlobalRpc.nativeInstance.startTorrents(getTorrentIds())
R.id.pause -> GlobalRpc.nativeInstance.pauseTorrents(getTorrentIds())
R.id.check -> GlobalRpc.nativeInstance.checkTorrents(getTorrentIds())
R.id.start_now -> GlobalRpc.nativeInstance.startTorrentsNow(getTorrentIds())
R.id.reannounce -> GlobalRpc.nativeInstance.reannounceTorrents(getTorrentIds())
R.id.set_location -> {
activity.navigate(
TorrentsListFragmentDirections.toTorrentSetLocationDialog(
getTorrentIds(),
adapter.getFirstSelectedTorrent().downloadDirectory
)
)
}
R.id.rename -> {
val torrent = adapter.getFirstSelectedTorrent()
activity.navigate(
TorrentsListFragmentDirections.toTorrentFileRenameDialog(
torrent.name,
torrent.name,
torrent.id
)
)
}
R.id.remove -> activity.navigate(
TorrentsListFragmentDirections.toRemoveTorrentDialog(
getTorrentIds()
)
)
R.id.share -> {
val magnetLinks =
adapter.currentList.slice(
selectionTracker.getSelectedPositionsUnsorted().sorted()
)
.map { it.data.magnetLink }
Utils.shareTorrents(magnetLinks, activity)
}
else -> return false
}
return true
}
private fun TorrentsAdapter.getFirstSelectedTorrent(): Torrent {
return getItem(selectionTracker.getFirstSelectedPosition())
}
}
private class Callback : DiffUtil.ItemCallback<Torrent>() {
override fun areItemsTheSame(oldItem: Torrent, newItem: Torrent): Boolean {
return oldItem.id == newItem.id
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: Torrent, newItem: Torrent): Boolean {
return oldItem === newItem
}
}
}
private fun Torrent.getStatusStringIfChanged(oldTorrent: Torrent?, context: Context): CharSequence? {
val statusChanged = oldTorrent?.status != status
return when (status) {
TorrentData.Status.Paused -> context.getTextIf(R.string.torrent_paused, statusChanged)
TorrentData.Status.Downloading -> if (statusChanged || oldTorrent?.seeders != seeders) {
context.resources.getQuantityString(
R.plurals.torrent_downloading,
seeders,
seeders
)
} else {
null
}
TorrentData.Status.StalledDownloading -> context.getTextIf(R.string.torrent_downloading_stalled, statusChanged)
TorrentData.Status.Seeding -> if (statusChanged || oldTorrent?.leechers != leechers) {
context.resources.getQuantityString(
R.plurals.torrent_seeding,
leechers,
leechers
)
} else {
null
}
TorrentData.Status.StalledSeeding -> context.getTextIf(R.string.torrent_seeding_stalled, statusChanged)
TorrentData.Status.QueuedForDownloading,
TorrentData.Status.QueuedForSeeding -> context.getTextIf(R.string.torrent_queued, statusChanged)
TorrentData.Status.Checking -> if (statusChanged || !(oldTorrent?.recheckProgress fuzzyEquals recheckProgress)) {
context.getString(
R.string.torrent_checking,
DecimalFormats.generic.format(recheckProgress * 100)
)
} else {
null
}
TorrentData.Status.QueuedForChecking -> context.getTextIf(R.string.torrent_queued_for_checking, statusChanged)
TorrentData.Status.Errored -> if (statusChanged || oldTorrent?.errorString != errorString) {
errorString
} else {
null
}
else -> null
}
}
private fun Context.getTextIf(@StringRes resId: Int, get: Boolean): CharSequence? {
return if (get) {
getText(resId)
} else {
null
}
}
| gpl-3.0 | 9d9ca325aa089f9f79435e49d1618492 | 37.289593 | 146 | 0.564051 | 5.386378 | false | false | false | false |
soywiz/korge | korge-dragonbones/src/commonMain/kotlin/com/dragonbones/armature/Armature.kt | 1 | 24836 | /**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* 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.
*/
@file:Suppress("KDocUnresolvedReference")
package com.dragonbones.armature
import com.dragonbones.animation.*
import com.dragonbones.core.*
import com.dragonbones.event.*
import com.soywiz.kds.iterators.*
import com.dragonbones.model.*
import com.dragonbones.util.*
import com.dragonbones.util.length
import com.soywiz.kds.*
import com.soywiz.klogger.*
import com.soywiz.kmem.*
import com.soywiz.korma.geom.*
/**
* - Armature is the core of the skeleton animation system.
* @see dragonBones.ArmatureData
* @see dragonBones.Bone
* @see dragonBones.Slot
* @see dragonBones.Animation
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 骨架是骨骼动画系统的核心。
* @see dragonBones.ArmatureData
* @see dragonBones.Bone
* @see dragonBones.Slot
* @see dragonBones.Animation
* @version DragonBones 3.0
* @language zh_CN
*/
class Armature(pool: SingleObjectPool<Armature>) : BaseObject(pool), IAnimatable {
override fun toString(): String {
return "[class dragonBones.Armature]"
}
companion object {
fun _onSortSlots(a: Slot, b: Slot): Int {
// @TODO: Circumvents kotlin-native bug
val aa = a._zIndex * 1000 + a._zOrder
val bb = b._zIndex * 1000 + b._zOrder
return aa.compareTo(bb)
//return if (a._zIndex * 1000 + a._zOrder > b._zIndex * 1000 + b._zOrder) 1 else -1
}
}
/**
* - Whether to inherit the animation control of the parent armature.
* True to try to have the child armature play an animation with the same name when the parent armature play the animation.
* @default true
* @version DragonBones 4.5
* @language en_US
*/
/**
* - 是否继承父骨架的动画控制。
* 如果该值为 true,当父骨架播放动画时,会尝试让子骨架播放同名动画。
* @default true
* @version DragonBones 4.5
* @language zh_CN
*/
var inheritAnimation: Boolean = true
/**
* @private
*/
var userData: Any? = null
/**
* @internal
*/
var _lockUpdate: Boolean = false
private var _slotsDirty: Boolean = true
private var _zOrderDirty: Boolean = false
/**
* @internal
*/
var _zIndexDirty: Boolean = false
/**
* @internal
*/
var _alphaDirty: Boolean = true
private var _flipX: Boolean = false
private var _flipY: Boolean = false
/**
* @internal
*/
var _cacheFrameIndex: Int = -1
private var _alpha: Double = 1.0
/**
* @internal
*/
var _globalAlpha: Double = 1.0
private val _bones: FastArrayList<Bone> = FastArrayList()
private val _slots: FastArrayList<Slot> = FastArrayList()
/**
* @internal
*/
val _constraints: FastArrayList<Constraint> = FastArrayList()
private val _actions: FastArrayList<EventObject> = FastArrayList()
/**
* @internal
*/
var _armatureData: ArmatureData? = null
private var _animation: Animation? = null // Initial value.
private var _proxy: IArmatureProxy? = null// Initial value.
private var _display: Any? = null
/**
* @internal
*/
var _replaceTextureAtlasData: TextureAtlasData? = null // Initial value.
private var _replacedTexture: Any? = null
/**
* @internal
*/
var _dragonBones: DragonBones? = null
private var _clock: WorldClock? = null // Initial value.
/**
* @internal
*/
var _parent: Slot? = null
override fun _onClear() {
this._clock?.remove(this)
this._bones.fastForEach { bone ->
bone.returnToPool()
}
this._slots.fastForEach { slot ->
slot.returnToPool()
}
this._constraints.fastForEach { constraint ->
constraint.returnToPool()
}
this._actions.fastForEach { action ->
action.returnToPool()
}
this._animation?.returnToPool()
this._proxy?.dbClear()
this._replaceTextureAtlasData?.returnToPool()
this.inheritAnimation = true
this.userData = null
this._lockUpdate = false
this._slotsDirty = true
this._zOrderDirty = false
this._zIndexDirty = false
this._alphaDirty = true
this._flipX = false
this._flipY = false
this._cacheFrameIndex = -1
this._alpha = 1.0
this._globalAlpha = 1.0
this._bones.lengthSet = 0
this._slots.lengthSet = 0
this._constraints.lengthSet = 0
this._actions.lengthSet = 0
this._armatureData = null //
this._animation = null //
this._proxy = null //
this._display = null
this._replaceTextureAtlasData = null
this._replacedTexture = null
this._dragonBones = null //
this._clock = null
this._parent = null
}
/**
* @internal
*/
fun _sortZOrder(slotIndices: Int16Buffer?, offset: Int) {
val slotDatas = this._armatureData!!.sortedSlots
if (this._zOrderDirty || slotIndices != null) {
val l = slotDatas.lengthSet
for (i in 0 until l) {
val slotIndex: Int = if (slotIndices == null) i else slotIndices[offset + i].toInt()
if (slotIndex < 0 || slotIndex >= l) {
continue
}
val slotData = slotDatas[slotIndex]
val slot = this.getSlot(slotData.name)
if (slot != null) {
slot._setZOrder(i)
}
}
this._slotsDirty = true
this._zOrderDirty = slotIndices != null
}
}
/**
* @internal
*/
fun _addBone(value: Bone) {
if (this._bones.indexOf(value) < 0) {
this._bones.add(value)
}
}
/**
* @internal
*/
fun _addSlot(value: Slot) {
if (this._slots.indexOf(value) < 0) {
this._slots.add(value)
}
}
/**
* @internal
*/
fun _addConstraint(value: Constraint) {
if (this._constraints.indexOf(value) < 0) {
this._constraints.add(value)
}
}
/**
* @internal
*/
fun _bufferAction(action: EventObject, append: Boolean) {
if (this._actions.indexOf(action) < 0) {
if (append) {
this._actions.add(action)
}
else {
this._actions.add(0, action)
}
}
}
/**
* - Dispose the armature. (Return to the object pool)
* @example
* <pre>
* removeChild(armature.display);
* armature.dispose();
* </pre>
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 释放骨架。 (回收到对象池)
* @example
* <pre>
* removeChild(armature.display);
* armature.dispose();
* </pre>
* @version DragonBones 3.0
* @language zh_CN
*/
fun dispose() {
if (this._armatureData != null) {
this._lockUpdate = true
//this._dragonBones?.bufferObject(this)
this.returnToPool()
}
}
/**
* @internal
*/
fun init(
armatureData: ArmatureData,
proxy: IArmatureProxy, display: Any, dragonBones: DragonBones
) {
if (this._armatureData != null) {
return
}
this._armatureData = armatureData
this._animation = pool.animation.borrow()
this._proxy = proxy
this._display = display
this._dragonBones = dragonBones
this._proxy?.dbInit(this)
this._animation?.init(this)
this._animation?.animations = this._armatureData?.animations!!
}
override fun advanceTime(passedTime: Double) {
_advanceTime(passedTime)
_slots.fastForEach { slot ->
slot.childArmature?.advanceTime(passedTime)
//slot._armature?.advanceTime(passedTime)
}
}
/**
* @inheritDoc
*/
private fun _advanceTime(passedTime: Double) {
if (this._lockUpdate) {
return
}
this._lockUpdate = true
if (this._armatureData == null) {
Console.warn("The armature has been disposed.")
return
}
else if (this._armatureData?.parent == null) {
Console.warn("The armature data has been disposed.\nPlease make sure dispose armature before call factory.clear().")
return
}
val prevCacheFrameIndex = this._cacheFrameIndex
// Update animation.
this._animation?.advanceTime(passedTime)
// Sort slots.
if (this._slotsDirty || this._zIndexDirty) {
this._slots.sortWith(Comparator(Armature.Companion::_onSortSlots))
if (this._zIndexDirty) {
for (i in 0 until this._slots.size) {
this._slots[i]._setZOrder(i) //
}
}
this._slotsDirty = false
this._zIndexDirty = false
}
// Update alpha.
if (this._alphaDirty) {
this._alphaDirty = false
this._globalAlpha = this._alpha * (this._parent?._globalAlpha ?: 1.0)
for (n in 0 until _bones.size) {
_bones[n]._updateAlpha()
}
for (n in 0 until _slots.size) {
_slots[n]._updateAlpha()
}
}
// Update bones and slots.
if (this._cacheFrameIndex < 0 || this._cacheFrameIndex != prevCacheFrameIndex) {
for (i in 0 until this._bones.length) {
this._bones[i].update(this._cacheFrameIndex)
}
for (i in 0 until this._slots.length) {
this._slots[i].update(this._cacheFrameIndex)
}
}
// Do actions.
if (this._actions.lengthSet > 0) {
this._actions.fastForEach { action ->
val actionData = action.actionData
if (actionData != null) {
if (actionData.type == ActionType.Play) {
when {
action.slot != null -> {
val childArmature = action.slot?.childArmature
childArmature?.animation?.fadeIn(actionData.name)
}
action.bone != null -> {
for (n in 0 until this._slots.size) {
val slot = this._slots[n]
if (slot.parent == action.bone) {
val childArmature = slot.childArmature
childArmature?.animation?.fadeIn(actionData.name)
}
}
}
else -> {
this._animation?.fadeIn(actionData.name)
}
}
}
}
action.returnToPool()
}
this._actions.lengthSet = 0
}
this._lockUpdate = false
this._proxy?.dbUpdate()
}
/**
* - Forces a specific bone or its owning slot to update the transform or display property in the next frame.
* @param boneName - The bone name. (If not set, all bones will be update)
* @param updateSlot - Whether to update the bone's slots. (Default: false)
* @see dragonBones.Bone#invalidUpdate()
* @see dragonBones.Slot#invalidUpdate()
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 强制特定骨骼或其拥有的插槽在下一帧更新变换或显示属性。
* @param boneName - 骨骼名称。 (如果未设置,将更新所有骨骼)
* @param updateSlot - 是否更新骨骼的插槽。 (默认: false)
* @see dragonBones.Bone#invalidUpdate()
* @see dragonBones.Slot#invalidUpdate()
* @version DragonBones 3.0
* @language zh_CN
*/
fun invalidUpdate(boneName: String? = null, updateSlot: Boolean = false) {
if (boneName != null && boneName.length > 0) {
val bone = this.getBone(boneName)
if (bone != null) {
bone.invalidUpdate()
if (updateSlot) {
this._slots.fastForEach { slot ->
if (slot.parent == bone) {
slot.invalidUpdate()
}
}
}
}
}
else {
this._bones.fastForEach { bone ->
bone.invalidUpdate()
}
if (updateSlot) {
this._slots.fastForEach { slot ->
slot.invalidUpdate()
}
}
}
}
/**
* - Check whether a specific point is inside a custom bounding box in a slot.
* The coordinate system of the point is the inner coordinate system of the armature.
* Custom bounding boxes need to be customized in Dragonbones Pro.
* @param x - The horizontal coordinate of the point.
* @param y - The vertical coordinate of the point.
* @version DragonBones 5.0
* @language en_US
*/
/**
* - 检查特定点是否在某个插槽的自定义边界框内。
* 点的坐标系为骨架内坐标系。
* 自定义边界框需要在 DragonBones Pro 中自定义。
* @param x - 点的水平坐标。
* @param y - 点的垂直坐标。
* @version DragonBones 5.0
* @language zh_CN
*/
fun containsPoint(x: Double, y: Double): Slot? {
this._slots.fastForEach { slot ->
if (slot.containsPoint(x, y)) {
return slot
}
}
return null
}
/**
* - Check whether a specific segment intersects a custom bounding box for a slot in the armature.
* The coordinate system of the segment and intersection is the inner coordinate system of the armature.
* Custom bounding boxes need to be customized in Dragonbones Pro.
* @param xA - The horizontal coordinate of the beginning of the segment.
* @param yA - The vertical coordinate of the beginning of the segment.
* @param xB - The horizontal coordinate of the end point of the segment.
* @param yB - The vertical coordinate of the end point of the segment.
* @param intersectionPointA - The first intersection at which a line segment intersects the bounding box from the beginning to the end. (If not set, the intersection point will not calculated)
* @param intersectionPointB - The first intersection at which a line segment intersects the bounding box from the end to the beginning. (If not set, the intersection point will not calculated)
* @param normalRadians - The normal radians of the tangent of the intersection boundary box. [x: Normal radian of the first intersection tangent, y: Normal radian of the second intersection tangent] (If not set, the normal will not calculated)
* @returns The slot of the first custom bounding box where the segment intersects from the start point to the end point.
* @version DragonBones 5.0
* @language en_US
*/
/**
* - 检查特定线段是否与骨架的某个插槽的自定义边界框相交。
* 线段和交点的坐标系均为骨架内坐标系。
* 自定义边界框需要在 DragonBones Pro 中自定义。
* @param xA - 线段起点的水平坐标。
* @param yA - 线段起点的垂直坐标。
* @param xB - 线段终点的水平坐标。
* @param yB - 线段终点的垂直坐标。
* @param intersectionPointA - 线段从起点到终点与边界框相交的第一个交点。 (如果未设置,则不计算交点)
* @param intersectionPointB - 线段从终点到起点与边界框相交的第一个交点。 (如果未设置,则不计算交点)
* @param normalRadians - 交点边界框切线的法线弧度。 [x: 第一个交点切线的法线弧度, y: 第二个交点切线的法线弧度] (如果未设置,则不计算法线)
* @returns 线段从起点到终点相交的第一个自定义边界框的插槽。
* @version DragonBones 5.0
* @language zh_CN
*/
fun intersectsSegment(
xA: Double, yA: Double, xB: Double, yB: Double,
intersectionPointA: Point? = null,
intersectionPointB: Point? = null,
normalRadians: Point? = null
): Slot? {
val isV = xA == xB
var dMin = 0.0
var dMax = 0.0
var intXA = 0.0
var intYA = 0.0
var intXB = 0.0
var intYB = 0.0
var intAN = 0.0
var intBN = 0.0
var intSlotA: Slot? = null
var intSlotB: Slot? = null
for (n in 0 until this._slots.size) {
val slot = this._slots[n]
val intersectionCount = slot.intersectsSegment(xA, yA, xB, yB, intersectionPointA, intersectionPointB, normalRadians)
if (intersectionCount > 0) {
if (intersectionPointA != null || intersectionPointB != null) {
if (intersectionPointA != null) {
var d = if (isV) intersectionPointA.yf - yA else intersectionPointA.xf - xA
if (d < 0.0) {
d = -d
}
if (intSlotA == null || d < dMin) {
dMin = d
intXA = intersectionPointA.xf.toDouble()
intYA = intersectionPointA.yf.toDouble()
intSlotA = slot
if (normalRadians != null) {
intAN = normalRadians.xf.toDouble()
}
}
}
if (intersectionPointB != null) {
var d = intersectionPointB.xf - xA
if (d < 0.0) {
d = -d
}
if (intSlotB == null || d > dMax) {
dMax = d
intXB = intersectionPointB.xf.toDouble()
intYB = intersectionPointB.yf.toDouble()
intSlotB = slot
if (normalRadians != null) {
intBN = normalRadians.yf.toDouble()
}
}
}
}
else {
intSlotA = slot
break
}
}
}
if (intSlotA != null && intersectionPointA != null) {
intersectionPointA.xf = intXA.toFloat()
intersectionPointA.yf = intYA.toFloat()
if (normalRadians != null) {
normalRadians.xf = intAN.toFloat()
}
}
if (intSlotB != null && intersectionPointB != null) {
intersectionPointB.xf = intXB.toFloat()
intersectionPointB.yf = intYB.toFloat()
if (normalRadians != null) {
normalRadians.yf = intBN.toFloat()
}
}
return intSlotA
}
/**
* - Get a specific bone.
* @param name - The bone name.
* @see dragonBones.Bone
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 获取特定的骨骼。
* @param name - 骨骼名称。
* @see dragonBones.Bone
* @version DragonBones 3.0
* @language zh_CN
*/
fun getBone(name: String?): Bone? {
this._bones.fastForEach { bone ->
if (bone.name == name) {
return bone
}
}
return null
}
/**
* - Get a specific bone by the display.
* @param display - The display object.
* @see dragonBones.Bone
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 通过显示对象获取特定的骨骼。
* @param display - 显示对象。
* @see dragonBones.Bone
* @version DragonBones 3.0
* @language zh_CN
*/
fun getBoneByDisplay(display: Any): Bone? {
val slot = this.getSlotByDisplay(display)
return if (slot != null) slot.parent else null
}
/**
* - Get a specific slot.
* @param name - The slot name.
* @see dragonBones.Slot
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 获取特定的插槽。
* @param name - 插槽名称。
* @see dragonBones.Slot
* @version DragonBones 3.0
* @language zh_CN
*/
fun getSlot(name: String?): Slot? {
this._slots.fastForEach { slot ->
if (slot.name == name) {
return slot
}
}
return null
}
/**
* - Get a specific slot by the display.
* @param display - The display object.
* @see dragonBones.Slot
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 通过显示对象获取特定的插槽。
* @param display - 显示对象。
* @see dragonBones.Slot
* @version DragonBones 3.0
* @language zh_CN
*/
fun getSlotByDisplay(display: Any?): Slot? {
if (display != null) {
this._slots.fastForEach { slot ->
if (slot.display == display) {
return slot
}
}
}
return null
}
/**
* - Get all bones.
* @see dragonBones.Bone
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 获取所有的骨骼。
* @see dragonBones.Bone
* @version DragonBones 3.0
* @language zh_CN
*/
fun getBones(): FastArrayList<Bone> {
return this._bones
}
/**
* - Get all slots.
* @see dragonBones.Slot
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 获取所有的插槽。
* @see dragonBones.Slot
* @version DragonBones 3.0
* @language zh_CN
*/
fun getSlots(): FastArrayList<Slot> {
return this._slots
}
/**
* - Whether to flip the armature horizontally.
* @version DragonBones 5.5
* @language en_US
*/
/**
* - 是否将骨架水平翻转。
* @version DragonBones 5.5
* @language zh_CN
*/
var flipX: Boolean get() = this._flipX
set(value) {
if (this._flipX == value) {
return
}
this._flipX = value
this.invalidUpdate()
}
/**
* - Whether to flip the armature vertically.
* @version DragonBones 5.5
* @language en_US
*/
/**
* - 是否将骨架垂直翻转。
* @version DragonBones 5.5
* @language zh_CN
*/
var flipY: Boolean get() = this._flipY
set(value) {
if (this._flipY == value) {
return
}
this._flipY = value
this.invalidUpdate()
}
/**
* - The animation cache frame rate, which turns on the animation cache when the set value is greater than 0.
* There is a certain amount of memory overhead to improve performance by caching animation data in memory.
* The frame rate should not be set too high, usually with the frame rate of the animation is similar and lower than the program running frame rate.
* When the animation cache is turned on, some features will fail, such as the offset property of bone.
* @example
* <pre>
* armature.cacheFrameRate = 24;
* </pre>
* @see dragonBones.DragonBonesData#frameRate
* @see dragonBones.ArmatureData#frameRate
* @version DragonBones 4.5
* @language en_US
*/
/**
* - 动画缓存帧率,当设置的值大于 0 的时,将会开启动画缓存。
* 通过将动画数据缓存在内存中来提高运行性能,会有一定的内存开销。
* 帧率不宜设置的过高,通常跟动画的帧率相当且低于程序运行的帧率。
* 开启动画缓存后,某些功能将会失效,比如骨骼的 offset 属性等。
* @example
* <pre>
* armature.cacheFrameRate = 24;
* </pre>
* @see dragonBones.DragonBonesData#frameRate
* @see dragonBones.ArmatureData#frameRate
* @version DragonBones 4.5
* @language zh_CN
*/
var cacheFrameRate: Int get() = this._armatureData!!.cacheFrameRate
set(value) {
if (this._armatureData!!.cacheFrameRate != value) {
this._armatureData!!.cacheFrames(value)
// Set child armature frameRate.
this._slots.fastForEach { slot ->
val childArmature = slot.childArmature
if (childArmature != null) {
childArmature.cacheFrameRate = value
}
}
}
}
/**
* - The armature name.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 骨架名称。
* @version DragonBones 3.0
* @language zh_CN
*/
val name: String get() = this._armatureData?.name ?: ""
/**
* - The armature data.
* @see dragonBones.ArmatureData
* @version DragonBones 4.5
* @language en_US
*/
/**
* - 骨架数据。
* @see dragonBones.ArmatureData
* @version DragonBones 4.5
* @language zh_CN
*/
val armatureData: ArmatureData get() = this._armatureData!!
/**
* - The animation player.
* @see dragonBones.Animation
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 动画播放器。
* @see dragonBones.Animation
* @version DragonBones 3.0
* @language zh_CN
*/
val animation: Animation get() = this._animation!!
/**
* @pivate
*/
val proxy: IArmatureProxy get() = this._proxy!!
/**
* - The EventDispatcher instance of the armature.
* @version DragonBones 4.5
* @language en_US
*/
/**
* - 该骨架的 EventDispatcher 实例。
* @version DragonBones 4.5
* @language zh_CN
*/
val eventDispatcher: IEventDispatcher get() = this._proxy!!
/**
* - The display container.
* The display of the slot is displayed as the parent.
* Depending on the rendering engine, the type will be different, usually the DisplayObjectContainer type.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 显示容器实例。
* 插槽的显示对象都会以此显示容器为父级。
* 根据渲染引擎的不同,类型会不同,通常是 DisplayObjectContainer 类型。
* @version DragonBones 3.0
* @language zh_CN
*/
val display: Any get() = this._display!!
/**
* @private
*/
var replacedTexture: Any? get() = this._replacedTexture
set (value) {
if (this._replacedTexture != value) {
this._replaceTextureAtlasData?.returnToPool()
this._replaceTextureAtlasData = null
this._replacedTexture = value
this._slots.fastForEach { slot ->
slot.invalidUpdate()
slot.update(-1)
}
}
}
/**
* @inheritDoc
*/
override var clock: WorldClock? get() = this._clock
set(value) {
if (this._clock == value) {
return
}
this._clock?.remove(this)
this._clock = value
this._clock?.add(this)
// Update childArmature clock.
this._slots.fastForEach { slot ->
val childArmature = slot.childArmature
if (childArmature != null) {
childArmature.clock = this._clock
}
}
}
///**
// * - Get the parent slot which the armature belongs to.
// * @see dragonBones.Slot
// * @version DragonBones 4.5
// * @language en_US
// */
///**
// * - 该骨架所属的父插槽。
// * @see dragonBones.Slot
// * @version DragonBones 4.5
// * @language zh_CN
// */
//val parent: Slot? get() {
// return this._parent
//}
//fun getDisplay(): Any {
// return this._display
//}
}
| apache-2.0 | 8610e91f59f4128d51c40a6e840c4a5a | 24.353579 | 245 | 0.648956 | 3.172208 | false | false | false | false |
apixandru/intellij-community | python/src/com/jetbrains/python/run/PyVirtualEnvReader.kt | 9 | 4795 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.run
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.EnvironmentUtil
import com.intellij.util.LineSeparator
import com.jetbrains.python.sdk.PythonSdkType
import java.io.File
/**
* @author traff
*/
class PyVirtualEnvReader(val virtualEnvSdkPath: String) : EnvironmentUtil.ShellEnvReader() {
private val LOG = Logger.getInstance("#com.jetbrains.python.run.PyVirtualEnvReader")
companion object {
val virtualEnvVars = listOf("PATH", "PS1", "VIRTUAL_ENV", "PYTHONHOME", "PROMPT", "_OLD_VIRTUAL_PROMPT", "_OLD_VIRTUAL_PYTHONHOME",
"_OLD_VIRTUAL_PATH")
}
// in case of Conda we need to pass an argument to an activate script that tells which exactly environment to activate
val activate: Pair<String, String?>? = findActivateScript(virtualEnvSdkPath, shell)
override fun getShell(): String? {
if (File("/bin/bash").exists()) {
return "/bin/bash";
}
else
if (File("/bin/sh").exists()) {
return "/bin/sh";
}
else {
return super.getShell();
}
}
override fun readShellEnv(): MutableMap<String, String> {
if (SystemInfo.isUnix) {
return super.readShellEnv()
}
else {
if (activate != null) {
return readVirtualEnvOnWindows(activate);
}
else {
LOG.error("Can't find activate script for $virtualEnvSdkPath")
return mutableMapOf();
}
}
}
override fun dumpProcessEnvToFile(command: MutableList<String>, envFile: File, lineSeparator: String?): MutableMap<String, String> {
// pass shell environment for correct virtualenv environment setup (virtualenv expects to be executed from the terminal)
return runProcessAndReadEnvs(command, null, EnvironmentUtil.getEnvironmentMap(), envFile, lineSeparator)
}
private fun readVirtualEnvOnWindows(activate: Pair<String, String?>): MutableMap<String, String> {
val activateFile = FileUtil.createTempFile("pycharm-virualenv-activate.", ".bat", false)
val envFile = FileUtil.createTempFile("pycharm-virualenv-envs.", ".tmp", false)
try {
FileUtil.copy(File(activate.first), activateFile);
FileUtil.appendToFile(activateFile, "\n\nset >" + envFile.absoluteFile)
val command = if (activate.second != null) listOf<String>(activateFile.path, activate.second!!)
else listOf<String>(activateFile.path)
return runProcessAndReadEnvs(command, envFile, LineSeparator.CRLF.separatorString)
}
finally {
FileUtil.delete(activateFile)
FileUtil.delete(envFile)
}
}
override fun getShellProcessCommand(): MutableList<String> {
val shellPath = shell
if (shellPath == null || !File(shellPath).canExecute()) {
throw Exception("shell:" + shellPath)
}
return if (activate != null) {
val activateArg = if (activate.second != null) "'${activate.first}' '${activate.second}'" else "'${activate.first}'"
mutableListOf(shellPath, "-c", ". $activateArg")
}
else super.getShellProcessCommand()
}
}
fun findActivateScript(path: String?, shellPath: String?): Pair<String, String?>? {
val shellName = if (shellPath != null) File(shellPath).name else null
val activate = if (SystemInfo.isWindows) findActivateOnWindows(path)
else if (shellName == "fish" || shellName == "csh") File(File(path).parentFile, "activate." + shellName)
else File(File(path).parentFile, "activate")
return if (activate != null && activate.exists()) {
val sdk = PythonSdkType.findSdkByPath(path)
if (sdk != null && PythonSdkType.isCondaVirtualEnv(sdk)) Pair(activate.absolutePath, condaEnvFolder(path))
else Pair(activate.absolutePath, null)
}
else null
}
private fun condaEnvFolder(path: String?) = if (SystemInfo.isWindows) File(path).parent else File(path).parentFile.parent
private fun findActivateOnWindows(path: String?): File? {
for (location in arrayListOf("activate.bat", "Scripts/activate.bat")) {
val file = File(File(path).parentFile, location)
if (file.exists()) {
return file
}
}
return null
} | apache-2.0 | e1ec9fa783caaafdf0ccda644f6f1376 | 34.525926 | 135 | 0.69781 | 4.098291 | false | false | false | false |
chromeos/vulkanphotobooth | app/src/main/java/dev/hadrosaur/vulkanphotobooth/cameracontroller/Camera2Controller.kt | 1 | 12131 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.hadrosaur.vulkanphotobooth.cameracontroller
import android.content.Context
import android.hardware.camera2.*
import android.os.Handler
import android.os.Looper
import android.view.Surface
import dev.hadrosaur.vulkanphotobooth.*
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.vulkanViewModel
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.logd
import java.lang.Thread.sleep
import java.util.*
/** State of the camera during an image capture - */
internal enum class CameraState {
UNINITIALIZED,
PREVIEW_RUNNING,
WAITING_FOCUS_LOCK,
WAITING_EXPOSURE_LOCK,
IMAGE_REQUESTED
}
/**
* Opens the camera using the Camera 2 API. The open call will complete
* in the DeviceStateCallback asynchronously.
*/
fun camera2OpenCamera(activity: MainActivity, params: CameraParams?) {
if (null == params)
return
// The camera has not finished closing, possibly due to an orientation/resize event
// Schedule the camera open in the future to allow for the camera to close properly
if (params.isClosing) {
Handler(Looper.getMainLooper()).postDelayed({
camera2OpenCamera(activity, params)
}, 20)
return
}
if (params.isPreviewing) {
return
}
// If camera is already opened (after onPause/rotation), just start a preview session
if (params.isOpen) {
camera2StartPreview(activity, params);
return
}
// Don't double up open request
if (params.cameraOpenRequested) {
return
} else {
params.cameraOpenRequested = true
}
val manager = activity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
logd("About to open camera: " + params.id)
// Might be a new session, update callbacks to make sure they match the needed config
params.camera2DeviceStateCallback =
Camera2DeviceStateCallback(params, activity)
params.camera2CaptureSessionCallback =
Camera2CaptureSessionCallback(activity, params)
manager.openCamera(params.id, params.camera2DeviceStateCallback!!, params.backgroundHandler)
} catch (e: CameraAccessException) {
logd("openCamera CameraAccessException: " + params.id)
e.printStackTrace()
} catch (e: SecurityException) {
logd("openCamera SecurityException: " + params.id)
e.printStackTrace()
}
}
/**
* Setup the camera preview session and output surface.
*/
fun camera2StartPreview(activity: MainActivity, params: CameraParams) {
// If camera is not open, return
if (!params.isOpen || params.isClosing) {
return
}
// If preview is already showing, no need to recreate it
if (params.isPreviewing) {
return
}
// Don't double up preview request
if (params.previewStartRequested) {
return
} else {
params.previewStartRequested = true;
}
try {
val surface = params.previewSurfaceView?.holder?.surface
if (null == surface)
return
params.previewImageReaderSurface = getImagePreviewSurface()
if (null == params.previewImageReaderSurface) {
logd("Preview imagereader surface is NULL, not starting preview")
return
}
params.captureRequestBuilder =
params.device?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
// params.captureRequestBuilder =
// params.device?.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
params.captureRequestBuilder?.addTarget(params.previewImageReaderSurface!!)
logd("In camera2StartPreview. Added request.")
logd("Preview SurfaceView width: " + params.previewSurfaceView?.width + ", height: " + params.previewSurfaceView?.height)
// Now try to hook up the native rendering/filtering engine.
if (params.previewImageReaderSurface != null) {
if (activity.isChromebox()) {
// connectPreviewToOutput(surface, vulkanViewModel.getFilterParams().rotation, 1920, 1080)
connectPreviewToOutput(surface, vulkanViewModel.getFilterParams().rotation, 960, 540)
// connectPreviewToOutput(surface, vulkanViewModel.getFilterParams().rotation, 1200, 675)
// connectPreviewToOutput(surface, vulkanViewModel.getFilterParams().rotation, 960, 540)
} else {
connectPreviewToOutput(surface, vulkanViewModel.getFilterParams().rotation, 0,0)
}
}
params.device?.createCaptureSession(
Arrays.asList(params.previewImageReaderSurface),
Camera2PreviewSessionStateCallback(activity, params), null)
} catch (e: CameraAccessException) {
MainActivity.logd("camera2StartPreview CameraAccessException: " + e.message)
e.printStackTrace()
} catch (e: IllegalStateException) {
MainActivity.logd("camera2StartPreview IllegalStateException: " + e.message)
e.printStackTrace()
}
}
/**
* Set up for a still capture.
*/
fun initializeStillCapture(activity: MainActivity, params: CameraParams) {
logd("TakePicture: capture start.")
if (!params.isOpen) {
return
}
lockFocus(activity, params)
}
/**
* Initiate the auto-focus routine if required.
*/
fun lockFocus(activity: MainActivity, params: CameraParams) {
logd("In lockFocus.")
if (!params.isOpen) {
return
}
try {
if (null != params.device) {
setAutoFlash(params, params.captureRequestBuilder)
// If this lens can focus, we need to start a focus search and wait for focus lock
if (params.hasAF &&
FocusMode.AUTO == params.focusMode) {
logd("In lockFocus. About to request focus lock and call capture.")
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_AUTO)
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_TRIGGER,
CameraMetadata.CONTROL_AF_TRIGGER_CANCEL)
params.camera2CaptureSession?.capture(params.captureRequestBuilder?.build()!!,
params.camera2CaptureSessionCallback, params.backgroundHandler)
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_AUTO)
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_TRIGGER,
CameraMetadata.CONTROL_AF_TRIGGER_START)
params.state = CameraState.WAITING_FOCUS_LOCK
params.autoFocusStuckCounter = 0
params.camera2CaptureSession?.capture(params.captureRequestBuilder?.build()!!,
params.camera2CaptureSessionCallback, params.backgroundHandler)
} else {
// If no auto-focus requested, go ahead to the still capture routine
logd("In lockFocus. Fixed focus or continuous focus, calling captureStillPicture.")
params.state = CameraState.IMAGE_REQUESTED
captureStillPicture(activity, params)
}
}
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
/**
* Request pre-capture auto-exposure (AE) metering
*/
fun runPrecaptureSequence(params: CameraParams) {
if (!params.isOpen) {
return
}
try {
if (null != params.device) {
setAutoFlash(params, params.captureRequestBuilder)
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START)
params.state = CameraState.WAITING_EXPOSURE_LOCK
params.camera2CaptureSession?.capture(params.captureRequestBuilder?.build()!!,
params.camera2CaptureSessionCallback, params.backgroundHandler)
}
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
/**
* Make a still capture request. At this point, AF and AE should be converged or unnecessary.
*/
fun captureStillPicture(activity: MainActivity, params: CameraParams) {
if (!params.isOpen) {
return
}
try {
if (null != params.device) {
params.captureRequestBuilder =
params.device?.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
when (params.focusMode) {
FocusMode.CONTINUOUS -> {
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
}
FocusMode.AUTO -> {
params.captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_TRIGGER,
CameraMetadata.CONTROL_AF_TRIGGER_IDLE)
}
FocusMode.FIXED -> {
}
}
// Disable HDR+ for Pixel devices
// This is a hack, Pixel devices do not have Sepia mode, but this forces HDR+ off
if (android.os.Build.MANUFACTURER.equals("Google")) {
// params.captureRequestBuilder?.set(CaptureRequest.CONTROL_EFFECT_MODE,
// CaptureRequest.CONTROL_EFFECT_MODE_SEPIA)
}
// Orientation
val rotation = activity.windowManager.defaultDisplay.rotation
val capturedImageRotation = getOrientation(params, rotation)
params.captureRequestBuilder
?.set(CaptureRequest.JPEG_ORIENTATION, capturedImageRotation)
// Flash
setAutoFlash(params, params.captureRequestBuilder)
val captureCallback =
Camera2CaptureCallback(activity, params)
params.camera2CaptureSession?.capture(params.captureRequestBuilder?.build()!!,
captureCallback, params.backgroundHandler)
}
} catch (e: CameraAccessException) {
e.printStackTrace()
} catch (e: IllegalStateException) {
logd("captureStillPicture IllegalStateException, aborting: " + e.message)
}
}
/**
* Stop preview stream and clean-up native ImageReader/processing
*/
fun camera2StopPreview(params: CameraParams) {
if (params.isPreviewing && !params.previewStopRequested) {
logd("camera2StopPreview")
params.previewStopRequested = true
params.camera2CaptureSession?.close()
}
}
/**
* Close preview stream and camera device.
*/
fun camera2CloseCamera(params: CameraParams?) {
if (params == null)
return
logd("closePreviewAndCamera: id: ${params.id}, isPreviewing: ${params.isPreviewing}, isStopRequested: ${params.previewStopRequested}")
if (params.isPreviewing && !params.previewStopRequested) {
params.cameraCloseRequested = true
params.previewStopRequested = true
params.camera2CaptureSession?.close()
} else {
params.isClosing = true;
params.device?.close()
}
}
/**
* An abort request has been received. Abandon everything
*/
fun camera2Abort(activity: MainActivity, params: CameraParams) {
params.camera2CaptureSession?.abortCaptures()
activity.stopBackgroundThread(params)
}
external fun getImagePreviewSurface() : Surface
external fun connectPreviewToOutput(outputSurface: Surface, rotation: Int, rendererCopyWidth: Int, rendererCopyHeight: Int): Boolean
external fun disconnectPreviewFromOutput(): Boolean | apache-2.0 | 73337739871063eb140e65b726581d32 | 35 | 139 | 0.662023 | 4.731279 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/fx/ComponentActorController.kt | 1 | 8403 | package org.pixelndice.table.pixelclient.fx
import com.google.common.eventbus.Subscribe
import javafx.application.Platform
import javafx.collections.FXCollections
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.*
import javafx.scene.control.cell.PropertyValueFactory
import javafx.scene.image.ImageView
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.ApplicationBus
import org.pixelndice.table.pixelclient.ds.resource.Actor
import org.pixelndice.table.pixelclient.isGm
import org.pixelndice.table.pixelclient.myAccount
private val logger = LogManager.getLogger(ComponentActorController::class.java)
class ComponentActorController {
@FXML
private lateinit var tabPane: TabPane
@FXML
private lateinit var tabInfo: Tab
@FXML
private lateinit var tabString: Tab
@FXML
private lateinit var tabInt: Tab
@FXML
private lateinit var tabBar: Tab
@FXML
private lateinit var accessTab: Tab
@FXML
private lateinit var accessTabController: ComponentAccessController
@FXML
private lateinit var nameLabel: Label
@FXML
private lateinit var imageView: ImageView
@FXML
private lateinit var tokenView: ImageView
@FXML
private lateinit var descriptionTextArea: TextArea
@FXML
private lateinit var gmNoteLabel: Label
@FXML
private lateinit var gmNoteTextArea: TextArea
@FXML
private lateinit var stringTableView: TableView<Pair<String,String>>
@FXML
private lateinit var stringKeyTableColumn: TableColumn<Pair<String,String>,String>
@FXML
private lateinit var stringValueTableColumn: TableColumn<Pair<String,String>,String>
@FXML
private lateinit var integerTableView: TableView<Pair<String,Int>>
@FXML
private lateinit var integerKeyTableColumn: TableColumn<Pair<String,Int>,String>
@FXML
private lateinit var integerValueTableColumn: TableColumn<Pair<String,Int>,Int>
@FXML
private lateinit var barVBox: VBox
private var actor: Actor = Actor()
/**
* ApplicationBus event handler
*/
val handler = Handler()
init {
ApplicationBus.register(handler)
}
fun initialize() {
// string hash table
stringTableView.isEditable = false
stringKeyTableColumn.prefWidthProperty().bind(stringTableView.widthProperty().multiply(0.25))
stringValueTableColumn.prefWidthProperty().bind(stringTableView.widthProperty().multiply(0.5))
stringKeyTableColumn.cellValueFactory = PropertyValueFactory<Pair<String,String>,String>("first")
stringValueTableColumn.cellValueFactory = PropertyValueFactory<Pair<String,String>,String>("second")
// integer hash table
integerTableView.isEditable = true
integerKeyTableColumn.prefWidthProperty().bind(integerTableView.widthProperty().multiply(0.25))
integerValueTableColumn.prefWidthProperty().bind(integerTableView.widthProperty().multiply(0.25))
integerKeyTableColumn.cellValueFactory = PropertyValueFactory<Pair<String,Int>,String>("first")
integerValueTableColumn.cellValueFactory = PropertyValueFactory<Pair<String,Int>,Int>("second")
// tab pane
tabPane.selectionModel.selectedItemProperty().addListener { _, _, tab2 ->
try {
when (tab2) {
tabInfo -> {
actor.tab = Actor.TabShowing.INFO
}
tabString -> {
actor.tab = Actor.TabShowing.STRING_ATTRIBUTES
}
tabInt -> {
actor.tab = Actor.TabShowing.INTEGER_ATTRIBUTES
}
tabBar -> {
actor.tab = Actor.TabShowing.BAR
}
accessTab -> {
actor.tab = Actor.TabShowing.ACCESS
}
}
}catch (except: kotlin.UninitializedPropertyAccessException){
logger.debug("Actor is not set up here. Nothing to do")
}
}
}
private fun refreshBarVBox(){
Platform.runLater {
barVBox.children.clear()
actor.barList.forEach { bar ->
val hbox = HBox()
hbox.alignment = Pos.CENTER_LEFT
hbox.padding = Insets(7.0,7.0,7.0,7.0)
val colorPicker = ColorPicker(bar.color)
colorPicker.isDisable = true
colorPicker.padding = Insets(7.0,7.0,7.0,7.0)
val barLabel = Label(bar.toString())
barLabel.padding = Insets(7.0,7.0,7.0,7.0)
hbox.children.addAll(colorPicker, barLabel)
barVBox.children.add(hbox)
}
}
}
fun view(gameResource: Actor){
actor = gameResource
Platform.runLater {
when(gameResource.tab){
Actor.TabShowing.INFO -> {tabPane.selectionModel.select(tabInfo)}
Actor.TabShowing.STRING_ATTRIBUTES -> {tabPane.selectionModel.select(tabString)}
Actor.TabShowing.INTEGER_ATTRIBUTES -> {tabPane.selectionModel.select(tabInt)}
Actor.TabShowing.BAR -> {tabPane.selectionModel.select(tabBar)}
Actor.TabShowing.ACCESS -> {tabPane.selectionModel.select(accessTab)}
}
if( isGm() || gameResource.isVisible(myAccount, true)) {
tabPane.isManaged = true
tabPane.isVisible = true
nameLabel.text = actor.name
imageView.image = null
actor.imageFile?.let {
imageView.image = it.toImage()
}
tokenView.image = null
actor.tokenFile?.let {
tokenView.image = it.toImage()
tokenView.fitWidth = PixelCanvas.GRID_WIDTH
tokenView.fitHeight = PixelCanvas.GRID_HEIGHT
tokenView.isPreserveRatio = true
tokenView.isSmooth = true
}
descriptionTextArea.text = actor.description
gmNoteTextArea.text = actor.gmNote
accessTabController.view(actor)
if (!isGm()) {
gmNoteLabel.isVisible = false
gmNoteLabel.isManaged = false
gmNoteTextArea.isVisible = false
gmNoteTextArea.isManaged = false
}
// string hash table
createObservableDataString()
// integer hash table
createObservableDataInteger()
refreshBarVBox()
if (!(isGm() || actor.isEditable(myAccount, true))) {
tabPane.tabs.remove(tabString)
tabPane.tabs.remove(tabInt)
tabPane.tabs.remove(tabBar)
}
}else{
tabPane.isVisible = false
tabPane.isManaged = false
}
}
}
@FXML
fun addImageOnAction(@Suppress("UNUSED_PARAMETER") event: ActionEvent){
ApplicationBus.post(ApplicationBus.RequestImage(this.actor))
}
@FXML
fun addTokenOnAction(@Suppress("UNUSED_PARAMETER") event: ActionEvent){
ApplicationBus.post(ApplicationBus.RequestTokenImage(this.actor))
}
private fun createObservableDataString(){
val data = FXCollections.observableArrayList<Pair<String,String>>()
actor.stringValues.forEach{ key,value -> data.add( Pair(key,value) ) }
stringTableView.items = data
}
private fun createObservableDataInteger(){
val data = FXCollections.observableArrayList<Pair<String,Int>>()
actor.integerValues.forEach { key, value -> data.add(Pair(key,value)) }
integerTableView.items = data
}
/**
* ApplicationBus event handler class
*/
inner class Handler{
@Subscribe
fun handleUpdateActorFromLobby(event: ApplicationBus.UpdateActorFromLobby){
if( actor.id == event.actorId ){
view(actor)
}
}
}
} | bsd-2-clause | eef104f3d6e0342b847467f795288325 | 30.358209 | 108 | 0.612281 | 4.922671 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/style/TextDecoration.kt | 3 | 3441 | /*
* 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.ui.text.style
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.text.fastFold
import androidx.compose.ui.text.fastJoinToString
/**
* Defines a horizontal line to be drawn on the text.
*/
@Immutable
class TextDecoration internal constructor(val mask: Int) {
companion object {
@Stable
val None: TextDecoration = TextDecoration(0x0)
/**
* Draws a horizontal line below the text.
*
* @sample androidx.compose.ui.text.samples.TextDecorationUnderlineSample
*/
@Stable
val Underline: TextDecoration = TextDecoration(0x1)
/**
* Draws a horizontal line over the text.
*
* @sample androidx.compose.ui.text.samples.TextDecorationLineThroughSample
*/
@Stable
val LineThrough: TextDecoration = TextDecoration(0x2)
/**
* Creates a decoration that includes all the given decorations.
*
* @sample androidx.compose.ui.text.samples.TextDecorationCombinedSample
*
* @param decorations The decorations to be added
*/
fun combine(decorations: List<TextDecoration>): TextDecoration {
val mask = decorations.fastFold(0) { acc, decoration ->
acc or decoration.mask
}
return TextDecoration(mask)
}
}
/**
* Creates a decoration that includes both of the TextDecorations.
*
* @sample androidx.compose.ui.text.samples.TextDecorationCombinedSample
*/
operator fun plus(decoration: TextDecoration): TextDecoration {
return TextDecoration(this.mask or decoration.mask)
}
/**
* Check whether this [TextDecoration] contains the given decoration.
*
* @param other The [TextDecoration] to be checked.
*/
operator fun contains(other: TextDecoration): Boolean {
return (mask or other.mask) == mask
}
override fun toString(): String {
if (mask == 0) {
return "TextDecoration.None"
}
val values: MutableList<String> = mutableListOf()
if ((mask and Underline.mask) != 0) {
values.add("Underline")
}
if ((mask and LineThrough.mask) != 0) {
values.add("LineThrough")
}
if ((values.size == 1)) {
return "TextDecoration.${values[0]}"
}
return "TextDecoration[${values.fastJoinToString(separator = ", ")}]"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TextDecoration) return false
if (mask != other.mask) return false
return true
}
override fun hashCode(): Int {
return mask
}
}
| apache-2.0 | 572660cb7069f1571653ed17ca8b70b4 | 30.281818 | 83 | 0.632956 | 4.656292 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-foundation/src/commonMain/kotlin/androidx/wear/compose/foundation/CurvedTextStyle.kt | 3 | 7814 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.wear.compose.foundation
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.text.TextStyle
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.unit.TextUnit
import androidx.compose.ui.unit.isUnspecified
import androidx.compose.ui.unit.sp
/** The default values to use if they are not specified. */
internal val DefaultCurvedTextStyles = CurvedTextStyle(
color = Color.Black,
fontSize = 14.sp,
background = Color.Transparent,
fontWeight = FontWeight.Normal,
fontStyle = FontStyle.Normal,
fontSynthesis = FontSynthesis.All
)
/**
* Styling configuration for a curved text.
*
* @sample androidx.wear.compose.foundation.samples.CurvedAndNormalText
*
* @param background The background color for the text.
* @param color The text color.
* @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This
* may be [TextUnit.Unspecified] for inheriting from another [CurvedTextStyle].
* @param fontFamily The font family to be used when rendering the text.
* @param fontWeight The thickness of the glyphs, in a range of [1, 1000]. see [FontWeight]
* @param fontStyle The typeface variant to use when drawing the letters (e.g. italic).
* @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight
* or style cannot be found in the provided font family.
*/
class CurvedTextStyle(
val background: Color = Color.Unspecified,
val color: Color = Color.Unspecified,
val fontSize: TextUnit = TextUnit.Unspecified,
val fontFamily: FontFamily? = null,
val fontWeight: FontWeight? = null,
val fontStyle: FontStyle? = null,
val fontSynthesis: FontSynthesis? = null
) {
/**
* Styling configuration for a curved text.
*
* @sample androidx.wear.compose.foundation.samples.CurvedAndNormalText
*
* @param background The background color for the text.
* @param color The text color.
* @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This
* may be [TextUnit.Unspecified] for inheriting from another [CurvedTextStyle].
*/
@Deprecated("This overload is provided for backwards compatibility with Compose for " +
"Wear OS 1.0. A newer overload is available with additional font parameters.",
level = DeprecationLevel.HIDDEN)
constructor(
background: Color = Color.Unspecified,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified
) : this(background, color, fontSize, null)
/**
* Create a curved text style from the given text style.
*
* Note that not all parameters in the text style will be used, only [TextStyle.color],
* [TextStyle.fontSize], [TextStyle.background], [TextStyle.fontFamily],
* [TextStyle.fontWeight], [TextStyle.fontStyle] and [TextStyle.fontSynthesis].
*/
constructor(style: TextStyle) : this(
style.background,
style.color,
style.fontSize,
style.fontFamily,
style.fontWeight,
style.fontStyle,
style.fontSynthesis
)
/**
* Returns a new curved text style that is a combination of this style and the given
* [other] style.
*
* [other] curved text style's null or inherit properties are replaced with the non-null
* properties of this curved text style. Another way to think of it is that the "missing"
* properties of the [other] style are _filled_ by the properties of this style.
*
* If the given curved text style is null, returns this curved text style.
*/
fun merge(other: CurvedTextStyle? = null): CurvedTextStyle {
if (other == null) return this
return CurvedTextStyle(
color = other.color.takeOrElse { this.color },
fontSize = if (!other.fontSize.isUnspecified) other.fontSize else this.fontSize,
background = other.background.takeOrElse { this.background },
fontFamily = other.fontFamily ?: this.fontFamily,
fontWeight = other.fontWeight ?: this.fontWeight,
fontStyle = other.fontStyle ?: this.fontStyle,
fontSynthesis = other.fontSynthesis ?: this.fontSynthesis,
)
}
/**
* Plus operator overload that applies a [merge].
*/
operator fun plus(other: CurvedTextStyle): CurvedTextStyle = this.merge(other)
@Deprecated("This overload is provided for backwards compatibility with Compose for " +
"Wear OS 1.0. A newer overload is available with additional font parameters.")
fun copy(
background: Color = this.background,
color: Color = this.color,
fontSize: TextUnit = this.fontSize,
): CurvedTextStyle {
return CurvedTextStyle(
background = background,
color = color,
fontSize = fontSize,
fontFamily = this.fontFamily,
fontWeight = this.fontWeight,
fontStyle = this.fontStyle,
fontSynthesis = this.fontSynthesis
)
}
fun copy(
background: Color = this.background,
color: Color = this.color,
fontSize: TextUnit = this.fontSize,
fontFamily: FontFamily? = this.fontFamily,
fontWeight: FontWeight? = this.fontWeight,
fontStyle: FontStyle? = this.fontStyle,
fontSynthesis: FontSynthesis? = this.fontSynthesis
): CurvedTextStyle {
return CurvedTextStyle(
background = background,
color = color,
fontSize = fontSize,
fontFamily = fontFamily,
fontWeight = fontWeight,
fontStyle = fontStyle,
fontSynthesis = fontSynthesis
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is CurvedTextStyle &&
color == other.color &&
fontSize == other.fontSize &&
background == other.background &&
fontFamily == other.fontFamily &&
fontWeight == other.fontWeight &&
fontStyle == other.fontStyle &&
fontSynthesis == other.fontSynthesis
}
override fun hashCode(): Int {
var result = color.hashCode()
result = 31 * result + fontSize.hashCode()
result = 31 * result + background.hashCode()
result = 31 * result + fontFamily.hashCode()
result = 31 * result + fontWeight.hashCode()
result = 31 * result + fontStyle.hashCode()
result = 31 * result + fontSynthesis.hashCode()
return result
}
override fun toString(): String {
return "CurvedTextStyle(" +
"background=$background" +
"color=$color, " +
"fontSize=$fontSize, " +
"fontFamily=$fontFamily, " +
"fontWeight=$fontWeight, " +
"fontStyle=$fontStyle, " +
"fontSynthesis=$fontSynthesis, " +
")"
}
}
| apache-2.0 | 395ebd64a9860f01c97cf86dfdb57276 | 37.683168 | 97 | 0.660993 | 4.712907 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/operations/SyncProfileOperation.kt | 2 | 4480 | /**
* ownCloud Android client application
*
* @author David A. Velasco
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.operations
import android.accounts.Account
import android.accounts.AccountManager
import com.owncloud.android.MainApp.Companion.appContext
import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase
import com.owncloud.android.domain.user.usecases.GetUserAvatarAsyncUseCase
import com.owncloud.android.domain.user.usecases.GetUserInfoAsyncUseCase
import com.owncloud.android.domain.user.usecases.RefreshUserQuotaFromServerAsyncUseCase
import com.owncloud.android.lib.common.accounts.AccountUtils
import com.owncloud.android.presentation.manager.AvatarManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import timber.log.Timber
/**
* Performs the Profile synchronization for account step by step.
*
* First: Synchronize user info
* Second: Synchronize user quota
* Third: Synchronize user avatar
*
* If one step fails, next one is not performed since it may fail too.
*/
class SyncProfileOperation(
private val account: Account
) : KoinComponent {
fun syncUserProfile() {
try {
CoroutineScope(Dispatchers.IO).launch {
val getUserInfoAsyncUseCase: GetUserInfoAsyncUseCase by inject()
val userInfoResult = getUserInfoAsyncUseCase.execute(GetUserInfoAsyncUseCase.Params(account.name))
userInfoResult.getDataOrNull()?.let { userInfo ->
Timber.d("User info synchronized for account ${account.name}")
AccountManager.get(appContext).run {
setUserData(account, AccountUtils.Constants.KEY_DISPLAY_NAME, userInfo.displayName)
setUserData(account, AccountUtils.Constants.KEY_ID, userInfo.id)
}
val refreshUserQuotaFromServerAsyncUseCase: RefreshUserQuotaFromServerAsyncUseCase by inject()
val userQuotaResult =
refreshUserQuotaFromServerAsyncUseCase.execute(
RefreshUserQuotaFromServerAsyncUseCase.Params(
account.name
)
)
userQuotaResult.getDataOrNull()?.let {
Timber.d("User quota synchronized for account ${account.name}")
val getStoredCapabilitiesUseCase: GetStoredCapabilitiesUseCase by inject()
val storedCapabilities = getStoredCapabilitiesUseCase.execute(GetStoredCapabilitiesUseCase.Params(account.name))
val shouldFetchAvatar = storedCapabilities?.isFetchingAvatarAllowed() ?: true
if (shouldFetchAvatar) {
val getUserAvatarAsyncUseCase: GetUserAvatarAsyncUseCase by inject()
val userAvatarResult = getUserAvatarAsyncUseCase.execute(GetUserAvatarAsyncUseCase.Params(account.name))
AvatarManager().handleAvatarUseCaseResult(account, userAvatarResult)
if (userAvatarResult.isSuccess) {
Timber.d("Avatar synchronized for account ${account.name}")
}
} else {
Timber.d("Avatar for this account: ${account.name} won't be synced due to capabilities ")
}
}
} ?: Timber.d("User profile was not synchronized")
}
} catch (e: Exception) {
Timber.e(e, "Exception while getting user profile")
}
}
}
| gpl-2.0 | 9d7f56d2a4ba85ce3e30c3675a2fbc17 | 46.147368 | 136 | 0.659522 | 5.202091 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-foundation/src/androidMain/kotlin/androidx/wear/compose/foundation/CurvedTextDelegate.android.kt | 3 | 7900 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.wear.compose.foundation
import android.graphics.Typeface
import android.text.StaticLayout
import android.text.TextPaint
import android.text.TextUtils
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.isSpecified
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalFontFamilyResolver
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.font.resolveAsTypeface
import androidx.compose.ui.text.style.TextOverflow
import kotlin.math.roundToInt
/**
* Used to cache computations and objects with expensive construction (Android's Paint & Path)
*/
internal actual class CurvedTextDelegate {
private var text: String = ""
private var clockwise: Boolean = true
private var fontSizePx: Float = 0f
actual var textWidth by mutableStateOf(0f)
actual var textHeight by mutableStateOf(0f)
actual var baseLinePosition = 0f
private var typeFace: State<Typeface?> = mutableStateOf(null)
private val paint = android.graphics.Paint().apply { isAntiAlias = true }
private val backgroundPath = android.graphics.Path()
private val textPath = android.graphics.Path()
var lastLayoutInfo: CurvedLayoutInfo? = null
actual fun updateIfNeeded(
text: String,
clockwise: Boolean,
fontSizePx: Float
) {
if (
text != this.text ||
clockwise != this.clockwise ||
fontSizePx != this.fontSizePx
) {
this.text = text
this.clockwise = clockwise
this.fontSizePx = fontSizePx
paint.textSize = fontSizePx
updateMeasures()
lastLayoutInfo = null // Ensure paths are recomputed
}
}
@Composable
actual fun UpdateFontIfNeeded(
fontFamily: FontFamily?,
fontWeight: FontWeight?,
fontStyle: FontStyle?,
fontSynthesis: FontSynthesis?
) {
val fontFamilyResolver = LocalFontFamilyResolver.current
typeFace = remember(fontFamily, fontWeight, fontStyle, fontSynthesis, fontFamilyResolver) {
derivedStateOf {
fontFamilyResolver.resolveAsTypeface(
fontFamily,
fontWeight ?: FontWeight.Normal,
fontStyle ?: FontStyle.Normal,
fontSynthesis ?: FontSynthesis.All
).value
}
}
updateTypeFace()
}
private fun updateMeasures() {
val rect = android.graphics.Rect()
paint.getTextBounds(text, 0, text.length, rect)
textWidth = rect.width().toFloat()
textHeight = -paint.fontMetrics.top + paint.fontMetrics.bottom
baseLinePosition =
if (clockwise) -paint.fontMetrics.top else paint.fontMetrics.bottom
}
private fun updateTypeFace() {
val currentTypeface = typeFace.value
if (currentTypeface != paint.typeface) {
paint.typeface = currentTypeface
updateMeasures()
lastLayoutInfo = null // Ensure paths are recomputed
}
}
private fun updatePathsIfNeeded(layoutInfo: CurvedLayoutInfo) {
if (layoutInfo != lastLayoutInfo) {
lastLayoutInfo = layoutInfo
with(layoutInfo) {
val clockwiseFactor = if (clockwise) 1f else -1f
val sweepDegree = sweepRadians.toDegrees().coerceAtMost(360f)
val centerX = centerOffset.x
val centerY = centerOffset.y
// TODO: move background drawing to a CurvedModifier
backgroundPath.reset()
backgroundPath.arcTo(
centerX - outerRadius,
centerY - outerRadius,
centerX + outerRadius,
centerY + outerRadius,
startAngleRadians.toDegrees(),
sweepDegree, false
)
backgroundPath.arcTo(
centerX - innerRadius,
centerY - innerRadius,
centerX + innerRadius,
centerY + innerRadius,
startAngleRadians.toDegrees() + sweepDegree,
-sweepDegree, false
)
backgroundPath.close()
textPath.reset()
textPath.addArc(
centerX - measureRadius,
centerY - measureRadius,
centerX + measureRadius,
centerY + measureRadius,
startAngleRadians.toDegrees() +
(if (clockwise) 0f else sweepDegree),
clockwiseFactor * sweepDegree
)
}
}
}
actual fun DrawScope.doDraw(
layoutInfo: CurvedLayoutInfo,
parentSweepRadians: Float,
overflow: TextOverflow,
color: Color,
background: Color
) {
updateTypeFace()
updatePathsIfNeeded(layoutInfo)
drawIntoCanvas { canvas ->
if (background.isSpecified && background != Color.Transparent) {
paint.color = background.toArgb()
canvas.nativeCanvas.drawPath(backgroundPath, paint)
}
paint.color = color.toArgb()
val actualText = if (
// Float arithmetic can make the parentSweepRadians slightly smaller
layoutInfo.sweepRadians <= parentSweepRadians + 0.001f ||
overflow == TextOverflow.Visible
) {
text
} else {
ellipsize(
text, TextPaint(paint), overflow == TextOverflow.Ellipsis,
(parentSweepRadians * layoutInfo.measureRadius).roundToInt()
)
}
canvas.nativeCanvas.drawTextOnPath(actualText, textPath, 0f, 0f, paint)
}
}
private fun ellipsize(
text: String,
paint: TextPaint,
addEllipsis: Boolean,
ellipsizedWidth: Int,
): String {
if (addEllipsis) {
return TextUtils.ellipsize(
text,
paint,
ellipsizedWidth.toFloat(),
TextUtils.TruncateAt.END
).toString()
}
val layout = StaticLayout.Builder
.obtain(text, 0, text.length, paint, ellipsizedWidth)
.setEllipsize(null)
.setMaxLines(1)
.build()
// Cut text that it's too big when in TextOverFlow.Clip mode.
return text.substring(0, layout.getLineEnd(0))
}
}
| apache-2.0 | cb0374b298cf702d666b603819dfc08a | 33.955752 | 99 | 0.613797 | 5.245684 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/Equipment.kt | 2 | 999 | package com.habitrpg.android.habitica.models.inventory
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.BaseMainObject
import io.realm.RealmModel
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Equipment : RealmObject(), BaseMainObject {
var value: Double = 0.toDouble()
var type: String? = ""
@PrimaryKey
var key: String? = ""
var klass: String = ""
var specialClass: String = ""
var index: String = ""
var text: String = ""
var notes: String = ""
var con: Int = 0
var str: Int = 0
var per: Int = 0
@SerializedName("int")
var _int: Int = 0
var owned: Boolean? = null
var twoHanded = false
var mystery = ""
var gearSet = ""
override val realmClass: Class<out RealmModel>
get() = Equipment::class.java
override val primaryIdentifier: String?
get() = key
override val primaryIdentifierName: String
get() = "key"
}
| gpl-3.0 | f31f8feb2a7c491de987819b8ed8da9f | 26.75 | 58 | 0.65966 | 3.996 | false | false | false | false |
nrizzio/Signal-Android | sms-exporter/app/src/main/java/org/signal/smsexporter/app/BitmapGenerator.kt | 1 | 817 | package org.signal.smsexporter.app
import android.graphics.Bitmap
import android.graphics.Color
import androidx.core.graphics.applyCanvas
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.Random
object BitmapGenerator {
private val colors = listOf(
Color.BLACK,
Color.BLUE,
Color.GRAY,
Color.GREEN,
Color.RED,
Color.CYAN
)
fun getStream(): InputStream {
val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
bitmap.applyCanvas {
val random = Random()
drawColor(colors[random.nextInt(colors.size - 1)])
}
val out = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)
val data = out.toByteArray()
return ByteArrayInputStream(data)
}
}
| gpl-3.0 | 9bf9a63ce69151e23bb3227a9034a939 | 22.342857 | 71 | 0.72705 | 4.085 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/SqlCipherErrorHandler.kt | 2 | 6464 | package org.thoughtcrime.securesms.database
import android.content.Context
import net.zetetic.database.DatabaseErrorHandler
import net.zetetic.database.sqlcipher.SQLiteConnection
import net.zetetic.database.sqlcipher.SQLiteDatabase
import net.zetetic.database.sqlcipher.SQLiteDatabaseHook
import org.signal.core.util.CursorUtil
import org.signal.core.util.ExceptionUtil
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.crypto.DatabaseSecretProvider
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference
/**
* The default error handler wipes the file. This one instead prints some diagnostics and then crashes so the original corrupt file isn't lost.
*/
class SqlCipherErrorHandler(private val databaseName: String) : DatabaseErrorHandler {
override fun onCorruption(db: SQLiteDatabase) {
val output = StringBuilder()
output.append("Database '$databaseName' corrupted! Going to try to run some diagnostics.\n")
val result: DiagnosticResults = runDiagnostics(ApplicationDependencies.getApplication(), db)
var lines: List<String> = result.logs.split("\n")
lines = listOf("Database '$databaseName' corrupted!. Diagnostics results:\n") + lines
Log.e(TAG, "Database '$databaseName' corrupted!. Diagnostics results:\n ${result.logs}")
if (result is DiagnosticResults.Success) {
if (result.pragma1Passes && result.pragma2Passes) {
throw DatabaseCorruptedError_BothChecksPass(lines)
} else if (!result.pragma1Passes && result.pragma2Passes) {
throw DatabaseCorruptedError_NormalCheckFailsCipherCheckPasses(lines)
} else if (result.pragma1Passes && !result.pragma2Passes) {
throw DatabaseCorruptedError_NormalCheckPassesCipherCheckFails(lines)
} else {
throw DatabaseCorruptedError_BothChecksFail(lines)
}
} else {
throw DatabaseCorruptedError_FailedToRunChecks(lines)
}
}
/**
* Try running diagnostics on the current database instance. If that fails, try opening a new connection and running the diagnostics there.
*/
private fun runDiagnostics(context: Context, db: SQLiteDatabase): DiagnosticResults {
val sameConnectionResult: DiagnosticResults = runDiagnosticsMethod("same-connection", queryDatabase(db))
if (sameConnectionResult is DiagnosticResults.Success) {
return sameConnectionResult
}
val differentConnectionResult: AtomicReference<DiagnosticResults> = AtomicReference()
val databaseFile = context.getDatabasePath(databaseName)
val latch = CountDownLatch(1)
try {
SQLiteDatabase.openOrCreateDatabase(
databaseFile.absolutePath, DatabaseSecretProvider.getOrCreateDatabaseSecret(context).asString(), null, null,
object : SQLiteDatabaseHook {
override fun preKey(connection: SQLiteConnection) {}
override fun postKey(connection: SQLiteConnection) {
if (latch.count > 0) {
val result: DiagnosticResults = runDiagnosticsMethod("different-connection") { query -> connection.executeForString(query, null, null) }
differentConnectionResult.set(result)
latch.countDown()
}
}
}
)
} catch (t: Throwable) {
return DiagnosticResults.Failure(ExceptionUtil.convertThrowableToString(t))
}
latch.await()
return differentConnectionResult.get()!!
}
/**
* Do two different integrity checks and return the results.
*/
private fun runDiagnosticsMethod(descriptor: String, query: (String) -> String): DiagnosticResults {
val output = StringBuilder()
var pragma1Passes = false
var pragma2Passes = true
output.append(" ===== PRAGMA integrity_check ($descriptor) =====\n")
try {
val results = query("PRAGMA integrity_check")
output.append(results)
if (results.lowercase().contains("ok")) {
pragma1Passes = true
}
} catch (t: Throwable) {
output.append("Failed to do integrity_check!\n").append(ExceptionUtil.convertThrowableToString(t))
return DiagnosticResults.Failure(output.toString())
}
output.append("\n").append("===== PRAGMA cipher_integrity_check ($descriptor) =====\n")
try {
val results = query("PRAGMA cipher_integrity_check")
output.append(results)
if (results.trim().isNotEmpty()) {
pragma2Passes = false
}
} catch (t: Throwable) {
output.append("Failed to do cipher_integrity_check!\n")
.append(ExceptionUtil.convertThrowableToString(t))
return DiagnosticResults.Failure(output.toString())
}
return DiagnosticResults.Success(
pragma1Passes = pragma1Passes,
pragma2Passes = pragma2Passes,
logs = output.toString()
)
}
private fun queryDatabase(db: SQLiteDatabase): (String) -> String {
return { query ->
val output = StringBuilder()
db.rawQuery(query, null).use { cursor ->
while (cursor.moveToNext()) {
val row = CursorUtil.readRowAsString(cursor)
output.append(row).append("\n")
}
}
output.toString()
}
}
private sealed class DiagnosticResults(val logs: String) {
class Success(
val pragma1Passes: Boolean,
val pragma2Passes: Boolean,
logs: String
) : DiagnosticResults(logs)
class Failure(logs: String) : DiagnosticResults(logs)
}
private open class CustomTraceError constructor(lines: List<String>) : Error() {
init {
val custom: Array<StackTraceElement> = lines.map { line -> StackTraceElement(line, "", "", 0) }.toTypedArray()
stackTrace = ExceptionUtil.joinStackTrace(stackTrace, custom)
}
}
private class DatabaseCorruptedError_BothChecksPass constructor(lines: List<String>) : CustomTraceError(lines)
private class DatabaseCorruptedError_BothChecksFail constructor(lines: List<String>) : CustomTraceError(lines)
private class DatabaseCorruptedError_NormalCheckFailsCipherCheckPasses constructor(lines: List<String>) : CustomTraceError(lines)
private class DatabaseCorruptedError_NormalCheckPassesCipherCheckFails constructor(lines: List<String>) : CustomTraceError(lines)
private class DatabaseCorruptedError_FailedToRunChecks constructor(lines: List<String>) : CustomTraceError(lines)
companion object {
private val TAG = Log.tag(SqlCipherErrorHandler::class.java)
}
}
| gpl-3.0 | cc346c6121b9aaab7ed4550adf25b077 | 38.414634 | 150 | 0.719059 | 4.510816 | false | false | false | false |
nrizzio/Signal-Android | app/src/spinner/java/org/thoughtcrime/securesms/database/ProfileKeyCredentialTransformer.kt | 1 | 1703 | package org.thoughtcrime.securesms.database
import android.database.Cursor
import org.signal.core.util.Hex
import org.signal.core.util.requireString
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredential
import org.signal.spinner.ColumnTransformer
import org.signal.spinner.DefaultColumnTransformer
import org.thoughtcrime.securesms.database.model.databaseprotos.ExpiringProfileKeyCredentialColumnData
import org.thoughtcrime.securesms.util.Base64
import org.thoughtcrime.securesms.util.toLocalDateTime
import java.security.MessageDigest
object ProfileKeyCredentialTransformer : ColumnTransformer {
override fun matches(tableName: String?, columnName: String): Boolean {
return columnName == RecipientDatabase.EXPIRING_PROFILE_KEY_CREDENTIAL && (tableName == null || tableName == RecipientDatabase.TABLE_NAME)
}
override fun transform(tableName: String?, columnName: String, cursor: Cursor): String {
val columnDataString = cursor.requireString(RecipientDatabase.EXPIRING_PROFILE_KEY_CREDENTIAL) ?: return DefaultColumnTransformer.transform(tableName, columnName, cursor)
val columnDataBytes = Base64.decode(columnDataString)
val columnData = ExpiringProfileKeyCredentialColumnData.parseFrom(columnDataBytes)
val credential = ExpiringProfileKeyCredential(columnData.expiringProfileKeyCredential.toByteArray())
return """
Credential: ${Hex.toStringCondensed(MessageDigest.getInstance("SHA-256").digest(credential.serialize()))}
Expires: ${credential.expirationTime.toLocalDateTime()}
Matching Profile Key:
${Base64.encodeBytes(columnData.profileKey.toByteArray())}
""".trimIndent().replace("\n", "<br>")
}
}
| gpl-3.0 | d20dfbfa703b55628abebcf27d0fa9d6 | 50.606061 | 174 | 0.80094 | 4.70442 | false | false | false | false |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt | 1 | 812 | package com.baeldung.kotlin;
import org.junit.Test
import org.mockito.Mockito
class LibraryManagementTest {
@Test(expected = IllegalStateException::class)
fun whenBookIsNotAvailable_thenAnExceptionIsThrown() {
val mockBookService = Mockito.mock(BookService::class.java)
Mockito.`when`(mockBookService.inStock(100)).thenReturn(false)
val manager = LendBookManager(mockBookService)
manager.checkout(100, 1)
}
@Test
fun whenBookIsAvailable_thenLendMethodIsCalled() {
val mockBookService = Mockito.mock(BookService::class.java)
Mockito.`when`(mockBookService.inStock(100)).thenReturn(true)
val manager = LendBookManager(mockBookService)
manager.checkout(100, 1)
Mockito.verify(mockBookService).lend(100, 1)
}
} | gpl-3.0 | b3e82dda547416c757523d0cd8ae2f25 | 26.1 | 70 | 0.711823 | 4 | false | true | false | false |
bibaev/stream-debugger-plugin | src/main/java/com/intellij/debugger/streams/trace/impl/TraceExpressionBuilderBase.kt | 1 | 6632 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.trace.impl
import com.intellij.debugger.streams.lib.HandlerFactory
import com.intellij.debugger.streams.trace.IntermediateCallHandler
import com.intellij.debugger.streams.trace.TerminatorCallHandler
import com.intellij.debugger.streams.trace.TraceExpressionBuilder
import com.intellij.debugger.streams.trace.TraceHandler
import com.intellij.debugger.streams.trace.dsl.ArrayVariable
import com.intellij.debugger.streams.trace.dsl.CodeBlock
import com.intellij.debugger.streams.trace.dsl.Dsl
import com.intellij.debugger.streams.trace.dsl.Variable
import com.intellij.debugger.streams.trace.dsl.impl.TextExpression
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.impl.StreamChainImpl
import java.util.*
/**
* @author Vitaliy.Bibaev
*/
abstract class TraceExpressionBuilderBase(protected val dsl: Dsl, private val handlerFactory: HandlerFactory)
: TraceExpressionBuilder {
protected val resultVariableName = "myRes"
override fun createTraceExpression(chain: StreamChain): String {
val intermediateHandlers = chain.intermediateCalls.mapIndexedTo(ArrayList(), handlerFactory::getForIntermediate)
val terminatorCall = chain.terminationCall
val terminatorHandler = handlerFactory.getForTermination(terminatorCall, "evaluationResult[0]")
val traceChain = buildTraceChain(chain, intermediateHandlers, terminatorHandler)
val infoArraySize = 2 + intermediateHandlers.size
val info = dsl.array(dsl.types.ANY, "info")
val streamResult = dsl.variable(dsl.types.nullable { ANY }, "streamResult")
val declarations = buildDeclarations(intermediateHandlers, terminatorHandler)
val tracingCall = buildStreamExpression(traceChain, streamResult)
val fillingInfoArray = buildFillInfo(intermediateHandlers, terminatorHandler, info)
val result = dsl.variable(dsl.types.ANY, resultVariableName)
return dsl.code {
scope {
// TODO: avoid language dependent code
val startTime = declare(variable(types.LONG, "startTime"), "java.lang.System.nanoTime()".expr, false)
declare(info, newSizedArray(types.ANY, infoArraySize), false)
declare(timeDeclaration())
add(declarations)
add(tracingCall)
add(fillingInfoArray)
val elapsedTime = declare(array(types.LONG, "elapsedTime"),
newArray(types.LONG, "java.lang.System.nanoTime() - ${startTime.toCode()}".expr), false)
result assign newArray(types.ANY, info, streamResult, elapsedTime)
}
}
}
private fun buildTraceChain(chain: StreamChain,
intermediateCallHandlers: List<IntermediateCallHandler>,
terminatorHandler: TerminatorCallHandler): StreamChain {
val newIntermediateCalls = mutableListOf<IntermediateStreamCall>()
val qualifierExpression = chain.qualifierExpression
newIntermediateCalls.add(createTimePeekCall(qualifierExpression.typeAfter))
val intermediateCalls = chain.intermediateCalls
assert(intermediateCalls.size == intermediateCallHandlers.size)
for ((call, handler) in intermediateCalls.zip(intermediateCallHandlers)) {
newIntermediateCalls.addAll(handler.additionalCallsBefore())
newIntermediateCalls.add(handler.transformCall(call))
newIntermediateCalls.add(createTimePeekCall(call.typeAfter))
newIntermediateCalls.addAll(handler.additionalCallsAfter())
}
newIntermediateCalls.addAll(terminatorHandler.additionalCallsBefore())
val terminatorCall = terminatorHandler.transformCall(chain.terminationCall)
return StreamChainImpl(qualifierExpression, newIntermediateCalls, terminatorCall,
chain.context)
}
private fun createTimePeekCall(elementType: GenericType): IntermediateStreamCall {
val lambda = dsl.lambda("x") {
doReturn(dsl.updateTime())
}.toCode()
return dsl.createPeekCall(elementType, lambda)
}
private fun buildDeclarations(intermediateCallsHandlers: List<IntermediateCallHandler>,
terminatorHandler: TerminatorCallHandler): CodeBlock {
return dsl.block {
intermediateCallsHandlers.flatMap { it.additionalVariablesDeclaration() }.forEach({ declare(it) })
terminatorHandler.additionalVariablesDeclaration().forEach({ declare(it) })
}
}
private fun buildStreamExpression(chain: StreamChain, streamResult: Variable): CodeBlock {
val resultType = chain.terminationCall.resultType
return dsl.block {
declare(streamResult, nullExpression, true)
val evaluationResult = array(resultType, "evaluationResult")
if (resultType != types.VOID) declare(evaluationResult, newArray(resultType, TextExpression(resultType.defaultValue)), true)
tryBlock {
if (resultType == types.VOID) {
streamResult assign newSizedArray(types.ANY, 1)
statement { TextExpression(chain.text) }
}
else {
statement { evaluationResult.set(0, TextExpression(chain.text)) }
streamResult assign evaluationResult
}
}.catch(variable(types.EXCEPTION, "t")) {
// TODO: add exception variable as a property of catch code block
streamResult assign newArray(types.EXCEPTION, "t".expr)
}
}
}
private fun buildFillInfo(intermediateCallsHandlers: List<IntermediateCallHandler>,
terminatorHandler: TerminatorCallHandler,
info: ArrayVariable): CodeBlock {
val handlers = listOf<TraceHandler>(*intermediateCallsHandlers.toTypedArray(), terminatorHandler)
return dsl.block {
for ((i, handler) in handlers.withIndex()) {
scope {
add(handler.prepareResult())
statement { info.set(i, handler.resultExpression) }
}
}
}
}
}
| apache-2.0 | f33a2fe94094414aeee4818d4c6a6d99 | 42.064935 | 130 | 0.733263 | 4.730385 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/hover/KotlinInformationProvider.kt | 1 | 2973 | /*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors.hover
import org.eclipse.jface.text.information.IInformationProvider
import org.eclipse.jface.text.information.IInformationProviderExtension
import org.eclipse.jface.text.information.IInformationProviderExtension2
import org.eclipse.jface.text.ITextViewer
import org.eclipse.jface.text.IRegion
import org.eclipse.jface.text.IInformationControlCreator
import org.eclipse.jdt.internal.ui.text.JavaWordFinder
import org.eclipse.jdt.internal.ui.text.java.hover.JavadocBrowserInformationControlInput
import org.jetbrains.kotlin.ui.editors.KotlinEditor
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.core.references.resolveToSourceDeclaration
import org.jetbrains.kotlin.core.resolve.lang.java.resolver.EclipseJavaSourceElement
import org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover
public class KotlinInformationProvider(val editor: KotlinEditor) : IInformationProvider, IInformationProviderExtension, IInformationProviderExtension2 {
override fun getSubject(textViewer: ITextViewer?, offset: Int): IRegion? {
return if (textViewer != null) JavaWordFinder.findWord(textViewer.getDocument(), offset) else null
}
override fun getInformation(textViewer: ITextViewer?, subject: IRegion?): String? = null // deprecated method
override fun getInformation2(textViewer: ITextViewer?, subject: IRegion): Any? {
val jetElement = EditorUtil.getJetElement(editor, subject.getOffset())
if (jetElement == null) return null
val sourceElements = jetElement.resolveToSourceDeclaration()
if (sourceElements.isEmpty()) return null
val javaElements = sourceElements.filterIsInstance(EclipseJavaSourceElement::class.java)
if (javaElements.isNotEmpty()) {
val elements = javaElements.mapNotNull { it.getElementBinding().getJavaElement() }
return JavadocHover.getHoverInfo(elements.toTypedArray(), null, subject, null)
}
return null
}
override fun getInformationPresenterControlCreator(): IInformationControlCreator {
return JavadocHover.PresenterControlCreator(editor.javaEditor.getSite())
}
} | apache-2.0 | 8ebf029babdaff9b34b0b4080dede49e | 49.40678 | 152 | 0.731921 | 4.652582 | false | false | false | false |
jonnyzzz/kotlin.xml.bind | jdom/src/main/kotlin/org/jonnyzzz/kotlin/xml/bind/jdom/impl/XBind.impl.kt | 1 | 2797 | package org.jonnyzzz.kotlin.xml.bind.jdom.impl
import org.jdom2.Element
import org.jonnyzzz.kotlin.xml.bind.*
import org.jonnyzzz.kotlin.xml.bind.jdom.impl.bind.XElementMatcher
import org.jonnyzzz.kotlin.xml.bind.jdom.impl.bind.XmlAnyElementWrap
import org.jonnyzzz.kotlin.xml.bind.jdom.impl.bind.XmlAnyElementsWrap
import org.jonnyzzz.kotlin.xml.bind.jdom.impl.bind.XmlBind
import java.util.*
internal class XMLAnyBuilderImpl(val elementsBefore : XMLBuilderImpl) : XMLAnyBinder {
override fun <T : Any> div(t: XSub<T>) = elementsBefore.wrap( XmlAnyElementWrap( XMLBuilderImpl() / t ))
override fun <T : Any> div(t: XUnknownElement<T>) = elementsBefore.wrap( XmlAnyElementWrap( XMLBuilderImpl() / t ))
}
internal class XMLsAnyBuilderImpl(val elementsBefore : XMLBuilderImpl) : XMLsAnyBinder {
override fun <T : Any> div(t: XSub<T>) = elementsBefore.wrap( XmlAnyElementsWrap { XMLBuilderImpl() / t })
override fun <T : Any> div(t: XUnknownElement<T>) = elementsBefore.wrap( XmlAnyElementsWrap { XMLBuilderImpl() / t })
}
internal object JDOMIMPL {
val ROOT : XMLBuilderImpl
get() = XMLBuilderImpl()
fun <T : Any> copy(from : T, to : T) {
val xml = save("mock-root-name", from)
bind(xml, to)
}
fun <T : Any> clone(t : T) : T {
val clazz = t.javaClass
val xml = save("mock-root-name", t)
return load(xml, clazz)
}
private fun <T : Any> elementsToBind(t : T): List<XmlBind> = t.delegatedProperties(XmlBind::class.java)
fun <T : Any> load(_element : Element, clazz : Class<T>) : T = bind(_element, clazz.newInstance())
fun <T : Any> bind(_element : Element, t : T) : T {
val element = _element.clone()
val fields = elementsToBind(t).toCollection(LinkedList())
val p1: (XmlBind) -> Boolean = { it is XElementMatcher }
fields.filter(p1).forEach { it.load(element) }
fields.filter(p1).forEach {
val matching = (it as XElementMatcher).matchingElements()
element.removeChildren(matching)
}
fields.filterNot(p1).forEach { it.load(element) }
return t
}
fun <T : Any> save(t : T, clazz : Class<T> = t.javaClass) : Element {
val root = clazz.getAnnotationRec(XRoot::class.java) ?: throw RuntimeException("Failed to get name for $clazz. XRoot annotation is missing")
val rootElementName = root.name
return save(rootElementName, t)
}
fun <T : Any> save(rootElementName: String, t: T) : Element {
val element = Element(rootElementName)
save(element, t)
return element
}
fun <T : Any> save(element: Element, t: T) {
fun elementsToSave(): List<XmlBind> {
val v = elementsToBind(t)
if (!v.any{it.saveOrder != null}) return v
return v.sortedBy { it -> (it.saveOrder ?: 0) }
}
elementsToSave().forEach {
it.save { element }
}
}
}
| apache-2.0 | 28230991a3b1bdecfb889af1d8c15ee9 | 33.109756 | 144 | 0.679299 | 3.436118 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/settings/AboutFragment.kt | 1 | 12264 | package me.proxer.app.settings
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.core.os.bundleOf
import com.danielstone.materialaboutlibrary.ConvenienceBuilder
import com.danielstone.materialaboutlibrary.MaterialAboutFragment
import com.danielstone.materialaboutlibrary.items.MaterialAboutActionItem
import com.danielstone.materialaboutlibrary.model.MaterialAboutCard
import com.danielstone.materialaboutlibrary.model.MaterialAboutList
import com.mikepenz.aboutlibraries.Libs
import com.mikepenz.aboutlibraries.LibsBuilder
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import me.proxer.app.BuildConfig
import me.proxer.app.R
import me.proxer.app.base.CustomTabsAware
import me.proxer.app.chat.prv.Participant
import me.proxer.app.chat.prv.PrvMessengerActivity
import me.proxer.app.chat.prv.create.CreateConferenceActivity
import me.proxer.app.chat.prv.sync.MessengerDao
import me.proxer.app.forum.TopicActivity
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.settings.status.ServerStatusActivity
import me.proxer.app.util.data.PreferenceHelper
import me.proxer.app.util.extension.androidUri
import me.proxer.app.util.extension.iconColor
import me.proxer.app.util.extension.openHttpPage
import me.proxer.app.util.extension.resolveColor
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.app.util.extension.toPrefixedHttpUrl
import me.proxer.app.util.extension.toast
import me.zhanghai.android.customtabshelper.CustomTabsHelperFragment
import okhttp3.HttpUrl
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class AboutFragment : MaterialAboutFragment(), CustomTabsAware {
companion object {
private val libraries = arrayOf(
"aspectratioimageview", "autodispose", "betterlinkmovementmethod", "customtabshelper", "exoplayer",
"flexboxlayout", "glide", "hawk", "jsoup", "koptional", "kotterknife", "leakcanary", "materialaboutlibrary",
"materialpreference", "materialdialogs", "materialprogressbar", "materialratingbar", "moshi", "okhttp",
"rapiddecoder", "recyclerviewsnap", "retrofit", "rxandroid", "rxbinding", "rxkotlin", "rxjava",
"subsamplingpdfdecoder", "subsamplingscaleimageview", "timber", "threeten", "threetenandroidbackport"
)
private val excludedLibraries = arrayOf("fastadapter", "materialize")
private val teamLink = "https://proxer.me/team?device=default".toPrefixedHttpUrl()
private val facebookLink = "https://facebook.com/Anime.Proxer.Me".toPrefixedHttpUrl()
private val twitterLink = "https://twitter.com/proxerme".toPrefixedHttpUrl()
private val youtubeLink = "https://youtube.com/channel/UC7h-fT9Y9XFxuZ5GZpbcrtA".toPrefixedHttpUrl()
private val discordLink = "https://discord.gg/XwrEDmA".toPrefixedHttpUrl()
private val repositoryLink = "https://github.com/proxer/ProxerAndroid".toPrefixedHttpUrl()
private const val supportId = "374605"
private const val supportCategory = "anwendungen"
private const val developerProxerName = "RubyGee"
private const val developerProxerId = "121658"
private const val developerGithubName = "rubengees"
fun newInstance() = AboutFragment().apply {
arguments = bundleOf()
}
}
private val preferenceHelper by safeInject<PreferenceHelper>()
private val messengerDao by safeInject<MessengerDao>()
private var customTabsHelper by Delegates.notNull<CustomTabsHelperFragment>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
customTabsHelper = CustomTabsHelperFragment.attachTo(this)
setLikelyUrl(teamLink)
setLikelyUrl(facebookLink)
setLikelyUrl(twitterLink)
setLikelyUrl(youtubeLink)
setLikelyUrl(discordLink)
}
override fun setLikelyUrl(url: HttpUrl): Boolean {
return customTabsHelper.mayLaunchUrl(url.androidUri(), bundleOf(), emptyList())
}
override fun showPage(url: HttpUrl, forceBrowser: Boolean) {
customTabsHelper.openHttpPage(requireActivity(), url, forceBrowser)
}
override fun getMaterialAboutList(context: Context): MaterialAboutList = MaterialAboutList.Builder()
.addCard(MaterialAboutCard.Builder()
.apply { buildInfoItems(context).forEach { addItem(it) } }
.build())
.addCard(MaterialAboutCard.Builder()
.title(R.string.about_social_media_title)
.apply { buildSocialMediaItems(context).forEach { addItem(it) } }
.build())
.addCard(MaterialAboutCard.Builder()
.title(R.string.about_support_title)
.apply { buildSupportItems(context).forEach { addItem(it) } }
.build())
.addCard(MaterialAboutCard.Builder()
.title(getString(R.string.about_developer_title))
.apply { buildDeveloperItems(context).forEach { addItem(it) } }
.build())
.build()
override fun getTheme() = R.style.Fragment_App_AboutFragment
override fun shouldAnimate() = false
private fun buildInfoItems(context: Context) = listOf(
ConvenienceBuilder.createAppTitleItem(context),
MaterialAboutActionItem.Builder()
.text(R.string.about_version_title)
.subText(BuildConfig.VERSION_NAME)
.icon(IconicsDrawable(context, CommunityMaterial.Icon.cmd_tag).iconColor(context))
.setOnClickAction {
val title = getString(R.string.clipboard_title)
requireContext().getSystemService<ClipboardManager>()?.setPrimaryClip(
ClipData.newPlainText(title, BuildConfig.VERSION_NAME)
)
requireContext().toast(R.string.clipboard_status)
}.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_licenses_title)
.subText(R.string.about_licenses_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon3.cmd_clipboard_text).iconColor(context))
.setOnClickAction {
LibsBuilder()
.withAutoDetect(false)
.withShowLoadingProgress(false)
.withAboutVersionShown(false)
.withAboutIconShown(false)
.withVersionShown(false)
.withLibraries(*libraries)
.withExcludedLibraries(*excludedLibraries)
.withFields(R.string::class.java.fields)
.withActivityTheme(preferenceHelper.themeContainer.theme.main)
.withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
.withActivityTitle(getString(R.string.about_licenses_activity_title))
.start(requireActivity())
}.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_source_code)
.subText(R.string.about_source_code_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon3.cmd_code_braces).iconColor(context))
.setOnClickAction { showPage(repositoryLink) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_server_status)
.subText(R.string.about_server_status_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon.cmd_server).iconColor(context))
.setOnClickAction { ServerStatusActivity.navigateTo(requireActivity()) }
.build()
)
private fun buildSocialMediaItems(context: Context) = listOf(
MaterialAboutActionItem.Builder()
.text(R.string.about_facebook_title)
.subText(R.string.about_facebook_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon4.cmd_facebook).iconColor(context))
.setOnClickAction { showPage(facebookLink) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_twitter_title)
.subText(R.string.about_twitter_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon.cmd_twitter).iconColor(context))
.setOnClickAction { showPage(twitterLink) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_youtube_title)
.subText(R.string.about_youtube_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon2.cmd_youtube).iconColor(context))
.setOnClickAction { showPage(youtubeLink) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_discord_title)
.subText(R.string.about_discord_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon4.cmd_discord).iconColor(context))
.setOnClickAction { showPage(discordLink) }
.build()
)
private fun buildSupportItems(context: Context) = listOf(
MaterialAboutActionItem.Builder()
.icon(IconicsDrawable(context, CommunityMaterial.Icon2.cmd_information).iconColor(context))
.subText(R.string.about_support_info)
.setOnClickAction { showPage(teamLink) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_support_message_title)
.subText(R.string.about_support_message_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon4.cmd_email).iconColor(context))
.setOnClickAction {
Completable
.fromAction {
messengerDao.findConferenceForUser(developerProxerName).let { existingConference ->
when (existingConference) {
null -> CreateConferenceActivity.navigateTo(
requireActivity(), false, Participant(developerProxerName)
)
else -> PrvMessengerActivity.navigateTo(requireActivity(), existingConference)
}
}
}
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_support_forum_title)
.subText(R.string.about_support_forum_description)
.icon(IconicsDrawable(context, CommunityMaterial.Icon4.cmd_forum).iconColor(context))
.setOnClickAction { TopicActivity.navigateTo(requireActivity(), supportId, supportCategory) }
.build()
)
private fun buildDeveloperItems(context: Context) = listOf(
MaterialAboutActionItem.Builder()
.text(R.string.about_developer_github_title)
.subText(developerGithubName)
.icon(IconicsDrawable(context, CommunityMaterial.Icon4.cmd_github_circle).iconColor(context))
.setOnClickAction { showPage("https://github.com/$developerGithubName".toPrefixedHttpUrl()) }
.build(),
MaterialAboutActionItem.Builder()
.text(getString(R.string.about_developer_proxer_title))
.subText(developerProxerName)
.icon(ContextCompat.getDrawable(context, R.drawable.ic_stat_proxer)?.apply {
colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(
context.resolveColor(R.attr.colorIcon), BlendModeCompat.SRC_IN
)
})
.setOnClickAction {
ProfileActivity.navigateTo(requireActivity(), developerProxerId, developerProxerName, null)
}
.build()
)
}
| gpl-3.0 | 244a82eca72c6b0641290d9b2c17f52f | 47.094118 | 120 | 0.674739 | 4.704258 | false | false | false | false |
nathanial/galaxy-sim | src/main/java/simulation/GalaxyView.kt | 1 | 3580 | package simulation
import com.google.common.eventbus.Subscribe
import main.*
import simulation.model.basic.Simulation
import simulation.model.basic.SolarSystem
import simulation.model.basic.TickEvent
import java.awt.*
import java.awt.geom.AffineTransform
import java.awt.geom.Ellipse2D
import java.awt.geom.Point2D
import java.util.*
import javax.swing.JPanel
import javax.swing.SwingUtilities
class GalaxyView(val simulation: Simulation) : JPanel() {
var lastX = 0.0
var lastY = 0.0
var lastTransform = AffineTransform()
var isDragging = false
var dragStart = XY(0.0, 0.0)
init {
isOpaque = false
background = Color.white
lastTransform.translate(500.0,500.0)
lastTransform.scale(0.01,0.01)
}
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
val g2d = g as Graphics2D
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
g2d.color = Color(0, 0, 0)
g2d.fillRect(0,0,this.size.width,this.size.height)
g2d.transform = lastTransform.clone() as AffineTransform
for(system in this.findSystemsInView(g2d.clipBounds)){
system.paint(g2d, pickRenderMode(g2d))
}
}
override fun getPreferredSize(): Dimension? {
return Dimension(1000, 1000)
}
fun findSystemsInView(clipBounds: Rectangle): Collection<SolarSystem> {
val systems = ArrayList<SolarSystem>()
for(system in this.simulation.systems.get()){
if(clipBounds.contains(Point2D.Double(system.galacticCoordinates.x, system.galacticCoordinates.y))){
systems.add(system)
}
}
return systems;
}
fun drag(x: Int, y: Int){
lastTransform.translate((x - dragStart.x) / lastTransform.scaleX, (y - dragStart.y) / lastTransform.scaleY)
dragStart = XY(x.toDouble(), y.toDouble())
repaint(16)
}
fun zoom(factor: Double){
val pt = Point2D.Double()
lastTransform.inverseTransform(Point2D.Double(lastX, lastY), pt)
lastTransform.translate(pt.x, pt.y)
lastTransform.scale(factor, factor)
lastTransform.translate(-pt.x, -pt.y)
repaint(16)
}
fun pickRenderMode(g2d: Graphics2D): SolarSystem.PaintOptions {
if(g2d.transform.scaleY > 6){
return SolarSystem.PaintOptions.ALL
} else {
return SolarSystem.PaintOptions.HIDE_PLANETS
}
}
@Subscribe
public fun onZoom(e: MouseZoomEvent){
SwingUtilities.invokeLater {
if(e.zoom > 0){
zoom(0.9)
} else {
zoom(1.1)
}
}
}
@Subscribe
public fun onMouseMove(e: MouseMoveEvent){
SwingUtilities.invokeLater {
if(isDragging){
drag(e.x, e.y);
}
lastX = e.x.toDouble()
lastY = e.y.toDouble()
}
}
@Subscribe
public fun onMouseDown(e: MouseDownEvent){
SwingUtilities.invokeLater {
isDragging = true
dragStart = XY(e.x.toDouble(), e.y.toDouble())
}
}
@Subscribe
public fun onMouseUp(e: MouseUpEvent){
SwingUtilities.invokeLater {
isDragging = false
}
}
@Subscribe
public fun onSimulationUpdated(e: TickEvent){
SwingUtilities.invokeLater {
repaint(100)
}
}
}
| mit | 328a0469774efaa916ce3c8c9bde8769 | 26.96875 | 115 | 0.618715 | 3.977778 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/manmanga/src/eu/kanade/tachiyomi/extension/en/manmanga/ManManga.kt | 1 | 5218 | package eu.kanade.tachiyomi.extension.en.manmanga
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.text.SimpleDateFormat
class ManManga : ParsedHttpSource() {
override val name = "Man Manga"
override val baseUrl = "https://m.manmanga.com"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
companion object {
val dateFormat by lazy {
SimpleDateFormat("MMM dd, yyyy")
}
}
override fun popularMangaSelector() = "#scrollBox > #scrollContent > li > a"
override fun latestUpdatesSelector() = popularMangaSelector()
override fun searchMangaSelector() = popularMangaSelector()
override fun popularMangaRequest(page: Int) =
GET("$baseUrl/category?sort=hot&page=$page", headers)
override fun latestUpdatesRequest(page: Int) =
GET("$baseUrl/category?sort=new&page=$page", headers)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) =
GET("$baseUrl/search?keyword=$query&page=$page", headers)
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.select("div.text > h4").text().trim()
}
override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.select("div.text > div.name > h4").text().trim()
}
override fun popularMangaNextPageSelector() = "script:containsData(next_page_url):not(:containsData(false))"
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(searchMangaSelector()).map { element ->
searchMangaFromElement(element)
}
val hasNextPage = searchMangaNextPageSelector().let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return client.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map { response ->
searchMangaParse(response)
}
}
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val getThumbnailUrl = document.select(".bg-box .bg").attr("style")
author = document.select(".author").text().replace("Author:", "").trim()
genre = document.select(".tags span").joinToString(", ") {
it.text().trim()
}
status = document.select(".type").text().replace("Status:", "").trim().let {
parseStatus(it)
}
description = document.select(".inner-text").text().trim()
thumbnail_url = getThumbnailUrl.substring(getThumbnailUrl.indexOf("https://"), getThumbnailUrl.indexOf("')"))
}
private fun parseStatus(status: String) = when {
status.contains("Ongoing") -> SManga.ONGOING
status.contains("Completed") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListParse(response: Response): List<SChapter> {
return super.chapterListParse(response).reversed()
}
override fun chapterListSelector() = "dl.chapter-list > dd > ul > li > a"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
setUrlWithoutDomain(element.attr("href"))
name = element.attr("alt").trim()
}
override fun pageListParse(document: Document): List<Page> {
val pages = mutableListOf<Page>()
if (document.select("ul.img-list > li.unloaded > img").toString().isNotEmpty()) {
document.select("ul.img-list > li.unloaded > img").forEach {
val imgUrl = it.attr("data-src")
pages.add(Page(pages.size, "", imgUrl))
}
} else {
document.select("ul.img-list > li.loaded > img").forEach {
val imgUrl = it.attr("data-src")
pages.add(Page(pages.size, "", imgUrl))
}
}
return pages
}
override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used")
override fun getFilterList() = FilterList()
}
| apache-2.0 | ab6aa648b121cefbccf8d93f9bd494bb | 35.71831 | 117 | 0.670311 | 4.74 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/newsfeed/dto/NewsfeedSearchExtendedResponse.kt | 1 | 2420 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.newsfeed.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.groups.dto.GroupsGroupFull
import com.vk.sdk.api.users.dto.UsersUserFull
import com.vk.sdk.api.wall.dto.WallWallpostFull
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param items
* @param profiles
* @param groups
* @param suggestedQueries
* @param nextFrom
* @param count - Filtered number
* @param totalCount - Total number
*/
data class NewsfeedSearchExtendedResponse(
@SerializedName("items")
val items: List<WallWallpostFull>? = null,
@SerializedName("profiles")
val profiles: List<UsersUserFull>? = null,
@SerializedName("groups")
val groups: List<GroupsGroupFull>? = null,
@SerializedName("suggested_queries")
val suggestedQueries: List<String>? = null,
@SerializedName("next_from")
val nextFrom: String? = null,
@SerializedName("count")
val count: Int? = null,
@SerializedName("total_count")
val totalCount: Int? = null
)
| mit | a022ea038d933e7339d2748e04d902b9 | 38.032258 | 81 | 0.696281 | 4.368231 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/color/HSVColor.kt | 1 | 1676 | package pl.shockah.godwit.color
import pl.shockah.godwit.ease.ease
import pl.shockah.godwit.geom.Angle
import pl.shockah.godwit.geom.Degrees
import kotlin.math.pow
import kotlin.math.sqrt
data class HSVColor(
val h: Angle,
val s: Float,
val v: Float
) : IGColor<HSVColor>() {
companion object {
fun from(rgb: RGBColor): HSVColor {
val max = maxOf(rgb.r, rgb.g, rgb.b)
val min = minOf(rgb.r, rgb.g, rgb.b)
val range = max - min
val h: Float
val s: Float
val v: Float
h = when {
range == 0f -> 0f
max == rgb.r -> (60 * (rgb.g - rgb.b) / range + 360) % 360
max == rgb.g -> 60 * (rgb.b - rgb.r) / range + 120
else -> 60 * (rgb.r - rgb.g) / range + 240
}
s = if (max > 0) 1 - min / max else 0f
v = max
return HSVColor(Degrees.of(h), s, v)
}
}
override val rgb by lazy {
var h = this.h.degrees.value
if (h < 0f)
h += 360f
val x = (h / 60f + 6) % 6
val i = x.toInt()
val f = x - i
val p = v * (1 - s)
val q = v * (1 - s * f)
val t = v * (1 - s * (1 - f))
return@lazy when (i) {
0 -> RGBColor(v, t, p)
1 -> RGBColor(q, v, p)
2 -> RGBColor(p, v, t)
3 -> RGBColor(p, q, v)
4 -> RGBColor(t, p, v)
else -> RGBColor(v, p, q)
}
}
override fun getDistance(other: HSVColor): Float {
val delta = h delta other.h
return sqrt((delta.degrees.value / 180f).pow(2) + (s - other.s).pow(2) + (v - other.v).pow(2))
}
override fun ease(other: HSVColor, f: Float): HSVColor {
return HSVColor(
h.ease(other.h, f),
f.ease(s, other.s),
f.ease(v, other.v)
)
}
fun with(h: Angle = this.h, s: Float = this.s, v: Float = this.v): HSVColor {
return HSVColor(h, s, v)
}
} | apache-2.0 | c7a6e5a08b896129dc68faba024d968d | 21.972603 | 96 | 0.565632 | 2.384068 | false | false | false | false |
overworld-hosting/overworld | core/src/main/kotlin/com/turtleboxgames/overworld/UUID.kt | 1 | 1056 | package com.turtleboxgames.overworld
import java.nio.ByteBuffer
import java.util.UUID
import java.util.Base64
/**
* Generates an array of bytes containing the UUID value.
* @return UUID bytes.
*/
fun UUID.bytes(): ByteArray {
val buffer = ByteBuffer.wrap(ByteArray(16))
buffer.putLong(this.mostSignificantBits)
buffer.putLong(this.leastSignificantBits)
return buffer.array()
}
/**
* Computes the base-64 representation of the UUID.
* The string will be in a URL-safe format with the padding removed.
* @return UUID in base-64.
*/
fun UUID.base64(): String {
val encoder = Base64.getUrlEncoder()
return encoder.encodeToString(this.bytes()).dropLast(2)
}
/**
* Extracts a UUID from a base-64 formatted string.
* The string should be the same format produced by @see UUID.base64.
* @return Parsed UUID.
*/
fun String.getBase64UUID(): UUID {
val bytes = Base64.getUrlDecoder().decode(this)
val buffer = ByteBuffer.wrap(bytes)
val high = buffer.long
val low = buffer.long
return UUID(high, low)
} | mit | 6bbee8f789c3844198a04c091e03cf0b | 26.102564 | 69 | 0.711174 | 3.705263 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpath/test/uk/co/reecedunn/intellij/plugin/xpath/tests/completion/XPathLookupElementTest.kt | 1 | 13562 | /*
* Copyright (C) 2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.tests.completion
import com.intellij.codeInsight.lookup.AutoCompletionPolicy
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.PluginId
import com.intellij.ui.JBColor
import org.hamcrest.CoreMatchers.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtensionPointBean
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.xpath.completion.lookup.XPathAtomicOrUnionTypeLookup
import uk.co.reecedunn.intellij.plugin.xpath.completion.lookup.XPathInsertText
import uk.co.reecedunn.intellij.plugin.xpath.completion.lookup.XPathKeywordLookup
import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathIcons
import uk.co.reecedunn.intellij.plugin.xpath.tests.parser.ParserTestCase
@Suppress("RedundantVisibilityModifier")
@DisplayName("XPath 3.1 - Code Completion - Lookup Element")
class XPathLookupElementTest : ParserTestCase() {
override val pluginId: PluginId = PluginId.getId("XPathLookupElementTest")
override fun registerServicesAndExtensions() {
super.registerServicesAndExtensions()
val app = ApplicationManager.getApplication()
app.registerExtensionPointBean(
"com.intellij.documentWriteAccessGuard",
"com.intellij.openapi.editor.impl.DocumentWriteAccessGuard",
pluginDisposable
)
}
@Nested
@DisplayName("XPath 3.1 EBNF (41) ForwardAxis ; XPath 3.1 EBNF (44) ReverseAxis")
internal inner class ForwardOrReverseAxis {
@Test
@DisplayName("lookup element")
fun lookupElement() {
val lookup: LookupElement = XPathKeywordLookup("descendant", XPathInsertText.AXIS_MARKER)
assertThat(lookup.toString(), `is`("descendant"))
assertThat(lookup.lookupString, `is`("descendant"))
assertThat(lookup.allLookupStrings, `is`(setOf("descendant")))
assertThat(lookup.`object`, `is`(sameInstance(lookup)))
assertThat(lookup.psiElement, `is`(nullValue()))
assertThat(lookup.isValid, `is`(true))
assertThat(lookup.requiresCommittedDocuments(), `is`(true))
assertThat(lookup.autoCompletionPolicy, `is`(AutoCompletionPolicy.SETTINGS_DEPENDENT))
assertThat(lookup.isCaseSensitive, `is`(true))
assertThat(lookup.isWorthShowingInAutoPopup, `is`(true))
val presentation = LookupElementPresentation()
lookup.renderElement(presentation)
// NOTE: IntelliJ 2020.2 deprecates and changes the behaviour of presentation.isReal.
assertThat(presentation.icon, `is`(nullValue()))
assertThat(presentation.typeIcon, `is`(nullValue()))
assertThat(presentation.itemText, `is`("descendant"))
assertThat(presentation.tailText, `is`("::"))
assertThat(presentation.typeText, `is`(nullValue()))
assertThat(presentation.isStrikeout, `is`(false))
assertThat(presentation.isItemTextBold, `is`(true))
assertThat(presentation.isItemTextItalic, `is`(false))
assertThat(presentation.isItemTextUnderlined, `is`(false))
assertThat(presentation.itemTextForeground, `is`(JBColor.foreground()))
assertThat(presentation.isTypeGrayed, `is`(false))
assertThat(presentation.isTypeIconRightAligned, `is`(false))
val tailFragments = presentation.tailFragments
assertThat(tailFragments.size, `is`(1))
assertThat(tailFragments[0].text, `is`("::"))
assertThat(tailFragments[0].isGrayed, `is`(false))
assertThat(tailFragments[0].isItalic, `is`(false))
assertThat(tailFragments[0].foregroundColor, `is`(nullValue()))
}
@Test
@DisplayName("handle insert")
fun handleInsert() {
val lookup: LookupElement = XPathKeywordLookup("descendant", XPathInsertText.AXIS_MARKER)
val context = handleInsert("descendant", 'd', lookup, 10)
assertThat(context.document.text, `is`("descendant::"))
assertThat(context.editor.caretModel.offset, `is`(12))
}
@Test
@DisplayName("handle insert with ':' after the inserted text")
fun handleInsert_colonAfter() {
val lookup: LookupElement = XPathKeywordLookup("descendant", XPathInsertText.AXIS_MARKER)
val context = handleInsert("descendant:", 'd', lookup, 10)
assertThat(context.document.text, `is`("descendant::"))
assertThat(context.editor.caretModel.offset, `is`(12))
}
@Test
@DisplayName("handle insert with '::' after the inserted text")
fun handleInsert_axisSpecifierAfter() {
val lookup: LookupElement = XPathKeywordLookup("descendant", XPathInsertText.AXIS_MARKER)
val context = handleInsert("descendant::", 'd', lookup, 10)
assertThat(context.document.text, `is`("descendant::"))
assertThat(context.editor.caretModel.offset, `is`(12))
}
}
@Nested
@DisplayName("XPath 3.1 EBNF (82) AtomicOrUnionType")
internal inner class AtomicOrUnionType {
@Test
@DisplayName("lookup element for NCName")
fun lookupElement_ncname() {
val lookup: LookupElement = XPathAtomicOrUnionTypeLookup("string")
assertThat(lookup.toString(), `is`("string"))
assertThat(lookup.lookupString, `is`("string"))
assertThat(lookup.allLookupStrings, `is`(setOf("string")))
assertThat(lookup.`object`, `is`(sameInstance(lookup)))
assertThat(lookup.psiElement, `is`(nullValue()))
assertThat(lookup.isValid, `is`(true))
assertThat(lookup.requiresCommittedDocuments(), `is`(true))
assertThat(lookup.autoCompletionPolicy, `is`(AutoCompletionPolicy.SETTINGS_DEPENDENT))
assertThat(lookup.isCaseSensitive, `is`(true))
assertThat(lookup.isWorthShowingInAutoPopup, `is`(false))
val presentation = LookupElementPresentation()
lookup.renderElement(presentation)
// NOTE: IntelliJ 2020.2 deprecates and changes the behaviour of presentation.isReal.
assertThat(presentation.icon, `is`(sameInstance(XPathIcons.Nodes.TypeDecl)))
assertThat(presentation.typeIcon, `is`(nullValue()))
assertThat(presentation.itemText, `is`("string"))
assertThat(presentation.tailFragments, `is`(listOf()))
assertThat(presentation.tailText, `is`(nullValue()))
assertThat(presentation.typeText, `is`(nullValue()))
assertThat(presentation.isStrikeout, `is`(false))
assertThat(presentation.isItemTextBold, `is`(false))
assertThat(presentation.isItemTextItalic, `is`(false))
assertThat(presentation.isItemTextUnderlined, `is`(false))
assertThat(presentation.itemTextForeground, `is`(JBColor.foreground()))
assertThat(presentation.isTypeGrayed, `is`(false))
assertThat(presentation.isTypeIconRightAligned, `is`(false))
}
@Test
@DisplayName("lookup element for QName")
fun lookupElement_qname() {
val lookup: LookupElement = XPathAtomicOrUnionTypeLookup("integer", "xsd")
assertThat(lookup.toString(), `is`("xsd:integer"))
assertThat(lookup.lookupString, `is`("xsd:integer"))
assertThat(lookup.allLookupStrings, `is`(setOf("xsd:integer")))
assertThat(lookup.`object`, `is`(sameInstance(lookup)))
assertThat(lookup.psiElement, `is`(nullValue()))
assertThat(lookup.isValid, `is`(true))
assertThat(lookup.requiresCommittedDocuments(), `is`(true))
assertThat(lookup.autoCompletionPolicy, `is`(AutoCompletionPolicy.SETTINGS_DEPENDENT))
assertThat(lookup.isCaseSensitive, `is`(true))
assertThat(lookup.isWorthShowingInAutoPopup, `is`(false))
val presentation = LookupElementPresentation()
lookup.renderElement(presentation)
// NOTE: IntelliJ 2020.2 deprecates and changes the behaviour of presentation.isReal.
assertThat(presentation.icon, `is`(sameInstance(XPathIcons.Nodes.TypeDecl)))
assertThat(presentation.typeIcon, `is`(nullValue()))
assertThat(presentation.itemText, `is`("xsd:integer"))
assertThat(presentation.tailFragments, `is`(listOf()))
assertThat(presentation.tailText, `is`(nullValue()))
assertThat(presentation.typeText, `is`(nullValue()))
assertThat(presentation.isStrikeout, `is`(false))
assertThat(presentation.isItemTextBold, `is`(false))
assertThat(presentation.isItemTextItalic, `is`(false))
assertThat(presentation.isItemTextUnderlined, `is`(false))
assertThat(presentation.itemTextForeground, `is`(JBColor.foreground()))
assertThat(presentation.isTypeGrayed, `is`(false))
assertThat(presentation.isTypeIconRightAligned, `is`(false))
}
@Test
@DisplayName("handle insert")
fun handleInsert() {
val lookup: LookupElement = XPathAtomicOrUnionTypeLookup("integer", "xsd")
val context = handleInsert("xsd:integer", 'i', lookup, 11)
assertThat(context.document.text, `is`("xsd:integer"))
assertThat(context.editor.caretModel.offset, `is`(11))
}
}
@Nested
@DisplayName("XPath 3.1 EBNF (122) QName")
internal inner class QName {
@Test
@DisplayName("lookup element")
fun lookupElement() {
val lookup: LookupElement = XPathKeywordLookup("math", XPathInsertText.QNAME_PREFIX)
assertThat(lookup.toString(), `is`("math"))
assertThat(lookup.lookupString, `is`("math"))
assertThat(lookup.allLookupStrings, `is`(setOf("math")))
assertThat(lookup.`object`, `is`(sameInstance(lookup)))
assertThat(lookup.psiElement, `is`(nullValue()))
assertThat(lookup.isValid, `is`(true))
assertThat(lookup.requiresCommittedDocuments(), `is`(true))
assertThat(lookup.autoCompletionPolicy, `is`(AutoCompletionPolicy.SETTINGS_DEPENDENT))
assertThat(lookup.isCaseSensitive, `is`(true))
assertThat(lookup.isWorthShowingInAutoPopup, `is`(true))
val presentation = LookupElementPresentation()
lookup.renderElement(presentation)
// NOTE: IntelliJ 2020.2 deprecates and changes the behaviour of presentation.isReal.
assertThat(presentation.icon, `is`(nullValue()))
assertThat(presentation.typeIcon, `is`(nullValue()))
assertThat(presentation.itemText, `is`("math"))
assertThat(presentation.tailText, `is`(":"))
assertThat(presentation.typeText, `is`(nullValue()))
assertThat(presentation.isStrikeout, `is`(false))
assertThat(presentation.isItemTextBold, `is`(true))
assertThat(presentation.isItemTextItalic, `is`(false))
assertThat(presentation.isItemTextUnderlined, `is`(false))
assertThat(presentation.itemTextForeground, `is`(JBColor.foreground()))
assertThat(presentation.isTypeGrayed, `is`(false))
assertThat(presentation.isTypeIconRightAligned, `is`(false))
val tailFragments = presentation.tailFragments
assertThat(tailFragments.size, `is`(1))
assertThat(tailFragments[0].text, `is`(":"))
assertThat(tailFragments[0].isGrayed, `is`(false))
assertThat(tailFragments[0].isItalic, `is`(false))
assertThat(tailFragments[0].foregroundColor, `is`(nullValue()))
}
@Test
@DisplayName("handle insert")
fun handleInsert() {
val lookup: LookupElement = XPathKeywordLookup("math", XPathInsertText.QNAME_PREFIX)
val context = handleInsert("math", 'm', lookup, 4)
assertThat(context.document.text, `is`("math:"))
assertThat(context.editor.caretModel.offset, `is`(5))
}
@Test
@DisplayName("handle insert with ':' after the inserted text")
fun handleInsert_colonAfter() {
val lookup: LookupElement = XPathKeywordLookup("math", XPathInsertText.QNAME_PREFIX)
val context = handleInsert("math:", 'd', lookup, 4)
assertThat(context.document.text, `is`("math:"))
assertThat(context.editor.caretModel.offset, `is`(5))
}
}
}
| apache-2.0 | 76da7c5c67bb2c01eb3de247f66d1e3e | 47.960289 | 101 | 0.663398 | 4.797312 | false | true | false | false |
hubojane/goohara | app/src/main/kotlin/com/frap/goohara/GooPagerWatcher.kt | 1 | 1155 | package com.frap.goohara
import android.support.v4.view.ViewPager
fun ViewPager.addPagerWatcher(init: GooPagerWatcher.() -> Unit) {
addOnPageChangeListener(GooPagerWatcher().apply(init))
}
class GooPagerWatcher : ViewPager.OnPageChangeListener {
private var mScrollChangedListener: ((Int) -> Unit)? = null
private var mScrolledListener: ((Int, Float, Int) -> Unit)? = null
private var mSelectedListener: ((Int) -> Unit)? = null
override fun onPageScrollStateChanged(state: Int) {
mScrollChangedListener?.invoke(state)
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
mScrolledListener?.invoke(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) {
mSelectedListener?.invoke(position)
}
fun onPageScrollStateChanged(listener: (Int) -> Unit) {
mScrollChangedListener = listener
}
fun onPageScrolled(listener: (Int, Float, Int) -> Unit) {
mScrolledListener = listener
}
fun onPageSelected(listener: (Int) -> Unit) {
mSelectedListener = listener
}
}
| apache-2.0 | 5df7fcaddce2810ce3dcd8dab423778f | 30.216216 | 98 | 0.700433 | 4.442308 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/ui/views/HabitDirectionPickerButton.kt | 1 | 3222 | package com.habitrpg.wearos.habitica.ui.views
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.common.habitica.extensions.dpToPx
class HabitDirectionPickerButton @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
private var drawFromTop: Boolean
private var drawable: BitmapDrawable?
private val paint = Paint()
private val path = Path()
private val rect = RectF(0f, 0f, 0f, 0f)
private val bitmapRect = RectF(0f, 0f, 0f, 0f)
var mainTaskColor: Int = ContextCompat.getColor(context, R.color.watch_gray_200)
var darkerTaskColor: Int = ContextCompat.getColor(context, R.color.watch_gray_10)
var iconColor: Int = ContextCompat.getColor(context, R.color.watch_white)
private val radius = 15.dpToPx(context)
init {
paint.style = Paint.Style.FILL
paint.isAntiAlias = true
setWillNotDraw(false)
val attributes = context.theme.obtainStyledAttributes(
attrs,
R.styleable.HabitDirectionPickerButton,
0, 0
)
drawable = attributes.getDrawable(R.styleable.HabitDirectionPickerButton_drawable) as? BitmapDrawable
drawFromTop = attributes.getBoolean(R.styleable.HabitDirectionPickerButton_drawFromTop, false)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
rect.left = right.toFloat() * 0.125f
rect.right = right.toFloat() * 0.875f
if (drawFromTop) {
rect.top = -bottom.toFloat()
rect.bottom = bottom.toFloat()
} else {
rect.bottom = bottom.toFloat() / 2f
}
val middleX = width / 2f
val middleY = height / 2f
val bitmapWidthHalf = (drawable?.bitmap?.width?.toFloat() ?: 0f) / 2f
val bitmapHeightHalf = (drawable?.bitmap?.height?.toFloat() ?: 0f) / 2f
bitmapRect.left = middleX - bitmapWidthHalf
bitmapRect.top = middleY - bitmapHeightHalf
bitmapRect.right = middleX + bitmapWidthHalf
bitmapRect.bottom = middleY + bitmapHeightHalf
invalidate()
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
if (canvas == null) return
path.reset()
if (drawFromTop) {
path.addArc(rect, 0f, 180f)
} else {
path.addArc(rect, 180f, 360f)
}
paint.color = mainTaskColor
canvas.drawPath(path, paint)
val middleX = width / 2f
val middleY = height / 2f
paint.color = darkerTaskColor
canvas.drawArc(middleX - radius, middleY - radius, middleX + radius, middleY + radius, 0f, 360f, true, paint)
drawable?.let {
paint.color = iconColor
canvas.drawBitmap(it.bitmap, null, bitmapRect, paint)
}
}
} | gpl-3.0 | 00e1a8ecac50d415bbd37f2a1b1ef1de | 34.417582 | 117 | 0.66077 | 4.099237 | false | false | false | false |
google/private-compute-services | src/com/google/android/as/oss/assets/federatedcompute/NowPlayingRecognitionsPolicy_FederatedCompute.kt | 1 | 1803 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.policies.federatedcompute
/** Data policy. */
val NowPlayingRecognitionsPolicy_FederatedCompute =
flavoredPolicies(
name = "NowPlayingRecognitionsPolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
To provide usage statistics to monitor/improve Now Playing.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics, federated learning.
ALLOWED USAGES: Federated analytics.
"""
.trimIndent()
// The population is defined for Pixel 4+ devices per country. Most
// countries (besides the US) have a smaller population and hence the min
// round size is set to 500.
flavors(Flavor.ASI_PROD) { minRoundSize(minRoundSize = 500, minSecAggRoundSize = 500) }
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(NOW_PLAYING_TRACK_RECOGNITION_GENERATED_DTD, Duration.ofDays(14)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"trackId" { rawUsage(UsageType.ANY) }
}
}
| apache-2.0 | c3da597f45bc13a0a47f9e2501e154a7 | 35.795918 | 91 | 0.73655 | 4.344578 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/codegen/basics/unit4.kt | 1 | 588 | fun main(args: Array<String>) {
for (x in 0 .. 8) {
foo(x, Unit)
}
println("Done")
}
var global = 42
fun foo(x: Int, unit: Unit) {
var local = 5
val y: Unit = when (x) {
0 -> {}
1 -> local = 6
2 -> global = 43
3 -> unit
4 -> Unit
5 -> bar()
6 -> return
7 -> {
5
bar()
}
8 -> {
val z: Any = Unit
z as Unit
}
else -> throw Error()
}
if (y !== Unit) {
println("Fail at x = $x")
}
}
fun bar() {
} | apache-2.0 | f5ff3032ece25c609fab1daf08214107 | 14.918919 | 33 | 0.346939 | 3.438596 | false | false | false | false |
jiaminglu/kotlin-native | Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/SimpleBridgeGeneratorImpl.kt | 1 | 9322 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform
import org.jetbrains.kotlin.native.interop.indexer.Language
import org.jetbrains.kotlin.native.interop.indexer.NativeLibrary
import org.jetbrains.kotlin.native.interop.indexer.mapFragmentIsCompilable
class SimpleBridgeGeneratorImpl(
private val platform: KotlinPlatform,
private val pkgName: String,
private val jvmFileClassName: String,
private val libraryForCStubs: NativeLibrary,
private val kotlinScope: KotlinScope
) : SimpleBridgeGenerator {
private var nextUniqueId = 0
private val BridgedType.nativeType: String get() = when (platform) {
KotlinPlatform.JVM -> when (this) {
BridgedType.BYTE -> "jbyte"
BridgedType.SHORT -> "jshort"
BridgedType.INT -> "jint"
BridgedType.LONG -> "jlong"
BridgedType.FLOAT -> "jfloat"
BridgedType.DOUBLE -> "jdouble"
BridgedType.NATIVE_PTR -> "jlong"
BridgedType.OBJC_POINTER -> TODO()
BridgedType.VOID -> "void"
}
KotlinPlatform.NATIVE -> when (this) {
BridgedType.BYTE -> "int8_t"
BridgedType.SHORT -> "int16_t"
BridgedType.INT -> "int32_t"
BridgedType.LONG -> "int64_t"
BridgedType.FLOAT -> "float"
BridgedType.DOUBLE -> "double"
BridgedType.NATIVE_PTR -> "void*"
BridgedType.OBJC_POINTER -> "id"
BridgedType.VOID -> "void"
}
}
private inner class NativeBridge(val kotlinLines: List<String>, val nativeLines: List<String>)
override fun kotlinToNative(
nativeBacked: NativeBacked,
returnType: BridgedType,
kotlinValues: List<BridgeTypedKotlinValue>,
block: NativeCodeBuilder.(arguments: List<NativeExpression>) -> NativeExpression
): KotlinExpression {
val kotlinLines = mutableListOf<String>()
val nativeLines = mutableListOf<String>()
val kotlinFunctionName = "kniBridge${nextUniqueId++}"
val kotlinParameters = kotlinValues.withIndex().joinToString {
"p${it.index}: ${it.value.type.kotlinType.render(kotlinScope)}"
}
val callExpr = "$kotlinFunctionName(${kotlinValues.joinToString { it.value }})"
val cFunctionParameters = when (platform) {
KotlinPlatform.JVM -> mutableListOf(
"jniEnv" to "JNIEnv*",
"jclss" to "jclass"
)
KotlinPlatform.NATIVE -> mutableListOf()
}
kotlinValues.withIndex().mapTo(cFunctionParameters) {
"p${it.index}" to it.value.type.nativeType
}
val joinedCParameters = cFunctionParameters.joinToString { (name, type) -> "$type $name" }
val cReturnType = returnType.nativeType
val cFunctionHeader = when (platform) {
KotlinPlatform.JVM -> {
val funcFullName = buildString {
if (pkgName.isNotEmpty()) {
append(pkgName)
append('.')
}
append(jvmFileClassName)
append('.')
append(kotlinFunctionName)
}
val functionName = "Java_" + funcFullName.replace("_", "_1").replace('.', '_').replace("$", "_00024")
"JNIEXPORT $cReturnType JNICALL $functionName ($joinedCParameters)"
}
KotlinPlatform.NATIVE -> {
val functionName = pkgName.replace('.', '_') + "_$kotlinFunctionName"
kotlinLines.add("@SymbolName(${functionName.quoteAsKotlinLiteral()})")
"$cReturnType $functionName ($joinedCParameters)"
}
}
nativeLines.add(cFunctionHeader + " {")
buildNativeCodeLines {
val cExpr = block(cFunctionParameters.takeLast(kotlinValues.size).map { (name, _) -> name })
if (returnType != BridgedType.VOID) {
out("return ($cReturnType)$cExpr;")
}
}.forEach {
nativeLines.add(" $it")
}
if (libraryForCStubs.language == Language.OBJECTIVE_C) {
// Prevent Objective-C exceptions from passing to Kotlin:
nativeLines.add(1, "@try {")
nativeLines.add("} @catch (id e) { objc_terminate(); }")
// 'objc_terminate' will report the exception.
// TODO: consider implementing this in bitcode generator.
}
nativeLines.add("}")
val kotlinReturnType = returnType.kotlinType.render(kotlinScope)
kotlinLines.add("private external fun $kotlinFunctionName($kotlinParameters): $kotlinReturnType")
val nativeBridge = NativeBridge(kotlinLines, nativeLines)
nativeBridges.add(nativeBacked to nativeBridge)
return callExpr
}
override fun nativeToKotlin(
nativeBacked: NativeBacked,
returnType: BridgedType,
nativeValues: List<BridgeTypedNativeValue>,
block: KotlinCodeBuilder.(arguments: List<KotlinExpression>) -> KotlinExpression
): NativeExpression {
if (platform != KotlinPlatform.NATIVE) TODO()
val kotlinLines = mutableListOf<String>()
val nativeLines = mutableListOf<String>()
val kotlinFunctionName = "kniBridge${nextUniqueId++}"
val kotlinParameters = nativeValues.withIndex().map {
"p${it.index}" to it.value.type.kotlinType
}
val joinedKotlinParameters = kotlinParameters.joinToString { "${it.first}: ${it.second.render(kotlinScope)}" }
val cFunctionParameters = nativeValues.withIndex().map {
"p${it.index}" to it.value.type.nativeType
}
val joinedCParameters = cFunctionParameters.joinToString { (name, type) -> "$type $name" }
val cReturnType = returnType.nativeType
val symbolName = pkgName.replace('.', '_') + "_$kotlinFunctionName"
kotlinLines.add("@konan.internal.ExportForCppRuntime(${symbolName.quoteAsKotlinLiteral()})")
val cFunctionHeader = "$cReturnType $symbolName($joinedCParameters)"
nativeLines.add("$cFunctionHeader;")
val kotlinReturnType = returnType.kotlinType.render(kotlinScope)
kotlinLines.add("private fun $kotlinFunctionName($joinedKotlinParameters): $kotlinReturnType {")
buildKotlinCodeLines {
var kotlinExpr = block(kotlinParameters.map { (name, _) -> name })
if (returnType == BridgedType.OBJC_POINTER) {
// The Kotlin code may lose the ownership on this pointer after returning from the bridge,
// so retain the pointer and autorelease it:
kotlinExpr = "objc_retainAutoreleaseReturnValue($kotlinExpr)"
// (Objective-C does the same for returned pointers).
}
out("return $kotlinExpr")
}.forEach {
kotlinLines.add(" $it")
}
kotlinLines.add("}")
insertNativeBridge(nativeBacked, kotlinLines, nativeLines)
return "$symbolName(${nativeValues.joinToString { it.value }})"
}
override fun insertNativeBridge(nativeBacked: NativeBacked, kotlinLines: List<String>, nativeLines: List<String>) {
val nativeBridge = NativeBridge(kotlinLines, nativeLines)
nativeBridges.add(nativeBacked to nativeBridge)
}
private val nativeBridges = mutableListOf<Pair<NativeBacked, NativeBridge>>()
override fun prepare(): NativeBridges {
val includedBridges = mutableListOf<NativeBridge>()
val excludedClients = mutableSetOf<NativeBacked>()
nativeBridges.map { it.second.nativeLines }
.mapFragmentIsCompilable(libraryForCStubs)
.forEachIndexed { index, isCompilable ->
if (isCompilable) {
includedBridges.add(nativeBridges[index].second)
} else {
excludedClients.add(nativeBridges[index].first)
}
}
// TODO: exclude unused bridges.
return object : NativeBridges {
override val kotlinLines: Sequence<String>
get() = includedBridges.asSequence().flatMap { it.kotlinLines.asSequence() }
override val nativeLines: Sequence<String>
get() = includedBridges.asSequence().flatMap { it.nativeLines.asSequence() }
override fun isSupported(nativeBacked: NativeBacked): Boolean =
nativeBacked !in excludedClients
}
}
} | apache-2.0 | ca5d8cf37c47234a4f177fa79329081b | 39.359307 | 119 | 0.616606 | 4.950611 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/photoview/PhotoViewActions.kt | 2 | 2967 | package io.github.feelfreelinux.wykopmobilny.ui.modules.photoview
import android.Manifest
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore.Images
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
import io.github.feelfreelinux.wykopmobilny.utils.ClipboardHelperApi
import kotlinx.android.synthetic.main.activity_photoview.*
import java.io.File
import java.io.FileOutputStream
interface PhotoViewCallbacks {
fun shareImage()
fun getImageBitmap(): Bitmap?
fun saveImage()
}
class PhotoViewActions(val context : Context, clipboardHelperApi: ClipboardHelperApi) : PhotoViewCallbacks {
val photoView = context as PhotoViewActivity
override fun shareImage() {
val bitmap = getImageBitmap()
if ( bitmap != null && checkForWriteReadPermission()) {
val path = Images.Media.insertImage(context.contentResolver, bitmap, "title", null)
val uri = Uri.parse(path)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_STREAM, uri)
context.startActivity(intent)
}
}
override fun getImageBitmap() : Bitmap? = (photoView.image.drawable as BitmapDrawable).bitmap
override fun saveImage() {
val bitmap = getImageBitmap()
if (bitmap != null && checkForWriteReadPermission()) {
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "OtwartyWykopMobilny")
if (!file.exists()) file.mkdirs()
val pictureFile = File("""${file.absoluteFile}/${photoView.url.substringAfterLast('/')}""")
val fos = FileOutputStream(pictureFile)
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos)
fos.close()
showToastMessage("Zapisano obraz")
}
}
private fun checkForWriteReadPermission() : Boolean {
val writePermission = ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
val readPermission = ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE)
return if (writePermission == PackageManager.PERMISSION_DENIED || readPermission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(photoView, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE), 1)
false
} else true
}
private fun showToastMessage(text : String) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
}
} | mit | 73ceba4f1c787cbfbe2adf19e9320fcf | 39.657534 | 155 | 0.716549 | 4.770096 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/model/dao/CategoryStampDao.kt | 1 | 2638 | package com.sjn.stamp.model.dao
import com.sjn.stamp.model.CategoryStamp
import com.sjn.stamp.model.constant.CategoryType
import io.realm.Realm
object CategoryStampDao : BaseDao<CategoryStamp>() {
fun findAll(realm: Realm): List<CategoryStamp> =
realm.where(CategoryStamp::class.java).findAll() ?: emptyList()
fun findByName(realm: Realm, name: String, isSystem: Boolean): List<CategoryStamp> =
realm.where(CategoryStamp::class.java).equalTo("name", name).equalTo("isSystem", isSystem).findAll()
?: emptyList()
fun findCategoryStampList(realm: Realm, categoryType: CategoryType, categoryValue: String): List<CategoryStamp> =
realm.where(CategoryStamp::class.java).equalTo("type", categoryType.databaseValue).equalTo("value", categoryValue).findAll()
?: emptyList()
fun findOrCreate(realm: Realm, name: String, categoryType: CategoryType, categoryValue: String, isSystem: Boolean): CategoryStamp {
var categoryStamp: CategoryStamp? = realm.where(CategoryStamp::class.java).equalTo("name", name).equalTo("type", categoryType.databaseValue).equalTo("value", categoryValue).equalTo("isSystem", isSystem).findFirst()
if (categoryStamp == null) {
realm.beginTransaction()
categoryStamp = realm.createObject(CategoryStamp::class.java, getAutoIncrementId(realm))
categoryStamp.name = name
categoryStamp.type = categoryType.databaseValue
categoryStamp.isSystem = isSystem
categoryStamp.value = categoryValue
realm.commitTransaction()
return categoryStamp
}
return categoryStamp
}
fun create(realm: Realm, name: String?, categoryType: CategoryType, categoryValue: String, isSystem: Boolean) {
if (name == null || name.isEmpty()) {
return
}
findOrCreate(realm, name, categoryType, categoryValue, isSystem)
}
fun delete(realm: Realm, name: String, isSystem: Boolean) {
realm.beginTransaction()
realm.where(CategoryStamp::class.java).equalTo("name", name).equalTo("isSystem", isSystem).findAll().deleteAllFromRealm()
realm.commitTransaction()
}
fun delete(realm: Realm, name: String, categoryType: CategoryType, categoryValue: String, isSystem: Boolean) {
realm.beginTransaction()
realm.where(CategoryStamp::class.java).equalTo("name", name).equalTo("type", categoryType.databaseValue).equalTo("value", categoryValue).equalTo("isSystem", isSystem).findAll().deleteAllFromRealm()
realm.commitTransaction()
}
}
| apache-2.0 | a5cf36e0f73c6074a15835d6c5697ab5 | 47.851852 | 222 | 0.686505 | 4.727599 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/storage/api/DriverAndKeyConfiguratorTest.kt | 1 | 4779 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage.api
import arcs.core.common.ArcId
import arcs.core.data.CreatableStorageKey
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
import arcs.core.data.SchemaName
import arcs.core.data.SchemaRegistry
import arcs.core.storage.CapabilitiesResolver
import arcs.core.storage.DefaultDriverFactory
import arcs.core.storage.StorageKeyManager
import arcs.core.storage.keys.DatabaseStorageKey
import arcs.core.storage.keys.ForeignStorageKey
import arcs.core.storage.keys.JoinStorageKey
import arcs.core.storage.keys.RamDiskStorageKey
import arcs.core.storage.keys.VolatileStorageKey
import arcs.core.storage.referencemode.ReferenceModeStorageKey
import arcs.core.testutil.assertFor
import arcs.core.testutil.doesNotFail
import arcs.jvm.storage.database.testutil.FakeDatabaseManager
import org.junit.Before
import org.junit.Test
// Note: this is a global object that was created a long time ago as a convenience. Ideally, we'd
// remove this completely in favor of a more explicit configuration approach. Since it exists,
// this test is a best effort at encoding the expected behavior for the methods.
class DriverAndKeyConfiguratorTest {
@Before
fun setup() {
// The methods manipulate the default driver factory, capabilities resolvers map, and store key
// parser manager. Since this object isn't set up very well for testing (and thus, should be
// removed, one day), we need to manually reset the global state before each test.
DefaultDriverFactory.update()
StorageKeyManager.GLOBAL_INSTANCE.reset()
CapabilitiesResolver.reset()
SchemaRegistry.register(DUMMY_SCHEMA)
}
@Test
fun configureKeyParsersAndFactories_configuresDefaultKeyParsersAndFactories() {
DriverAndKeyConfigurator.configureKeyParsersAndFactories()
ALL_KEY_TYPES.forEach {
assertFor(it).doesNotFail {
StorageKeyManager.GLOBAL_INSTANCE.parse(it.toString())
}
}
}
@Test
fun configure_withNoDatabase_configuresDefaultsDrivers_andKeyParsers() {
DriverAndKeyConfigurator.configure(null)
ALL_NON_DB_DRIVER_KEYS.forEach {
assertFor(it).that(DefaultDriverFactory.get().willSupport(it)).isTrue()
}
ALL_DB_DRIVER_KEYS.forEach {
assertFor(it).that(DefaultDriverFactory.get().willSupport(it)).isFalse()
}
ALL_KEY_TYPES.forEach {
assertFor(it).doesNotFail {
StorageKeyManager.GLOBAL_INSTANCE.parse(it.toString())
}
}
}
@Test
fun configure_withDatabase_configuresDefaultsDrivers_andKeyParsers() {
DriverAndKeyConfigurator.configure(FakeDatabaseManager())
ALL_NON_DB_DRIVER_KEYS.map {
assertFor(it).that(DefaultDriverFactory.get().willSupport(it)).isTrue()
}
ALL_DB_DRIVER_KEYS.forEach {
assertFor(it).that(DefaultDriverFactory.get().willSupport(it)).isTrue()
}
ALL_KEY_TYPES.forEach {
assertFor(it).doesNotFail {
StorageKeyManager.GLOBAL_INSTANCE.parse(it.toString())
}
}
}
companion object {
private val DUMMY_SCHEMA = Schema(
names = setOf(SchemaName("test")),
fields = SchemaFields(emptyMap(), emptyMap()),
hash = "abc123"
)
private val DUMMY_RAMDISK_KEY = RamDiskStorageKey("dummy")
private val DUMMY_REFMODE_KEY = ReferenceModeStorageKey(DUMMY_RAMDISK_KEY, DUMMY_RAMDISK_KEY)
private val DUMMY_VOLATILE_KEY = VolatileStorageKey(ArcId.newForTest("test"), "dummy")
private val DUMMY_DB_KEY = DatabaseStorageKey.Persistent("test", "test")
private val DUMMY_MEMDB_KEY = DatabaseStorageKey.Memory("test", "test")
private val DUMMY_CREATABLE_KEY = CreatableStorageKey("test")
private val DUMMY_JOIN_KEY = JoinStorageKey(listOf(DUMMY_RAMDISK_KEY, DUMMY_RAMDISK_KEY))
private val DUMMY_FOREIGN_KEY = ForeignStorageKey("test")
// The dummy keys created above are grouped into meaningful sets to be used in the tests
// themselves. These named groups better telegraph the expected results of the helper methods
// than manually verifying storage keys in the tests bodies themselves would.
val ALL_KEY_TYPES = listOf(
DUMMY_RAMDISK_KEY,
DUMMY_REFMODE_KEY,
DUMMY_VOLATILE_KEY,
DUMMY_DB_KEY,
DUMMY_MEMDB_KEY,
DUMMY_CREATABLE_KEY,
DUMMY_JOIN_KEY,
DUMMY_FOREIGN_KEY
)
val ALL_NON_DB_DRIVER_KEYS = listOf(
DUMMY_RAMDISK_KEY,
DUMMY_VOLATILE_KEY
)
val ALL_DB_DRIVER_KEYS = listOf(
DUMMY_DB_KEY,
DUMMY_MEMDB_KEY
)
}
}
| bsd-3-clause | 5a5f0ef2e39d7570b85efa6c6cf4184d | 34.664179 | 99 | 0.73551 | 4.074169 | false | true | false | false |
JetBrains/ideavim | src/test/java/org/jetbrains/plugins/ideavim/ex/parser/ParserTest.kt | 1 | 2072 | /*
* 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 org.jetbrains.plugins.ideavim.ex.parser
import kotlin.math.pow
abstract class ParserTest {
protected val ZERO_OR_MORE_SPACES = "@#\\\$#@\\\$!j zero or more spaces @#\\\$#@\\\$!j"
protected fun getTextWithAllSpacesCombinations(text: String): List<String> {
val combinations = mutableListOf<String>()
val zeroOrMoreIndexes = text.allIndexesOf(ZERO_OR_MORE_SPACES)
return if (zeroOrMoreIndexes.isNotEmpty()) {
val allZeroOrMoreSpaceCombinations = getAllSpacesCombinations(2, zeroOrMoreIndexes.size)
for (spacesCombination in allZeroOrMoreSpaceCombinations) {
var newString = text
for (space in spacesCombination) {
newString = newString.replaceFirst(ZERO_OR_MORE_SPACES, space)
}
combinations.add(newString)
}
combinations
} else {
mutableListOf(text)
}
}
private fun getAllSpacesCombinations(base: Int, exponent: Int): List<List<String>> {
val spacesCombinations = mutableListOf<List<String>>()
var counter = 0
while (counter < base.pow(exponent)) {
val combination = mutableListOf<String>()
var binaryString = Integer.toBinaryString(counter)
val leadingZeroesCount = exponent - binaryString.length
binaryString = "0".repeat(leadingZeroesCount) + binaryString
for (byte in binaryString) {
combination.add(" ".repeat(Integer.parseInt(byte.toString())))
}
spacesCombinations.add(combination)
counter += 1
}
return spacesCombinations
}
private fun String.allIndexesOf(seq: String): List<Int> {
val indexes = mutableListOf<Int>()
var index: Int = this.indexOf(seq)
while (index >= 0) {
indexes.add(index)
index = this.indexOf(seq, index + 1)
}
return indexes
}
}
private fun Int.pow(p: Int): Int {
return this.toDouble().pow(p).toInt()
}
| mit | 51e6d0d08ee6ac3912d645c108299cb4 | 30.393939 | 94 | 0.678089 | 4.054795 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/formatters/NumberFormatter.kt | 1 | 3802 | /*
* Copyright 2019 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.formatters
import com.acornui.i18n.Locale
import com.acornui.properties.afterChange
import com.acornui.system.userInfo
import kotlin.properties.ReadWriteProperty
/**
* This class formats numbers into localized string representations.
*/
class NumberFormatter : StringFormatter<Number?>, StringParser<Double> {
var type by watched(NumberFormatType.NUMBER)
/**
* The ordered locale chain to use for formatting. If this is left null, the user's current locale will be used.
*
* See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation]
*/
var locales: List<Locale>? by watched(null)
var minIntegerDigits: Int by watched(1)
var maxIntegerDigits: Int by watched(40)
var minFractionDigits: Int by watched(0)
var maxFractionDigits: Int by watched(3)
/**
* Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.
* Default is true.
*/
var useGrouping: Boolean by watched(true)
/**
* The ISO 4217 code of the currency.
* Used only if [type] == [NumberFormatType.CURRENCY]
*/
var currencyCode: String by watched("USD")
private var formatter: dynamic = null
override fun format(value: Number?): String {
if (value == null) return ""
if (formatter == null) {
val locales = (locales ?: userInfo.systemLocale).map { it.value }
val JsNumberFormat = js("Intl.NumberFormat")
val options = js("({})")
options.minimumIntegerDigits = minIntegerDigits
options.maximumIntegerDigits = maxIntegerDigits
options.minimumFractionDigits = minFractionDigits
options.maximumFractionDigits = maxFractionDigits
options.useGrouping = useGrouping
if (type == NumberFormatType.CURRENCY) {
options.style = "currency"
options.currency = currencyCode
} else if (type == NumberFormatType.PERCENT) {
options.style = "percent"
}
formatter = JsNumberFormat(locales.toTypedArray(), options)
}
return formatter!!.format(value)
}
private fun <T> watched(initial: T): ReadWriteProperty<Any?, T> {
return afterChange(initial) {
formatter = null
}
}
override fun parse(value: String): Double? {
val thousandSeparator = format(1111).replace("1", "")
val decimalSeparator = format(1.1).replace("1", "")
return value.replace(thousandSeparator, "").replace(decimalSeparator, ".").toDoubleOrNull()
}
}
enum class NumberFormatType {
NUMBER,
CURRENCY,
PERCENT
}
fun numberFormatter(init: NumberFormatter.() -> Unit = {}): NumberFormatter {
val formatter = NumberFormatter()
formatter.init()
return formatter
}
/**
* @pstsm currencyCode the ISO 4217 code of the currency
*/
fun currencyFormatter(currencyCode: String, init: NumberFormatter.() -> Unit = {}): NumberFormatter {
return NumberFormatter().apply {
type = NumberFormatType.CURRENCY
minFractionDigits = 2
this.currencyCode = currencyCode
init()
}
}
/**
* Percent formatter will format a number as a percent value.
* E.g. 0.23 will be formatted as 23%
*/
fun percentFormatter(init: NumberFormatter.() -> Unit = {}): NumberFormatter {
return NumberFormatter().apply {
type = NumberFormatType.PERCENT
init()
}
}
| apache-2.0 | be1878c33338ed0198695a99805b92c0 | 28.937008 | 133 | 0.728564 | 3.852077 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/workers/notification/bloggingprompts/BloggingPromptsOnboardingNotificationScheduler.kt | 1 | 2082 | package org.wordpress.android.workers.notification.bloggingprompts
import org.wordpress.android.R
import org.wordpress.android.util.config.BloggingPromptsFeatureConfig
import org.wordpress.android.workers.notification.local.LocalNotification
import org.wordpress.android.workers.notification.local.LocalNotification.Type.BLOGGING_PROMPTS_ONBOARDING
import org.wordpress.android.workers.notification.local.LocalNotificationScheduler
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.inject.Inject
class BloggingPromptsOnboardingNotificationScheduler @Inject constructor(
private val localNotificationScheduler: LocalNotificationScheduler,
private val bloggingPromptsOnboardingNotificationHandler: BloggingPromptsOnboardingNotificationHandler,
private val bloggingPromptsFeatureConfig: BloggingPromptsFeatureConfig
) {
fun scheduleBloggingPromptsOnboardingNotificationIfNeeded() {
if (bloggingPromptsOnboardingNotificationHandler.shouldShowNotification()) {
val firstNotification = LocalNotification(
type = BLOGGING_PROMPTS_ONBOARDING,
delay = 3000, // TODO @RenanLukas replace with real delay
delayUnits = MILLISECONDS,
title = R.string.blogging_prompts_onboarding_notification_title,
text = R.string.blogging_prompts_onboarding_notification_text,
icon = R.drawable.ic_wordpress_white_24dp,
firstActionIcon = -1,
firstActionTitle = R.string.blogging_prompts_onboarding_notification_action,
secondActionIcon = -1,
secondActionTitle = R.string.blogging_prompts_notification_dismiss
)
if (bloggingPromptsFeatureConfig.isEnabled()) {
localNotificationScheduler.scheduleOneTimeNotification(firstNotification)
}
}
}
fun cancelBloggingPromptsOnboardingNotification() {
localNotificationScheduler.cancelScheduledNotification(BLOGGING_PROMPTS_ONBOARDING)
}
}
| gpl-2.0 | 4931cb46c758392f4d3ccc8bb9c4e7a9 | 52.384615 | 107 | 0.73487 | 5.627027 | false | true | false | false |
PKRoma/PocketHub | app/src/main/java/com/github/pockethub/android/ui/commit/CommitCompareListFragment.kt | 5 | 8415 | /*
* Copyright (c) 2015 PocketHub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pockethub.android.ui.commit
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.pockethub.android.Intents.EXTRA_BASE
import com.github.pockethub.android.Intents.EXTRA_HEAD
import com.github.pockethub.android.Intents.EXTRA_REPOSITORY
import com.github.pockethub.android.R
import com.github.pockethub.android.core.commit.CommitUtils
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.ui.base.BaseFragment
import com.github.pockethub.android.ui.item.TextItem
import com.github.pockethub.android.ui.item.commit.CommitFileHeaderItem
import com.github.pockethub.android.ui.item.commit.CommitFileLineItem
import com.github.pockethub.android.ui.item.commit.CommitItem
import com.github.pockethub.android.util.AvatarLoader
import com.github.pockethub.android.util.ToastUtils
import com.meisolsson.githubsdk.core.ServiceGenerator
import com.meisolsson.githubsdk.model.Commit
import com.meisolsson.githubsdk.model.CommitCompare
import com.meisolsson.githubsdk.model.GitHubFile
import com.meisolsson.githubsdk.model.Repository
import com.meisolsson.githubsdk.service.repositories.RepositoryCommitService
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.Item
import com.xwray.groupie.OnItemClickListener
import com.xwray.groupie.Section
import com.xwray.groupie.ViewHolder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_commit_diff_list.*
import java.text.MessageFormat
import java.util.*
import javax.inject.Inject
/**
* Fragment to display a list of commits being compared
*/
class CommitCompareListFragment : BaseFragment(), OnItemClickListener {
@Inject
lateinit var avatars: AvatarLoader
private var diffStyler: DiffStyler? = null
private var repository: Repository? = null
private var base: String? = null
private var head: String? = null
private val adapter = GroupAdapter<ViewHolder>()
private val mainSection = Section()
private val commitsSection = Section()
private val filesSection = Section()
private var compare: CommitCompare? = null
override fun onAttach(context: Context) {
super.onAttach(context)
val activity = context as Activity
repository = activity.intent.getParcelableExtra(EXTRA_REPOSITORY)
base = activity.intent.getStringExtra(EXTRA_BASE).substring(0, 7)
head = activity.intent.getStringExtra(EXTRA_HEAD).substring(0, 7)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainSection.add(commitsSection)
mainSection.add(filesSection)
adapter.add(mainSection)
adapter.setOnItemClickListener(this)
diffStyler = DiffStyler(resources)
compareCommits()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
list.layoutManager = LinearLayoutManager(activity)
list.adapter = adapter
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.fragment_commit_diff_list, container, false)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_refresh, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (!isAdded) {
return false
}
return when (item.itemId) {
R.id.m_refresh -> {
compareCommits()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun compareCommits() {
ServiceGenerator.createService(activity, RepositoryCommitService::class.java)
.compareCommits(repository!!.owner()!!.login(), repository!!.name(), base, head)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
val compareCommit = response.body()
val files = compareCommit!!.files()
diffStyler!!.setFiles(files)
Collections.sort(files, CommitFileComparator())
updateList(compareCommit)
}, { error -> ToastUtils.show(activity, R.string.error_commits_load) })
}
private fun updateList(compare: CommitCompare) {
if (!isAdded) {
return
}
this.compare = compare
pb_loading.visibility = View.GONE
list.visibility = View.VISIBLE
val commits = compare.commits()
if (!commits.isEmpty()) {
val comparingCommits = getString(R.string.comparing_commits)
val text = MessageFormat.format(comparingCommits, commits.size)
commitsSection.setHeader(
TextItem(R.layout.commit_details_header, R.id.tv_commit_summary, text)
)
val items = commits.map { CommitItem(avatars, it) }
commitsSection.update(items)
}
val files = compare.files()
if (!files.isEmpty()) {
filesSection.setHeader(
TextItem(R.layout.commit_compare_file_details_header,
R.id.tv_commit_file_summary, CommitUtils.formatStats(files))
)
filesSection.update(createFileSections(files))
}
}
private fun createFileSections(files: List<GitHubFile>): List<Section> {
return files.map { file ->
val lines = diffStyler!!.get(file.filename())
Section(CommitFileHeaderItem(activity!!, file), lines.map { CommitFileLineItem(diffStyler!!, it) })
}
}
private fun openCommit(commit: Commit) {
if (compare != null) {
val commits = compare!!.commits()
val commitPosition = commits
.takeWhile { commit !== it }
.count()
if (commitPosition < commits.size) {
val ids = commits.map { it.sha()!! }.toTypedArray()
startActivity(CommitViewActivity.createIntent(repository!!, commitPosition, *ids))
}
} else {
startActivity(CommitViewActivity.createIntent(repository!!, commit.sha()!!))
}
}
private fun openFile(file: GitHubFile) {
if (!TextUtils.isEmpty(file.filename()) && !TextUtils.isEmpty(file.sha())) {
startActivity(CommitFileViewActivity.createIntent(repository!!, head!!, file))
}
}
private fun openLine(adapter: GroupAdapter<*>, position: Int) {
var pos = position
var item: Any
while (--pos >= 0) {
item = adapter.getItem(pos)
if (item is CommitFileHeaderItem) {
openFile(item.file)
return
}
}
}
override fun onItemClick(@NonNull item: Item<*>, @NonNull view: View) {
when (item) {
is CommitItem -> openCommit(item.commit)
is CommitFileHeaderItem -> openFile(item.file)
is CommitFileLineItem -> {
val position = adapter.getAdapterPosition(item)
openLine(adapter, position)
}
}
}
}
| apache-2.0 | 928c506a604d9973e82af56c9aed12d9 | 34.357143 | 111 | 0.672252 | 4.672404 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangePropertySignatureDialog.kt | 1 | 12731 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.ui.MethodSignatureComponent
import com.intellij.refactoring.ui.RefactoringDialog
import com.intellij.ui.EditorTextField
import com.intellij.ui.SeparatorFactory
import com.intellij.ui.layout.*
import com.intellij.util.Alarm
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.intentions.AddFullQualifierIntention
import org.jetbrains.kotlin.idea.refactoring.changeSignature.*
import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangeSignatureDialog.Companion.getTypeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangeSignatureDialog.Companion.showWarningMessage
import org.jetbrains.kotlin.idea.refactoring.introduce.ui.KotlinSignatureComponent
import org.jetbrains.kotlin.idea.refactoring.validateElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtValVarKeywordOwner
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.SwingUtilities
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
import kotlin.properties.Delegates
class KotlinChangePropertySignatureDialog(
project: Project,
private val methodDescriptor: KotlinMethodDescriptor,
@NlsContexts.Command private val commandName: String?
) : RefactoringDialog(project, true) {
private val visibilityCombo = ComboBox(
arrayOf(
DescriptorVisibilities.INTERNAL,
DescriptorVisibilities.PRIVATE,
DescriptorVisibilities.PROTECTED,
DescriptorVisibilities.PUBLIC,
)
)
private val signatureUpdater = object : DocumentListener, ChangeListener, ActionListener {
private fun update() = updateSignature()
override fun documentChanged(event: DocumentEvent) = update()
override fun stateChanged(e: ChangeEvent?) = update()
override fun actionPerformed(e: ActionEvent?) = update()
}
private val kotlinPsiFactory = KtPsiFactory(project)
private val returnTypeCodeFragment = kotlinPsiFactory.createTypeCodeFragment(
methodDescriptor.returnTypeInfo.render(),
methodDescriptor.baseDeclaration,
)
private val receiverTypeCodeFragment = kotlinPsiFactory.createTypeCodeFragment(
methodDescriptor.receiverTypeInfo.render(),
methodDescriptor.baseDeclaration,
)
private val receiverDefaultValueCodeFragment = kotlinPsiFactory.createExpressionCodeFragment(
"",
methodDescriptor.baseDeclaration,
)
private val nameField = EditorTextField(methodDescriptor.name).apply { addDocumentListener(signatureUpdater) }
private val name: String get() = nameField.text.quoteIfNeeded()
private val returnTypeField = createKotlinEditorTextField(returnTypeCodeFragment, withListener = true)
private val receiverTypeField = createKotlinEditorTextField(receiverTypeCodeFragment, withListener = true)
private val receiverDefaultValueField = createKotlinEditorTextField(receiverDefaultValueCodeFragment, withListener = false)
private var receiverTypeCheckBox: JCheckBox? = null
private var receiverTypeLabel: JLabel by Delegates.notNull()
private var receiverDefaultValueLabel: JLabel by Delegates.notNull()
private val updateSignatureAlarm = Alarm()
private val signatureComponent: MethodSignatureComponent = KotlinSignatureComponent("", project).apply {
preferredSize = Dimension(-1, 130)
minimumSize = Dimension(-1, 130)
}
init {
title = RefactoringBundle.message("changeSignature.refactoring.name")
init()
Disposer.register(myDisposable) {
updateSignatureAlarm.cancelAllRequests()
}
}
private fun updateSignature(): Unit = SwingUtilities.invokeLater label@{
if (Disposer.isDisposed(myDisposable)) return@label
updateSignatureAlarm.cancelAllRequests()
updateSignatureAlarm.addRequest(
{ PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted { updateSignatureAlarmFired() } },
100,
ModalityState.stateForComponent(signatureComponent)
)
}
private fun updateSignatureAlarmFired() {
doUpdateSignature()
validateButtons()
}
private fun doUpdateSignature() {
signatureComponent.setSignature(calculateSignature())
}
private fun calculateSignature(): String = buildString {
methodDescriptor.baseDeclaration.safeAs<KtValVarKeywordOwner>()?.valOrVarKeyword?.let {
val visibility = visibilityCombo.selectedItem
if (visibility != DescriptorVisibilities.DEFAULT_VISIBILITY) {
append("$visibility ")
}
append("${it.text} ")
}
if (receiverTypeCheckBox?.isSelected == true && receiverTypeField.isEnabled) {
val receiverText = receiverTypeField.text
if ("->" in receiverText) {
append("($receiverText).")
} else {
append("$receiverText.")
}
}
append("$name: ${returnTypeField.text}")
}
override fun getPreferredFocusedComponent() = nameField
override fun createCenterPanel(): JComponent = panel {
if (methodDescriptor.canChangeVisibility()) {
row(KotlinBundle.message("label.text.visibility")) {
visibilityCombo.selectedItem = methodDescriptor.visibility
visibilityCombo.addActionListener(signatureUpdater)
visibilityCombo()
}
}
row(KotlinBundle.message("label.text.name")) { nameField(growX) }
row(KotlinBundle.message("label.text.type")) { returnTypeField(growX) }
if (methodDescriptor.baseDeclaration is KtProperty) {
fun updateReceiverUI(receiverComboBox: JCheckBox) {
val withReceiver = receiverComboBox.isSelected
receiverTypeLabel.isEnabled = withReceiver
receiverTypeField.isEnabled = withReceiver
receiverDefaultValueLabel.isEnabled = withReceiver
receiverDefaultValueField.isEnabled = withReceiver
}
val receiverTypeCheckBox = JCheckBox(KotlinBundle.message("checkbox.text.extension.property")).apply {
addActionListener { updateReceiverUI(this) }
addActionListener(signatureUpdater)
isSelected = methodDescriptor.receiver != null
}
row { receiverTypeCheckBox() }
[email protected] = receiverTypeCheckBox
receiverTypeLabel = JLabel(KotlinBundle.message("label.text.receiver.type"))
row(receiverTypeLabel) { receiverTypeField(growX) }
receiverDefaultValueLabel = JLabel(KotlinBundle.message("label.text.default.receiver.value"))
if (methodDescriptor.receiver == null) {
row(receiverDefaultValueLabel) { receiverDefaultValueField(growX) }
}
updateReceiverUI(receiverTypeCheckBox)
}
row { SeparatorFactory.createSeparator(RefactoringBundle.message("signature.preview.border.title"), null)(growX) }
row { signatureComponent(grow) }
updateSignature()
}
private fun createKotlinEditorTextField(file: PsiFile, withListener: Boolean): EditorTextField = EditorTextField(
PsiDocumentManager.getInstance(myProject).getDocument(file),
myProject,
KotlinFileType.INSTANCE
).apply {
if (withListener) addDocumentListener(signatureUpdater)
}
override fun canRun() {
if (!name.isIdentifier()) {
throw ConfigurationException(KotlinBundle.message("error.text.invalid.name"))
}
returnTypeCodeFragment.validateElement(KotlinBundle.message("error.text.invalid.return.type"))
if (receiverTypeCheckBox?.isSelected == true) {
receiverTypeCodeFragment.validateElement(KotlinBundle.message("error.text.invalid.receiver.type"))
}
}
private fun evaluateKotlinChangeInfo(): KotlinChangeInfo {
val originalDescriptor = methodDescriptor.original
val receiver = if (receiverTypeCheckBox?.isSelected == true) {
originalDescriptor.receiver ?: KotlinParameterInfo(
callableDescriptor = originalDescriptor.baseDescriptor,
name = "receiver",
defaultValueForCall = receiverDefaultValueCodeFragment.getContentElement(),
)
} else null
receiver?.currentTypeInfo = receiverTypeCodeFragment.getTypeInfo(isCovariant = false, forPreview = false)
return KotlinChangeInfo(
originalDescriptor,
name,
returnTypeCodeFragment.getTypeInfo(isCovariant = false, forPreview = false),
visibilityCombo.selectedItem as DescriptorVisibility,
emptyList(),
receiver,
originalDescriptor.method,
checkUsedParameters = true,
)
}
override fun doAction() {
val changeInfo = evaluateKotlinChangeInfo()
val typeInfo = changeInfo.newReturnTypeInfo
if (typeInfo.type == null && !showWarningMessage(
myProject,
KotlinBundle.message("message.text.property.type.cannot.be.resolved", typeInfo.render()),
)
) return
val receiverParameterInfo = changeInfo.receiverParameterInfo
val receiverTypeInfo = receiverParameterInfo?.currentTypeInfo
if (receiverTypeInfo != null && receiverTypeInfo.type == null && !showWarningMessage(
myProject,
KotlinBundle.message("message.text.property.receiver.type.cannot.be.resolved", receiverTypeInfo.render()),
)
) return
receiverParameterInfo?.let { normalizeReceiver(it, withCopy = false) }
invokeRefactoring(KotlinChangeSignatureProcessor(myProject, changeInfo, commandName ?: title))
}
override fun getHelpId(): String = "refactoring.changeSignature"
companion object {
fun createProcessorForSilentRefactoring(
project: Project,
@NlsContexts.Command commandName: String,
descriptor: KotlinMethodDescriptor
): BaseRefactoringProcessor {
val originalDescriptor = descriptor.original
val changeInfo = KotlinChangeInfo(methodDescriptor = originalDescriptor, context = originalDescriptor.method)
changeInfo.newName = descriptor.name
changeInfo.receiverParameterInfo = descriptor.receiver?.also { normalizeReceiver(it, withCopy = true) }
return KotlinChangeSignatureProcessor(project, changeInfo, commandName)
}
private fun normalizeReceiver(receiver: KotlinParameterInfo, withCopy: Boolean) {
val defaultValue = receiver.defaultValueForCall ?: return
val newElement = if (withCopy) {
val fragment = KtPsiFactory(defaultValue.project).createExpressionCodeFragment(defaultValue.text, defaultValue)
fragment.getContentElement() ?: return
} else {
defaultValue
}
receiver.defaultValueForCall = AddFullQualifierIntention.addQualifiersRecursively(newElement) as? KtExpression
}
}
}
| apache-2.0 | 4bd21ea6c710f74b2b9747020d320855 | 41.86532 | 158 | 0.713534 | 5.653197 | false | false | false | false |
Yubico/yubioath-android | app/src/main/kotlin/com/yubico/yubioath/keystore/KeyStoreProvider.kt | 1 | 2429 | package com.yubico.yubioath.keystore
import android.os.Build
import android.security.keystore.KeyProperties
import android.security.keystore.KeyProtection
import androidx.annotation.RequiresApi
import java.security.KeyStore
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
@RequiresApi(Build.VERSION_CODES.M)
class KeyStoreProvider : KeyProvider {
private val keystore = KeyStore.getInstance("AndroidKeyStore")
private val entries = hashMapOf<String, MutableSet<String>>()
init {
keystore.load(null)
keystore.aliases().asSequence().map {
it.split(',', limit = 2)
}.forEach {
entries.getOrPut(it[0], { mutableSetOf() }).add(it[1])
}
}
override fun hasKeys(deviceId: String): Boolean = !entries[deviceId].orEmpty().isEmpty()
override fun getKeys(deviceId: String): Sequence<StoredSigner> {
return entries[deviceId].orEmpty().sorted().asSequence().map {
KeyStoreStoredSigner(deviceId, it)
}
}
override fun addKey(deviceId: String, secret: ByteArray) {
val keys = entries.getOrPut(deviceId, { mutableSetOf() })
val secretId = (0..keys.size).map { "$it" }.find { !keys.contains(it) } ?: throw RuntimeException() // Can't happen
val alias = "$deviceId,$secretId"
keystore.setEntry(alias, KeyStore.SecretKeyEntry(SecretKeySpec(secret, KeyProperties.KEY_ALGORITHM_HMAC_SHA1)), KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build())
keys.add(secretId)
}
override fun clearKeys(deviceId: String) {
entries.remove(deviceId).orEmpty().forEach {
keystore.deleteEntry("$deviceId,$it")
}
}
override fun clearAll() {
keystore.aliases().asSequence().forEach { keystore.deleteEntry(it) }
entries.clear()
}
private inner class KeyStoreStoredSigner(val deviceId: String, val secretId: String) : StoredSigner {
val mac: Mac = Mac.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA1).apply {
init(keystore.getKey("$deviceId,$secretId", null))
}
override fun sign(input: ByteArray): ByteArray = mac.doFinal(input)
override fun promote() {
entries[deviceId].orEmpty().filter { it != secretId }.forEach {
keystore.deleteEntry("$deviceId,$it")
}
entries[deviceId] = mutableSetOf(secretId)
}
}
} | bsd-2-clause | 2e933e9180f1bb642653760649a05e00 | 35.268657 | 178 | 0.659531 | 4.416364 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/util/ObfuscatedTrip.kt | 1 | 2840 | /*
* ObfuscatedTrip.kt
*
* Copyright 2017 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.util
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
/**
* Special wrapper for Trip that handles obfuscation of Trip data.
*/
@Parcelize
internal class ObfuscatedTrip (
override val startTimestamp: Timestamp?,
override val endTimestamp: Timestamp?,
override val routeName: FormattedString?,
override val startStation: Station?,
override val mode: Trip.Mode,
override val endStation: Station?,
override val fare: TransitCurrency?,
override val humanReadableRouteID: String?,
override val vehicleID: String?,
override val machineID: String?,
override val passengerCount: Int,
private val mAgencyName: FormattedString?,
private val mShortAgencyName: FormattedString?
): Trip() {
constructor(realTrip: Trip, timeDelta: Long, obfuscateFares: Boolean) : this (
routeName = realTrip.routeName,
mAgencyName = realTrip.getAgencyName(false),
mShortAgencyName = realTrip.getAgencyName(true),
startStation = realTrip.startStation,
endStation = realTrip.endStation,
mode = realTrip.mode,
passengerCount = realTrip.passengerCount,
vehicleID = realTrip.vehicleID,
machineID = realTrip.machineID,
humanReadableRouteID = realTrip.humanReadableRouteID,
fare = realTrip.fare?.let {
if (obfuscateFares)
it.obfuscate()
else
it
},
startTimestamp = realTrip.startTimestamp?.obfuscateDelta(timeDelta),
endTimestamp = realTrip.endTimestamp?.obfuscateDelta(timeDelta)
)
override fun getAgencyName(isShort: Boolean) =
if (isShort) mShortAgencyName else mAgencyName
}
| gpl-3.0 | a2168cbd73c2ee8478c1ad4c9b68095c | 38.444444 | 82 | 0.691197 | 4.544 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/test/kotlin/diskmap/NamedObjectMapTest.kt | 1 | 5654 | package diskmap
import com.onyx.diskmap.factory.impl.DefaultDiskMapFactory
import database.base.DatabaseBaseTest
import entities.EntityYo
import org.junit.BeforeClass
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Created by timothy.osborn on 4/2/15.
*/
class NamedObjectMapTest {
companion object {
private val TEST_DATABASE = "C:/Sandbox/Onyx/Tests/namedObjectMapTest.db"
@BeforeClass
@JvmStatic
fun beforeTest() = DatabaseBaseTest.deleteDatabase(TEST_DATABASE)
}
@Test
fun testPushObject() {
val store = DefaultDiskMapFactory(TEST_DATABASE)
val myMap = store.getHashMap<MutableMap<String, EntityYo>>(String::class.java, "objectos")
val entityYo = EntityYo()
entityYo.id = "OOO, this is an id"
entityYo.longValue = 23L
entityYo.dateValue = Date(1433233222)
entityYo.longStringValue = "This is a really long string key wooo, long string textThis is a really long string key wooo, long string textThis is a really long string key wooo, long string textThis is a really long string key wooo, long string textThis is a really long string key wooo, long string textThis is a really long string key wooo, long string text"
entityYo.otherStringValue = "Normal text"
entityYo.mutableInteger = 23
entityYo.mutableLong = 42L
entityYo.mutableBoolean = false
entityYo.mutableFloat = 23.2f
entityYo.mutableDouble = 23.1
entityYo.immutableInteger = 77
entityYo.immutableLong = 653356L
entityYo.immutableBoolean = true
entityYo.immutableFloat = 23.45f
entityYo.immutableDouble = 232.232
myMap.put(entityYo.id!!, entityYo)
val another = myMap[entityYo.id!!]
assertEquals(entityYo.id, another!!.id)
assertEquals(entityYo.longValue, another.longValue)
assertEquals(entityYo.dateValue, another.dateValue)
assertEquals(entityYo.longStringValue, another.longStringValue)
assertEquals(entityYo.otherStringValue, another.otherStringValue)
assertEquals(entityYo.mutableInteger, another.mutableInteger)
assertEquals(entityYo.mutableLong, another.mutableLong)
assertEquals(entityYo.mutableBoolean, another.mutableBoolean)
assertEquals(entityYo.mutableFloat, another.mutableFloat)
assertEquals(entityYo.mutableDouble, another.mutableDouble)
assertEquals(entityYo.immutableInteger, another.immutableInteger)
assertEquals(entityYo.immutableLong, another.immutableLong)
assertEquals(entityYo.immutableBoolean, another.immutableBoolean)
assertEquals(entityYo.immutableFloat, another.immutableFloat)
assertEquals(entityYo.immutableDouble, another.immutableDouble)
}
@Test
fun testNullObject() {
val store = DefaultDiskMapFactory(TEST_DATABASE)
val myMap = store.getHashMap<MutableMap<String, EntityYo>>(String::class.java, "objectos")
val entityYo = EntityYo()
entityYo.id = "OOO, this is an id"
myMap.put(entityYo.id!!, entityYo)
val another = myMap[entityYo.id!!]
assertEquals(entityYo.id, another!!.id)
assertNull(entityYo.dateValue)
assertNull(entityYo.longStringValue)
assertNull(entityYo.otherStringValue)
assertNull(entityYo.mutableInteger)
assertNull(entityYo.mutableLong)
assertNull(entityYo.mutableBoolean)
assertNull(entityYo.mutableFloat)
assertNull(entityYo.mutableDouble)
assertEquals(0, entityYo.immutableInteger)
assertEquals(0L, entityYo.immutableLong)
assertEquals(false, entityYo.immutableBoolean)
assertEquals(0.0f, entityYo.immutableFloat)
assertEquals(0.0, entityYo.immutableDouble)
}
@Test
fun testSet() {
val store = DefaultDiskMapFactory(TEST_DATABASE)
val myMap = store.getHashMap<MutableMap<String, List<*>>>(String::class.java, "objectos")
val list = ArrayList<String>()
list.add("HIYA1")
list.add("HIYA2")
list.add("HIYA3")
list.add("HIYA4")
list.add("HIYA5")
myMap.put("FIRST", list)
val list2 = myMap["FIRST"]
assertEquals(list2!!.size, list.size)
assertEquals(list2[0], "HIYA1")
assertEquals(list2[4], "HIYA5")
assertTrue(list2 is ArrayList<*>)
}
@Test
fun testHashSet() {
val store = DefaultDiskMapFactory(TEST_DATABASE)
val myMap = store.getHashMap<MutableMap<String, Set<*>>>(String::class.java, "objectos")
val list = HashSet<String>()
list.add("HIYA1")
list.add("HIYA2")
list.add("HIYA3")
list.add("HIYA4")
list.add("HIYA5")
list.add("HIYA2")
myMap.put("FIRST", list)
val list2 = myMap["FIRST"]
assertEquals(list2!!.size, list.size)
assertTrue(list2 is HashSet<*>)
}
@Test
fun testMap() {
val store = DefaultDiskMapFactory(TEST_DATABASE)
val myMap = store.getHashMap<MutableMap<String, Map<*, *>>>(String::class.java, "objectos")
val list = HashMap<String, Int>()
list.put("HIYA1", 1)
list.put("HIYA2", 2)
list.put("HIYA3", 3)
list.put("HIYA4", 4)
list.put("HIYA5", 5)
list.put("HIYA2", 6)
myMap.put("FIRST", list)
val list2 = myMap["FIRST"]
assertEquals(list2!!.size, list.size)
assertTrue(list2 is HashMap<*, *>)
assertEquals(6, list2["HIYA2"])
}
}
| agpl-3.0 | 2ef98bded4fcf3eef5b9c0a3c52d4e8b | 33.266667 | 367 | 0.665723 | 3.875257 | false | true | false | false |
GunoH/intellij-community | platform/inspect/src/com/intellij/codeInspection/inspectionProfile/ProfileMigrationUtils.kt | 2 | 806 | // 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.codeInspection.inspectionProfile
import org.jdom.Element
object ProfileMigrationUtils {
fun readXmlOptions(element: Element): Map<String, String> {
return element.children.filter { it.name == "option" }.associate { node ->
val name = node.getAttributeValue("name")
val value = node.getAttributeValue("value")
name to value
}
}
fun writeXmlOptions(element: Element, options: Map<String, *>) {
options.forEach { (key, value) ->
val child = Element("option")
element.addContent(child)
if (value is String) {
child.setAttribute("name", key)
child.setAttribute("value", value)
}
}
}
} | apache-2.0 | 91574161d6fb52f31490cec4a80d76c3 | 31.28 | 120 | 0.673697 | 4.070707 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/caches/resolve/MultiModuleHighlightingTest.kt | 1 | 13216 | // 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.caches.resolve
import com.intellij.facet.FacetManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.impl.PsiModificationTrackerImpl
import com.intellij.psi.util.PsiModificationTracker
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.ResolverForModuleComputationTracker
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.ResolutionAnchorCacheService
import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.withLibraryToSourceAnalysis
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.caches.trackers.KotlinModuleOutOfCodeBlockModificationTracker
import org.jetbrains.kotlin.idea.completion.test.withComponentRegistered
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.facet.KotlinFacetConfiguration
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.idea.test.allKotlinFiles
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.idea.util.projectStructure.sdk
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverPluginNames.ANNOTATION_OPTION_NAME
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverPluginNames.PLUGIN_ID
import org.jetbrains.kotlin.test.util.ResolverTracker
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.junit.Assert.assertNotEquals
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import java.io.File
import java.util.concurrent.ThreadLocalRandom
import kotlin.math.absoluteValue
@RunWith(JUnit38ClassRunner::class)
open class MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("multiModuleHighlighting")
fun testVisibility() {
val module1 = module("m1")
val module2 = module("m2")
module2.addDependency(module1)
checkHighlightingInProject()
}
fun testDependency() {
val module1 = module("m1")
val module2 = module("m2")
val module3 = module("m3")
val module4 = module("m4")
module2.addDependency(module1)
module1.addDependency(module2)
module3.addDependency(module2)
module4.addDependency(module1)
module4.addDependency(module2)
module4.addDependency(module3)
checkHighlightingInProject()
}
fun testLazyResolvers() {
val tracker = ResolverTracker()
project.withComponentRegistered<ResolverForModuleComputationTracker, Unit>(tracker) {
val module1 = module("m1")
val module2 = module("m2")
val module3 = module("m3")
module3.addDependency(module2)
module3.addDependency(module1)
assertTrue(module1 !in tracker.moduleResolversComputed)
assertTrue(module2 !in tracker.moduleResolversComputed)
assertTrue(module3 !in tracker.moduleResolversComputed)
checkHighlightingInProject { project.allKotlinFiles().filter { "m3" in it.name } }
assertTrue(module1 in tracker.moduleResolversComputed)
assertTrue(module2 !in tracker.moduleResolversComputed)
assertTrue(module3 in tracker.moduleResolversComputed)
}
}
fun testRecomputeResolversOnChange() {
val tracker = ResolverTracker()
project.withComponentRegistered<ResolverForModuleComputationTracker, Unit>(tracker) {
val module1 = module("m1")
val module2 = module("m2")
val module3 = module("m3")
module2.addDependency(module1)
module3.addDependency(module2)
// Ensure modules have the same SDK instance, and not two distinct SDKs with the same path
ModuleRootModificationUtil.setModuleSdk(module2, module1.sdk)
assertEquals(0, tracker.sdkResolversComputed.size)
checkHighlightingInProject { project.allKotlinFiles().filter { "m2" in it.name } }
assertEquals(1, tracker.sdkResolversComputed.size)
assertEquals(2, tracker.moduleResolversComputed.size)
tracker.clear()
val module1ModTracker = KotlinModuleOutOfCodeBlockModificationTracker(module1)
val module2ModTracker = KotlinModuleOutOfCodeBlockModificationTracker(module2)
val module3ModTracker = KotlinModuleOutOfCodeBlockModificationTracker(module3)
val m2ContentRoot = ModuleRootManager.getInstance(module1).contentRoots.single()
val m1 = m2ContentRoot.findChild("m1.kt")!!
val m1doc = FileDocumentManager.getInstance().getDocument(m1)!!
project.executeWriteCommand("a") {
m1doc.insertString(m1doc.textLength, "fun foo() = 1")
PsiDocumentManager.getInstance(myProject).commitAllDocuments()
}
// Internal counters should be ready after modifications in m1
val afterFirstModification = KotlinModuleOutOfCodeBlockModificationTracker.getModificationCount(module1)
assertEquals(afterFirstModification, module1ModTracker.modificationCount)
assertEquals(afterFirstModification, module2ModTracker.modificationCount)
assertEquals(afterFirstModification, module3ModTracker.modificationCount)
val m1ContentRoot = ModuleRootManager.getInstance(module2).contentRoots.single()
val m2 = m1ContentRoot.findChild("m2.kt")!!
val m2doc = FileDocumentManager.getInstance().getDocument(m2)!!
project.executeWriteCommand("a") {
m2doc.insertString(m2doc.textLength, "fun foo() = 1")
PsiDocumentManager.getInstance(myProject).commitAllDocuments()
}
val currentModCount = KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker.modificationCount
// Counter for m1 module should be unaffected by modification in m2
assertEquals(afterFirstModification, KotlinModuleOutOfCodeBlockModificationTracker.getModificationCount(module1))
assertEquals(afterFirstModification, module1ModTracker.modificationCount)
// Counters for m2 and m3 should be changed
assertNotEquals(afterFirstModification, currentModCount)
assertEquals(currentModCount, module2ModTracker.modificationCount)
assertEquals(currentModCount, module3ModTracker.modificationCount)
checkHighlightingInProject { project.allKotlinFiles().filter { "m2" in it.name } }
assertEquals(0, tracker.sdkResolversComputed.size)
assertEquals(2, tracker.moduleResolversComputed.size)
tracker.clear()
ApplicationManager.getApplication().runWriteAction {
(PsiModificationTracker.getInstance(myProject) as PsiModificationTrackerImpl).incOutOfCodeBlockModificationCounter()
}
checkHighlightingInProject { project.allKotlinFiles().filter { "m2" in it.name } }
assertEquals(0, tracker.sdkResolversComputed.size)
assertEquals(2, tracker.moduleResolversComputed.size)
}
}
fun testTestRoot() {
val module1 = module("m1", hasTestRoot = true)
val module2 = module("m2", hasTestRoot = true)
val module3 = module("m3", hasTestRoot = true)
module3.addDependency(module1, dependencyScope = DependencyScope.TEST)
module3.addDependency(module2, dependencyScope = DependencyScope.TEST)
module2.addDependency(module1, dependencyScope = DependencyScope.COMPILE)
checkHighlightingInProject()
}
fun testLanguageVersionsViaFacets() {
val m1 = module("m1").setupKotlinFacet {
settings.languageLevel = LanguageVersion.KOTLIN_1_1
}
val m2 = module("m2").setupKotlinFacet {
settings.languageLevel = LanguageVersion.KOTLIN_1_0
}
m1.addDependency(m2)
m2.addDependency(m1)
checkHighlightingInProject()
}
fun testSamWithReceiverExtension() {
val module1 = module("m1").setupKotlinFacet {
settings.compilerArguments!!.pluginOptions =
arrayOf("plugin:$PLUGIN_ID:${ANNOTATION_OPTION_NAME}=anno.A")
}
val module2 = module("m2").setupKotlinFacet {
settings.compilerArguments!!.pluginOptions =
arrayOf("plugin:$PLUGIN_ID:${ANNOTATION_OPTION_NAME}=anno.B")
}
module1.addDependency(module2)
module2.addDependency(module1)
checkHighlightingInProject()
}
fun testResolutionAnchorsAndBuiltins() {
val jarForCompositeLibrary = KotlinCompilerStandalone(
sources = listOf(File("$testDataPath${getTestName(true)}/compositeLibraryPart"))
).compile()
val stdlibJarForCompositeLibrary = TestKotlinArtifacts.kotlinStdlib
val jarForSourceDependentLibrary = KotlinCompilerStandalone(
sources = listOf(File("$testDataPath${getTestName(true)}/sourceDependentLibrary"))
).compile()
val dependencyModule = module("dependencyModule")
val anchorModule = module("anchor")
val sourceModule = module("sourceModule")
val sourceDependentLibraryName = "sourceDependentLibrary"
sourceModule.addMultiJarLibrary(listOf(stdlibJarForCompositeLibrary, jarForCompositeLibrary), "compositeLibrary")
sourceModule.addLibrary(jarForSourceDependentLibrary, sourceDependentLibraryName)
anchorModule.addDependency(dependencyModule)
val anchorMapping = mapOf(sourceDependentLibraryName to anchorModule.name)
withResolutionAnchors(anchorMapping) {
checkHighlightingInProject()
dependencyModule.modifyTheOnlySourceFile()
checkHighlightingInProject()
}
}
private fun withResolutionAnchors(anchors: Map<String, String>, block: () -> Unit) {
val resolutionAnchorService = ResolutionAnchorCacheService.getInstance(project).safeAs<ResolutionAnchorCacheServiceImpl>()
?: error("Anchor service missing")
val oldResolutionAnchorMappingState = resolutionAnchorService.state
try {
resolutionAnchorService.setAnchors(anchors)
project.withLibraryToSourceAnalysis {
block()
}
} finally {
resolutionAnchorService.loadState(oldResolutionAnchorMappingState)
}
}
private fun Module.modifyTheOnlySourceFile() {
val sourceRoot = sourceRoots.singleOrNull() ?: error("Expected single source root in a test module")
assert(sourceRoot.isDirectory) { "Source root of a test module is not a directory" }
val ktFile = sourceRoot.children.singleOrNull()?.toPsiFile(project) as? KtFile
?: error("Expected single .kt file in a test source module")
val stubFunctionName = "fn${System.currentTimeMillis()}_${ThreadLocalRandom.current().nextInt().toLong().absoluteValue}"
WriteCommandAction.runWriteCommandAction(project) {
ktFile.add(
KtPsiFactory(project).createFunction("fun $stubFunctionName() {}")
)
}
}
private fun Module.setupKotlinFacet(configure: KotlinFacetConfiguration.() -> Unit) = apply {
runWriteAction {
val facet = FacetManager.getInstance(this).addFacet(KotlinFacetType.INSTANCE, KotlinFacetType.NAME, null)
val configuration = facet.configuration
// this is actually needed so facet settings object is in a valid state
configuration.settings.compilerArguments = K2JVMCompilerArguments()
// make sure module-specific settings are used
configuration.settings.useProjectSettings = false
configuration.configure()
}
}
}
| apache-2.0 | 3046b3f755f41b9b4062ed196026903a | 43.498316 | 136 | 0.723139 | 5.120496 | false | true | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseData.kt | 7 | 2887 | // 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.codeInsight.navigation
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.navigation.BaseCtrlMouseInfo.getReferenceRanges
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.lang.documentation.psi.isNavigatableQuickDoc
import com.intellij.lang.documentation.psi.psiDocumentationTarget
import com.intellij.lang.documentation.symbol.impl.symbolDocumentationTarget
import com.intellij.model.Symbol
import com.intellij.model.psi.PsiSymbolService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts.HintText
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus.Internal
/**
* @param ranges absolute ranges to highlight
* @param isNavigatable whether to apply link highlighting
* @param hintText HTML of the hint
* @param target target, which generated the [hintText], or `null` if [hintText] is a simple message; used to resolve links in [hintText]
*/
@Internal
class CtrlMouseData(
val ranges: List<TextRange>,
val isNavigatable: Boolean,
val hintText: @HintText String?,
val target: DocumentationTarget?,
)
internal fun rangeOnlyCtrlMouseData(ranges: List<TextRange>): CtrlMouseData = CtrlMouseData(
ranges,
isNavigatable = true,
hintText = null,
target = null,
)
internal fun multipleTargetsCtrlMouseData(ranges: List<TextRange>): CtrlMouseData = CtrlMouseData(
ranges,
isNavigatable = true,
hintText = CodeInsightBundle.message("multiple.implementations.tooltip"),
target = null,
)
internal fun symbolCtrlMouseData(
project: Project,
symbol: Symbol,
elementAtOffset: PsiElement,
ranges: List<TextRange>,
declared: Boolean,
): CtrlMouseData {
val psi = PsiSymbolService.getInstance().extractElementFromSymbol(symbol)
if (psi != null) {
return targetCtrlMouseData(
ranges,
isNavigatable = declared || isNavigatableQuickDoc(elementAtOffset, psi),
target = psiDocumentationTarget(psi, elementAtOffset)
)
}
return targetCtrlMouseData(
ranges,
true, // non-PSI are always navigatable
target = symbolDocumentationTarget(project, symbol),
)
}
internal fun psiCtrlMouseData(
leafElement: PsiElement,
targetElement: PsiElement,
): CtrlMouseData {
return targetCtrlMouseData(
ranges = getReferenceRanges(leafElement),
isNavigatable = isNavigatableQuickDoc(leafElement, targetElement),
target = psiDocumentationTarget(targetElement, leafElement)
)
}
internal fun targetCtrlMouseData(
ranges: List<TextRange>,
isNavigatable: Boolean,
target: DocumentationTarget?,
): CtrlMouseData = CtrlMouseData(
ranges,
isNavigatable,
target?.computeDocumentationHint(),
target,
)
| apache-2.0 | 6eecdcbdb25eb7cb614419d88a78a402 | 31.438202 | 137 | 0.784551 | 4.427914 | false | false | false | false |
DeskChan/DeskChan | src/main/kotlin/info/deskchan/core/LoaderManager.kt | 2 | 2878 | package info.deskchan.core
import java.io.FilenameFilter
typealias PluginFiles = Set<Path>
object LoaderManager {
/** Extensions that registered loaders can interpret as plugin. **/
private val registeredExtensions = mutableSetOf<String>()
/** 'plugins' path. **/
private val pluginsDirPath = PluginManager.getPluginsDirPath()
/** Scan plugins directory to runnable plugins. **/
private fun scanPluginsDir(): PluginFiles {
val loadedPlugins = PluginManager.getInstance().namesOfLoadedPlugins
return pluginsDirPath.files(FilenameFilter { _, name -> !loadedPlugins.contains(name) })
}
/** Automatically load all plugins from 'plugin' directory. **/
internal fun loadPlugins() {
var unloadedPlugins = scanPluginsDir()
var loaderCount: Int
do {
loaderCount = registeredExtensions.size
unloadedPlugins = unloadedPlugins
.loadFilePlugins()
.loadDirectoryPlugins()
} while (unloadedPlugins.isNotEmpty() && loaderCount != registeredExtensions.size )
unloadedPlugins
.loadRestPlugins()
.forEach { PluginManager.log("Could not match loader for plugin ${it.name}") }
}
/** Iterates over all registered extensions to find loadable plugins. **/
private fun PluginFiles.loadFilePlugins(): PluginFiles {
val unloadedPlugins = this.toMutableSet()
val extensions = registeredExtensions
extensions.forEach { ext ->
this.filter { it.extension == ext }.forEach { unloadedPlugins.tryLoadPlugin(it) }
}
return unloadedPlugins
}
/** Iterates over all first level directories to find loadable plugins. **/
private fun PluginFiles.loadDirectoryPlugins(): PluginFiles {
val unloadedPlugins = this.toMutableSet()
val (loaders, plugins) = this
.filter { it.isDirectory }
.partition { it.name.endsWith("support") || it.name.endsWith("loader") }
(loaders + plugins).forEach { unloadedPlugins.tryLoadPlugin(it) }
return unloadedPlugins
}
/** Tries to load all plugins that wasn't loaded previously. **/
private fun PluginFiles.loadRestPlugins(): PluginFiles {
val unloadedPlugins = this.toMutableSet()
this.forEach { unloadedPlugins.tryLoadPlugin(it) }
return unloadedPlugins
}
/** Tries to load plugin that wasn't loaded previously. **/
private fun MutableSet<Path>.tryLoadPlugin(file: Path) {
if (PluginManager.getInstance().tryLoadPluginByPath(file)) {
this.remove(file)
}
}
fun registerExtensions(vararg extensions: String) = registeredExtensions.addAll(extensions)
fun registerExtensions(extensions: List<String>) = registerExtensions(*extensions.toTypedArray())
}
| lgpl-3.0 | 159d4b8b8d8e5f1b1778333675246e3c | 37.373333 | 101 | 0.662265 | 5.057996 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/my/MyStoriesItem.kt | 1 | 7983 | package org.thoughtcrime.securesms.stories.my
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.menu.ActionItem
import org.thoughtcrime.securesms.components.menu.SignalContextMenu
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.conversation.ConversationMessage
import org.thoughtcrime.securesms.database.model.MmsMessageRecord
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.stories.StoryTextPostModel
import org.thoughtcrime.securesms.util.DateUtils
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
import java.util.Locale
object MyStoriesItem {
private const val STATUS_CHANGE = 0
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.stories_my_stories_item))
}
class Model(
val distributionStory: ConversationMessage,
val onClick: (Model, View) -> Unit,
val onLongClick: (Model) -> Boolean,
val onSaveClick: (Model) -> Unit,
val onDeleteClick: (Model) -> Unit,
val onForwardClick: (Model) -> Unit,
val onShareClick: (Model) -> Unit
) : PreferenceModel<Model>() {
override fun areItemsTheSame(newItem: Model): Boolean {
return distributionStory.messageRecord.id == newItem.distributionStory.messageRecord.id
}
override fun areContentsTheSame(newItem: Model): Boolean {
return distributionStory == newItem.distributionStory &&
!hasStatusChange(newItem) &&
distributionStory.messageRecord.viewedReceiptCount == newItem.distributionStory.messageRecord.viewedReceiptCount &&
super.areContentsTheSame(newItem)
}
override fun getChangePayload(newItem: Model): Any? {
return if (isSameRecord(newItem) && hasStatusChange(newItem)) {
STATUS_CHANGE
} else {
null
}
}
private fun isSameRecord(newItem: Model): Boolean {
return distributionStory.messageRecord.id == newItem.distributionStory.messageRecord.id
}
private fun hasStatusChange(newItem: Model): Boolean {
val oldRecord = distributionStory.messageRecord
val newRecord = newItem.distributionStory.messageRecord
return oldRecord.isOutgoing &&
newRecord.isOutgoing &&
(oldRecord.isPending != newRecord.isPending || oldRecord.isSent != newRecord.isSent || oldRecord.isFailed != newRecord.isFailed)
}
}
private class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val downloadTarget: View = itemView.findViewById(R.id.download_touch)
private val moreTarget: View = itemView.findViewById(R.id.more_touch)
private val storyPreview: ImageView = itemView.findViewById<ImageView>(R.id.story).apply {
isClickable = false
}
private val storyBlur: ImageView = itemView.findViewById<ImageView>(R.id.story_blur).apply {
isClickable = false
}
private val viewCount: TextView = itemView.findViewById(R.id.view_count)
private val date: TextView = itemView.findViewById(R.id.date)
private val errorIndicator: View = itemView.findViewById(R.id.error_indicator)
override fun bind(model: Model) {
storyPreview.isClickable = false
itemView.setOnClickListener { model.onClick(model, storyPreview) }
itemView.setOnLongClickListener { model.onLongClick(model) }
downloadTarget.setOnClickListener { model.onSaveClick(model) }
moreTarget.setOnClickListener { showContextMenu(model) }
presentDateOrStatus(model)
if (model.distributionStory.messageRecord.isSent) {
viewCount.text = context.resources.getQuantityString(
R.plurals.MyStories__d_views,
model.distributionStory.messageRecord.viewedReceiptCount,
model.distributionStory.messageRecord.viewedReceiptCount
)
}
if (STATUS_CHANGE in payload) {
return
}
val record: MmsMessageRecord = model.distributionStory.messageRecord as MmsMessageRecord
val thumbnail = record.slideDeck.thumbnailSlide?.uri
val blur = record.slideDeck.thumbnailSlide?.placeholderBlur
clearGlide()
storyBlur.visible = blur != null
if (blur != null) {
GlideApp.with(storyBlur).load(blur).into(storyBlur)
}
@Suppress("CascadeIf")
if (record.storyType.isTextStory) {
storyBlur.visible = false
val storyTextPostModel = StoryTextPostModel.parseFrom(record)
GlideApp.with(storyPreview)
.load(storyTextPostModel)
.placeholder(storyTextPostModel.getPlaceholder())
.centerCrop()
.dontAnimate()
.into(storyPreview)
} else if (thumbnail != null) {
storyBlur.visible = blur != null
GlideApp.with(storyPreview)
.load(DecryptableStreamUriLoader.DecryptableUri(thumbnail))
.addListener(HideBlurAfterLoadListener())
.centerCrop()
.dontAnimate()
.into(storyPreview)
}
}
private fun presentDateOrStatus(model: Model) {
if (model.distributionStory.messageRecord.isPending || model.distributionStory.messageRecord.isMediaPending) {
errorIndicator.visible = false
date.visible = false
viewCount.setText(R.string.StoriesLandingItem__sending)
} else if (model.distributionStory.messageRecord.isFailed) {
errorIndicator.visible = true
date.visible = true
viewCount.setText(R.string.StoriesLandingItem__send_failed)
date.setText(R.string.StoriesLandingItem__tap_to_retry)
} else {
errorIndicator.visible = false
date.visible = true
date.text = DateUtils.getBriefRelativeTimeSpanString(context, Locale.getDefault(), model.distributionStory.messageRecord.dateSent)
}
}
private fun showContextMenu(model: Model) {
SignalContextMenu.Builder(itemView, itemView.rootView as ViewGroup)
.preferredHorizontalPosition(SignalContextMenu.HorizontalPosition.END)
.offsetX(DimensionUnit.DP.toPixels(16f).toInt())
.offsetY(DimensionUnit.DP.toPixels(12f).toInt())
.show(
listOf(
ActionItem(R.drawable.ic_delete_24_tinted, context.getString(R.string.delete)) { model.onDeleteClick(model) },
ActionItem(R.drawable.ic_download_24_tinted, context.getString(R.string.save)) { model.onSaveClick(model) },
ActionItem(R.drawable.ic_forward_24_tinted, context.getString(R.string.MyStories_forward)) { model.onForwardClick(model) },
ActionItem(R.drawable.ic_share_24_tinted, context.getString(R.string.StoriesLandingItem__share)) { model.onShareClick(model) }
)
)
}
private inner class HideBlurAfterLoadListener : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean = false
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
storyBlur.visible = false
return false
}
}
private fun clearGlide() {
GlideApp.with(storyPreview).clear(storyPreview)
GlideApp.with(storyBlur).clear(storyBlur)
}
}
}
| gpl-3.0 | a76fb36cd58c89475ad667975b2d415c | 41.015789 | 157 | 0.726043 | 4.492403 | false | false | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/Pom.kt | 1 | 4413 | package com.beust.kobalt.maven
import com.beust.kobalt.misc.toString
import com.beust.kobalt.misc.warn
import com.google.inject.assistedinject.Assisted
import kotlinx.dom.childElements
import org.w3c.dom.Element
import org.w3c.dom.NodeList
import org.xml.sax.InputSource
import java.io.FileReader
import javax.xml.xpath.XPathConstants
class Pom @javax.inject.Inject constructor(@Assisted val id: String,
@Assisted documentFile: java.io.File) {
val XPATH_FACTORY = javax.xml.xpath.XPathFactory.newInstance()
val XPATH = XPATH_FACTORY.newXPath()
var groupId: String? = null
var artifactId: String? = null
var packaging: String? = null
var version: String? = null
/**
* If the version is a string, extract it, look it up and evaluate it if we find it. Otherwise, error.
*/
private fun calculateVersion(s: String) : String {
val v = extractVar(s)
if (v != null) {
val value = properties[v]
if (value != null) {
return value
} else {
warn("Unknown variable for version: " + s)
return ""
}
} else {
return s
}
}
private fun extractVar(s: String) : String? {
if (s.startsWith("\${") && s.endsWith("}")) {
return s.substring(2, s.length - 1)
} else {
return null
}
}
var name: String? = null
var properties = sortedMapOf<String, String>()
var repositories = listOf<String>()
interface IFactory {
fun create(@Assisted id: String, @Assisted documentFile: java.io.File): Pom
}
data class Dependency(val groupId: String, val artifactId: String, val packaging: String?,
val version: String, val optional: Boolean = false, val scope: String? = null) {
val mustDownload: Boolean
get() = !optional && "provided" != scope && "test" != scope
val id: String = "$groupId:$artifactId:$version"
}
val dependencies = arrayListOf<Dependency>()
init {
val DEPENDENCIES = XPATH.compile("/project/dependencies/dependency")
val document = kotlinx.dom.parseXml(InputSource(FileReader(documentFile)))
groupId = XPATH.compile("/project/groupId").evaluate(document)
artifactId = XPATH.compile("/project/artifactId").evaluate(document)
version = XPATH.compile("/project/version").evaluate(document)
name = XPATH.compile("/project/name").evaluate(document)
var repositoriesList = XPATH.compile("/project/repositories").evaluate(document, XPathConstants.NODESET)
as NodeList
var repoElem = repositoriesList.item(0) as Element?
repositories = repoElem.childElements().map({ it.getElementsByTagName("url").item(0).textContent })
val propertiesList = XPATH.compile("/project/properties").evaluate(document, XPathConstants.NODESET) as NodeList
var propsElem = propertiesList.item(0) as Element?
propsElem.childElements().forEach {
properties.put(it.nodeName, it.textContent)
}
val deps = DEPENDENCIES.evaluate(document, XPathConstants.NODESET) as NodeList
for (i in 0..deps.length - 1) {
val d = deps.item(i) as NodeList
var groupId: String? = null
var artifactId: String? = null
var packaging: String? = null
var readVersion: String = ""
var optional: Boolean? = false
var scope: String? = null
for (j in 0..d.length - 1) {
val e = d.item(j)
if (e is Element) {
when (e.tagName) {
"groupId" -> groupId = e.textContent
"artifactId" -> artifactId = e.textContent
"type" -> packaging = e.textContent
"version" -> readVersion = e.textContent
"optional" -> optional = "true".equals(e.textContent, true)
"scope" -> scope = e.textContent
}
}
}
val version = calculateVersion(readVersion)
val tmpDependency = Dependency(groupId!!, artifactId!!, packaging, version, optional!!, scope)
dependencies.add(tmpDependency)
}
}
override fun toString() = toString("Pom", "id", id)
}
| apache-2.0 | 97ec7cc7069a43049a9a0d7e1f40382a | 37.373913 | 120 | 0.59506 | 4.475659 | false | false | false | false |
carrotengineer/Warren | src/main/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl005/Rpl005ChanModesHandler.kt | 2 | 1596 | package engineer.carrot.warren.warren.handler.rpl.Rpl005
import engineer.carrot.warren.kale.irc.CharacterCodes
import engineer.carrot.warren.warren.loggerFor
import engineer.carrot.warren.warren.state.ChannelModesState
interface IRpl005ChanModesHandler {
fun handle(rawValue: String, state: ChannelModesState): Boolean
}
object Rpl005ChanModesHandler : IRpl005ChanModesHandler {
private val LOGGER = loggerFor<Rpl005ChanModesHandler>()
override fun handle(rawValue: String, state: ChannelModesState): Boolean {
// CHANMODES: eIb,k,l,imnpstSr
val value = rawValue
if (value.isNullOrEmpty()) {
LOGGER.warn("CHANMODES value null or empty, bailing")
return false
}
val modeValues = value.split(delimiters = CharacterCodes.COMMA)
if (modeValues.size < 4) {
LOGGER.warn("CHANMODES has less than 4 types, bailing")
return false
}
val typeA = parseModes(modeValues[0])
val typeB = parseModes(modeValues[1])
val typeC = parseModes(modeValues[2])
val typeD = parseModes(modeValues[3])
state.typeA = typeA
state.typeB = typeB
state.typeC = typeC
state.typeD = typeD
LOGGER.debug("handled 005 CHANMODES: $state")
return true
}
private fun parseModes(typeValues: String): Set<Char> {
val parsedModes = mutableSetOf<Char>()
for (i in 0..typeValues.length - 1) {
val c = typeValues[i]
parsedModes.add(c)
}
return parsedModes
}
} | isc | 3ef963f992595c4d3acf127b8d9f06f2 | 25.616667 | 78 | 0.646617 | 4.256 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/vulkan/VulkanFramebuffer.kt | 2 | 31059 | package graphics.scenery.backends.vulkan
import graphics.scenery.utils.LazyLogger
import org.lwjgl.system.MemoryUtil.*
import org.lwjgl.system.Struct
import org.lwjgl.vulkan.*
import org.lwjgl.vulkan.VK10.*
import java.nio.LongBuffer
import java.util.*
/**
* Vulkan Framebuffer class. Creates a framebuffer on [device], associated with
* a [commandPool]. The framebuffer's [width] and [height] need to be given, as well
* as a [commandBuffer] during which's execution the framebuffer will be created.
*
* [shouldClear] - set if on the beginning of a render pass, the framebuffer should be cleared. On by default.
* [sRGB] - set if sRGB targets should be used. Off by default.
*
* @author Ulrik Günther <[email protected]>
*/
open class VulkanFramebuffer(protected val device: VulkanDevice,
protected var commandPool: Long,
var width: Int,
var height: Int,
val commandBuffer: VkCommandBuffer,
var shouldClear: Boolean = true, val sRGB: Boolean = false): AutoCloseable {
protected val logger by LazyLogger()
/** Raw Vulkan framebuffer reference. */
var framebuffer = memAllocLong(1)
protected set
/** Raw Vulkan renderpass reference. */
var renderPass = memAllocLong(1)
protected set
/* Raw Vulkan sampler reference. */
var framebufferSampler = memAllocLong(1)
protected set
/** Descriptor set for this framebuffer's output. */
var outputDescriptorSetLayout: Long = -1L
internal set
/** Descriptor set for this framebuffer's output. */
var outputDescriptorSet: Long = -1L
internal set
/** Descriptor set for this framebuffer's output. */
var imageLoadStoreDescriptorSetLayout: Long = -1L
internal set
/** Descriptor set for this framebuffer's output. */
var imageLoadStoreDescriptorSet: Long = -1L
internal set
/** Flag to indicate whether this framebuffer has been initialiased or not. */
protected var initialized: Boolean = false
/** Enum class for indicating whether a framebuffer containts a color or a depth attachment. */
enum class VulkanFramebufferType { COLOR_ATTACHMENT, DEPTH_ATTACHMENT }
/** Class to describe framebuffer attachments */
inner class VulkanFramebufferAttachment: AutoCloseable {
/** Image reference for the attachment */
var image: Long = -1L
/** Memory reference for the attachment */
var memory: LongBuffer = memAllocLong(1)
/** Image view for the attachment */
var imageView: LongBuffer = memAllocLong(1)
/** Vulkan format of this attachment */
var format: Int = 0
/** Descriptor set for this attachment */
var descriptorSetLayout: Long = -1L
/** Descriptor set for this attachment */
var descriptorSet: Long = -1L
/** Descriptor set to use this attachment for image load/store */
var loadStoreDescriptorSetLayout: Long? = null
/** Descriptor set to use this attachment for image load/store */
var loadStoreDescriptorSet: Long? = null
/** Attachment type */
var type: VulkanFramebufferType = VulkanFramebufferType.COLOR_ATTACHMENT
/** Vulkan attachment description */
var desc: VkAttachmentDescription = VkAttachmentDescription.calloc()
/**
* Indicates whether the image for this attachment comes from a swapchain image,
* in which case a dedicated allocation is not necessary.
*/
var fromSwapchain = false
init {
memory.put(0, -1L)
}
/**
* Closes the attachment, freeing its resources.
*/
override fun close() {
if(descriptorSetLayout != -1L) {
device.removeDescriptorSetLayout(descriptorSetLayout)
}
loadStoreDescriptorSetLayout?.let {
if (loadStoreDescriptorSetLayout != -1L) {
device.removeDescriptorSetLayout(it)
}
}
vkDestroyImageView(device.vulkanDevice, imageView.get(0), null)
memFree(imageView)
if(image != -1L && fromSwapchain == false) {
vkDestroyImage(device.vulkanDevice, image, null)
}
if(memory.get(0) != -1L) {
vkFreeMemory(device.vulkanDevice, memory.get(0), null)
}
memFree(memory)
desc.free()
}
fun compatibleWith(thisFramebuffer: VulkanFramebuffer, other: VulkanFramebufferAttachment, otherFramebuffer: VulkanFramebuffer): Boolean {
return (this.format == other.format
&& this.type == other.type
&& thisFramebuffer.width == otherFramebuffer.width
&& thisFramebuffer.height == otherFramebuffer.height
&& thisFramebuffer.sRGB == otherFramebuffer.sRGB)
}
}
/** Linked hash map of this framebuffer's [VulkanFramebufferAttachment]s. */
var attachments = LinkedHashMap<String, VulkanFramebufferAttachment>()
init {
val samplerCreateInfo = VkSamplerCreateInfo.calloc()
.default()
.magFilter(VK_FILTER_LINEAR)
.minFilter(VK_FILTER_LINEAR)
.mipmapMode(VK_SAMPLER_MIPMAP_MODE_LINEAR)
.addressModeU(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
.addressModeV(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
.addressModeW(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
.mipLodBias(0.0f)
.maxAnisotropy(1.0f)
.minLod(0.0f)
.maxLod(1.0f)
.borderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE)
vkCreateSampler(device.vulkanDevice, samplerCreateInfo, null, this.framebufferSampler)
samplerCreateInfo.free()
}
/**
* Internal function to create attachments of [format], with image usage flags given in [usage].
* The attachment will have dimensions [attachmentWidth] x [attachmentHeight].
*
* This function also creates the necessary images, memory allocs, and image views.
*/
protected fun createAttachment(format: Int, usage: Int, attachmentWidth: Int = width, attachmentHeight: Int = height, name: String = ""): VulkanFramebufferAttachment {
val a = VulkanFramebufferAttachment()
var aspectMask: Int = 0
var imageLayout: Int = 0
var loadStoreSupported = false
a.format = format
if (usage == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
aspectMask = VK_IMAGE_ASPECT_COLOR_BIT
imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
}
if (usage == VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT
imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
}
val imageExtent = VkExtent3D.calloc()
.width(attachmentWidth)
.height(attachmentHeight)
.depth(1)
val image = VkImageCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO)
.pNext(NULL)
.imageType(VK_IMAGE_TYPE_2D)
.format(a.format)
.extent(imageExtent)
.mipLevels(1)
.arrayLayers(1)
.samples(VK_SAMPLE_COUNT_1_BIT)
.tiling(VK_IMAGE_TILING_OPTIMAL)
.usage(usage or VK_IMAGE_USAGE_SAMPLED_BIT or VK_IMAGE_USAGE_TRANSFER_SRC_BIT or VK_IMAGE_USAGE_TRANSFER_DST_BIT)
if(device.formatFeatureSupported(a.format, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT, optimalTiling = true)) {
image.usage(image.usage() or VK_IMAGE_USAGE_STORAGE_BIT)
loadStoreSupported = true
}
a.image = VU.getLong("Create VkImage",
{ vkCreateImage(device.vulkanDevice, image, null, this) },
{ image.free(); imageExtent.free() })
val requirements = VkMemoryRequirements.calloc()
vkGetImageMemoryRequirements(device.vulkanDevice, a.image, requirements)
val allocation = VkMemoryAllocateInfo.calloc()
.allocationSize(requirements.size())
.memoryTypeIndex(device.getMemoryType(requirements.memoryTypeBits(), VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).first())
.sType(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO)
.pNext(NULL)
vkAllocateMemory(device.vulkanDevice, allocation, null, a.memory)
vkBindImageMemory(device.vulkanDevice, a.image, a.memory.get(0), 0)
requirements.free()
allocation.free()
VU.setImageLayout(
commandBuffer,
a.image,
aspectMask,
VK_IMAGE_LAYOUT_UNDEFINED,
if (usage == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
else imageLayout
)
val subresourceRange = VkImageSubresourceRange.calloc()
.aspectMask(aspectMask)
.baseMipLevel(0)
.levelCount(1)
.baseArrayLayer(0)
.layerCount(1)
val iv = VkImageViewCreateInfo.calloc()
.viewType(VK_IMAGE_VIEW_TYPE_2D)
.format(format)
.subresourceRange(subresourceRange)
.image(a.image)
.sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
.pNext(NULL)
vkCreateImageView(device.vulkanDevice, iv, null, a.imageView)
iv.free()
subresourceRange.free()
a.descriptorSetLayout = device.createDescriptorSetLayout(
descriptorNum = 1,
descriptorCount = 1,
type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
)
a.descriptorSet = device.createRenderTargetDescriptorSet(
a.descriptorSetLayout,
this,
onlyFor = listOf(a)
)
logger.debug("Created sampling DSL ${a.descriptorSetLayout.toHexString()} and DS ${a.descriptorSet.toHexString()} for attachment $name")
if(loadStoreSupported) {
val dsl = device.createDescriptorSetLayout(
descriptorNum = 1,
descriptorCount = 1,
type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
)
a.loadStoreDescriptorSetLayout = dsl
a.loadStoreDescriptorSet = device.createRenderTargetDescriptorSet(
dsl,
this,
onlyFor = listOf(a),
imageLoadStore = true
)
logger.debug("Created load/store DSL ${a.loadStoreDescriptorSetLayout?.toHexString()} and DS ${a.loadStoreDescriptorSet?.toHexString()} for attachment $name")
}
return a
}
/**
* Internal function to create a depth/stencil attachment of [format], with
* dimensions [attachmentWidth] x [attachmentHeight].
*/
private fun createAndAddDepthStencilAttachmentInternal(name: String, format: Int, attachmentWidth: Int, attachmentHeight: Int) {
val att = createAttachment(format, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, attachmentWidth, attachmentHeight, name)
val (loadOp, stencilLoadOp) = if (!shouldClear) {
VK_ATTACHMENT_LOAD_OP_LOAD to VK_ATTACHMENT_LOAD_OP_LOAD
} else {
VK_ATTACHMENT_LOAD_OP_CLEAR to VK_ATTACHMENT_LOAD_OP_CLEAR
}
val initialImageLayout = if(!shouldClear) {
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
} else {
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
}
att.desc.samples(VK_SAMPLE_COUNT_1_BIT)
.loadOp(loadOp)
.storeOp(VK_ATTACHMENT_STORE_OP_STORE)
.stencilLoadOp(stencilLoadOp)
.stencilStoreOp(VK_ATTACHMENT_STORE_OP_STORE)
.initialLayout(initialImageLayout)
.finalLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
.format(format)
att.type = VulkanFramebufferType.DEPTH_ATTACHMENT
attachments.put(name, att)
}
/**
* Internal function to create a new color attachment of format [fornat], with
* dimensions [attachmentWidth] x [attachmentHeight].
*/
private fun createAndAddColorAttachmentInternal(name: String, format: Int, attachmentWidth: Int, attachmentHeight: Int) {
val att = createAttachment(format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, attachmentWidth, attachmentHeight, name)
val (loadOp, stencilLoadOp) = if (!shouldClear) {
VK_ATTACHMENT_LOAD_OP_LOAD to VK_ATTACHMENT_LOAD_OP_LOAD
} else {
VK_ATTACHMENT_LOAD_OP_CLEAR to VK_ATTACHMENT_LOAD_OP_DONT_CARE
}
val initialImageLayout = if(!shouldClear) {
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
} else {
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
}
att.desc.samples(VK_SAMPLE_COUNT_1_BIT)
.loadOp(loadOp)
.storeOp(VK_ATTACHMENT_STORE_OP_STORE)
.stencilLoadOp(stencilLoadOp)
.stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
.initialLayout(initialImageLayout)
.finalLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
.format(format)
attachments.put(name, att)
}
/**
* Adds a float attachment with a bit depth of [channelDepth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addFloatBuffer(name: String, channelDepth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(channelDepth) {
16 -> VK_FORMAT_R16_SFLOAT
32 -> VK_FORMAT_R32_SFLOAT
else -> { logger.warn("Unsupported channel depth $channelDepth, using 16 bit."); VK_FORMAT_R16_SFLOAT }
}
createAndAddColorAttachmentInternal(name, format, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds a float RG attachment with a bit depth of [channelDepth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addFloatRGBuffer(name: String, channelDepth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(channelDepth) {
16 -> VK_FORMAT_R16G16_SFLOAT
32 -> VK_FORMAT_R32G32_SFLOAT
else -> { logger.warn("Unsupported channel depth $channelDepth, using 16 bit."); VK_FORMAT_R16G16_SFLOAT }
}
createAndAddColorAttachmentInternal(name, format, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds a float RGB attachment with a bit depth of [channelDepth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addFloatRGBBuffer(name: String, channelDepth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(channelDepth) {
16 -> VK_FORMAT_R16G16B16_SFLOAT
32 -> VK_FORMAT_R32G32B32_SFLOAT
else -> { logger.warn("Unsupported channel depth $channelDepth, using 16 bit."); VK_FORMAT_R16G16B16A16_SFLOAT }
}
createAndAddColorAttachmentInternal(name, format, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds a float RGBA attachment with a bit depth of [channelDepth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addFloatRGBABuffer(name: String, channelDepth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(channelDepth) {
16 -> VK_FORMAT_R16G16B16A16_SFLOAT
32 -> VK_FORMAT_R32G32B32A32_SFLOAT
else -> { logger.warn("Unsupported channel depth $channelDepth, using 16 bit."); VK_FORMAT_R16G16B16A16_SFLOAT }
}
createAndAddColorAttachmentInternal(name, format, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds an unsigned byte RGBA attachment with a bit depth of [channelDepth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addUnsignedByteRGBABuffer(name: String, channelDepth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(channelDepth) {
8 -> if (sRGB) {
VK_FORMAT_R8G8B8A8_SRGB
} else {
VK_FORMAT_R8G8B8A8_UNORM
}
16 -> VK_FORMAT_R16G16B16A16_UNORM
else -> { logger.warn("Unsupported channel depth $channelDepth, using 16 bit."); VK_FORMAT_R16G16B16A16_UINT }
}
createAndAddColorAttachmentInternal(name, format, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds an unsigned byte R attachment with a bit depth of [channelDepth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addUnsignedByteRBuffer(name: String, channelDepth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(channelDepth) {
8 -> VK_FORMAT_R8_UNORM
16 -> VK_FORMAT_R16_UNORM
else -> { logger.warn("Unsupported channel depth $channelDepth, using 16 bit."); VK_FORMAT_R16_UNORM }
}
createAndAddColorAttachmentInternal(name, format, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds a depth buffer attachment with a bit depth of [depth], and a size of [attachmentWidth] x [attachmentHeight].
*/
fun addDepthBuffer(name: String, depth: Int, attachmentWidth: Int = width, attachmentHeight: Int = height): VulkanFramebuffer {
val format: Int = when(depth) {
16 -> VK_FORMAT_D16_UNORM
24 -> VK_FORMAT_D24_UNORM_S8_UINT
32 -> VK_FORMAT_D32_SFLOAT
else -> { logger.warn("Unsupported channel depth $depth, using 32 bit."); VK_FORMAT_D32_SFLOAT }
}
val bestSupportedFormat = getBestDepthFormat(format).first()
createAndAddDepthStencilAttachmentInternal(name, bestSupportedFormat, attachmentWidth, attachmentHeight)
return this
}
/**
* Adds a swapchain-based attachment from the given [swapchain]. The image will be derived
* from the swapchain's image [index].
*/
fun addSwapchainAttachment(name: String, swapchain: Swapchain, index: Int): VulkanFramebuffer {
val att = VulkanFramebufferAttachment()
att.image = swapchain.images[index]
att.imageView.put(0, swapchain.imageViews[index])
att.type = VulkanFramebufferType.COLOR_ATTACHMENT
att.fromSwapchain = true
val (loadOp, stencilLoadOp) = if (!shouldClear) {
VK_ATTACHMENT_LOAD_OP_LOAD to VK_ATTACHMENT_LOAD_OP_LOAD
} else {
VK_ATTACHMENT_LOAD_OP_CLEAR to VK_ATTACHMENT_LOAD_OP_DONT_CARE
}
val initialImageLayout = VK_IMAGE_LAYOUT_UNDEFINED
att.desc
.samples(VK_SAMPLE_COUNT_1_BIT)
.loadOp(loadOp)
.storeOp(VK_ATTACHMENT_STORE_OP_STORE)
.stencilLoadOp(stencilLoadOp)
.stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
.initialLayout(initialImageLayout)
.finalLayout(KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)
.format(if (sRGB) {
VK_FORMAT_B8G8R8A8_SRGB
} else {
VK_FORMAT_B8G8R8A8_UNORM
})
attachments.put(name, att)
val loadStoreSupported = device.formatFeatureSupported(att.format, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT, optimalTiling = true)
att.descriptorSetLayout = device.createDescriptorSetLayout(
descriptorNum = 1,
descriptorCount = 1,
type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
)
att.descriptorSet = device.createRenderTargetDescriptorSet(
att.descriptorSetLayout,
this,
onlyFor = listOf(att)
)
logger.debug("Created sampling DSL ${att.descriptorSetLayout.toHexString()} and DS ${att.descriptorSet.toHexString()} for attachment $name")
if(loadStoreSupported) {
val dsl = device.createDescriptorSetLayout(
descriptorNum = 1,
descriptorCount = 1,
type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
)
att.loadStoreDescriptorSetLayout = dsl
att.loadStoreDescriptorSet = device.createRenderTargetDescriptorSet(
dsl,
this,
onlyFor = listOf(att),
imageLoadStore = true
)
logger.debug("Created load/store DSL ${att.loadStoreDescriptorSetLayout?.toHexString()} and DS ${att.loadStoreDescriptorSet?.toHexString()} for attachment $name")
} else {
logger.debug("Not creating load/store DSL/DS for attachment $name due to lack of feature support for format ${att.desc.format()}")
}
return this
}
/**
* Gets a Vulkan attachment description from the current framebuffer state.
*/
protected fun getAttachmentDescBuffer(): VkAttachmentDescription.Buffer {
val descriptionBuffer = VkAttachmentDescription.calloc(attachments.size)
attachments.values.forEach{ descriptionBuffer.put(it.desc) }
return descriptionBuffer.flip()
}
/**
* Gets all the image views of the current framebuffer.
*/
protected fun getAttachmentImageViews(): LongBuffer {
val ivBuffer = memAllocLong(attachments.size)
attachments.values.forEach{ ivBuffer.put(it.imageView.get(0)) }
ivBuffer.flip()
return ivBuffer
}
/**
* Creates the Vulkan Renderpass and Framebuffer from the state of the
* framebuffer.
*/
fun createRenderpassAndFramebuffer() {
val colorDescs = VkAttachmentReference.calloc(attachments.filter { it.value.type == VulkanFramebufferType.COLOR_ATTACHMENT }.size)
attachments.values.filter { it.type == VulkanFramebufferType.COLOR_ATTACHMENT }.forEachIndexed { i, _ ->
colorDescs[i]
.attachment(i)
.layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
}
val depthDescs: VkAttachmentReference? = if(attachments.any { it.value.type == VulkanFramebufferType.DEPTH_ATTACHMENT }) {
VkAttachmentReference.calloc()
.attachment(colorDescs.limit())
.layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
} else {
null
}
logger.trace("Subpass for has ${colorDescs.remaining()} color attachments")
val subpass = VkSubpassDescription.calloc(1)
.pColorAttachments(colorDescs)
.colorAttachmentCount(colorDescs.remaining())
.pDepthStencilAttachment(depthDescs)
.pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS)
.pInputAttachments(null)
.pPreserveAttachments(null)
.pResolveAttachments(null)
.flags(0)
val dependencyChain = VkSubpassDependency.calloc(2)
// dependencyChain[0]
// .srcSubpass(VK_SUBPASS_EXTERNAL)
// .dstSubpass(0)
// .srcStageMask(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT or VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
// .srcAccessMask(0)
// .dstStageMask(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT)
// .dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)
//
// dependencyChain[1]
// .srcSubpass(0)
// .dstSubpass(VK_SUBPASS_EXTERNAL)
// .srcStageMask(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT or VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)
// .srcAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT or VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT or VK_ACCESS_COLOR_ATTACHMENT_READ_BIT)
// .dstStageMask(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)
// .dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
dependencyChain[0]
.srcSubpass(VK_SUBPASS_EXTERNAL)
.dstSubpass(0)
.srcStageMask(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT)
.dstStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT or VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
.srcAccessMask(VK_ACCESS_MEMORY_READ_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT or VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
// .dependencyFlags(VK_DEPENDENCY_BY_REGION_BIT)
dependencyChain[1]
.srcSubpass(0)
.dstSubpass(VK_SUBPASS_EXTERNAL)
.srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT or VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
.dstStageMask(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT or VK_PIPELINE_STAGE_TRANSFER_BIT or VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT or VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)
.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT or VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_MEMORY_READ_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT or VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT or VK_ACCESS_SHADER_READ_BIT)
// .dependencyFlags(VK_DEPENDENCY_BY_REGION_BIT)
if(!attachments.any { it.value.fromSwapchain }) {
dependencyChain[0].dependencyFlags(VK_DEPENDENCY_BY_REGION_BIT)
dependencyChain[1].dependencyFlags(VK_DEPENDENCY_BY_REGION_BIT)
}
val attachmentDescs = getAttachmentDescBuffer()
val renderPassInfo = VkRenderPassCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO)
.pAttachments(attachmentDescs)
.pSubpasses(subpass)
.pDependencies(dependencyChain)
.pNext(NULL)
renderPass.put(0, VU.getLong("create renderpass",
{ vkCreateRenderPass(device.vulkanDevice, renderPassInfo, null, this) },
{ attachmentDescs.free() }))
logger.trace("Created renderpass ${renderPass.get(0)}")
val attachmentImageViews = getAttachmentImageViews()
val fbinfo = VkFramebufferCreateInfo.calloc()
.default()
.renderPass(renderPass.get(0))
.pAttachments(attachmentImageViews)
.width(width)
.height(height)
.layers(1)
framebuffer.put(0, VU.getLong("create framebuffer",
{ vkCreateFramebuffer(device.vulkanDevice, fbinfo, null, this) },
{ fbinfo.free(); memFree(attachmentImageViews); }))
outputDescriptorSetLayout = device.createDescriptorSetLayout(
descriptorNum = attachments.count(),
descriptorCount = 1,
type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
)
outputDescriptorSet = device.createRenderTargetDescriptorSet(
outputDescriptorSetLayout,
this
)
logger.debug("Created sampling DSL ${outputDescriptorSetLayout.toHexString()} and DS ${outputDescriptorSet.toHexString()} for framebuffer")
imageLoadStoreDescriptorSetLayout = device.createDescriptorSetLayout(
descriptorNum = attachments.count { it.value.loadStoreDescriptorSet != null },
descriptorCount = 1,
type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
)
imageLoadStoreDescriptorSet = device.createRenderTargetDescriptorSet(
imageLoadStoreDescriptorSetLayout,
this,
imageLoadStore = true,
onlyFor = attachments.values.filter { it.loadStoreDescriptorSet != null }
)
logger.debug("Created load/store DSL ${imageLoadStoreDescriptorSetLayout.toHexString()} and DS ${imageLoadStoreDescriptorSet.toHexString()} for framebuffer")
renderPassInfo.free()
subpass.free()
colorDescs.free()
depthDescs?.free()
initialized = true
}
/**
* Helper function to set up Vulkan structs.
*/
fun <T : Struct> T.default(): T {
if(this is VkSamplerCreateInfo) {
this.sType(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO).pNext(NULL)
} else if(this is VkFramebufferCreateInfo) {
this.sType(VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO).pNext(NULL)
}
return this
}
/** Returns a string representation of this framebuffer. */
override fun toString(): String {
return "VulkanFramebuffer ${width}x$height (${attachments.size} attachments)"
}
/**
* Returns the best available depth format, from a list of [preferredFormat]s.
*/
private fun getBestDepthFormat(preferredFormat: Int): List<Int> {
// this iterates through the list of possible (though not all required formats)
// and returns the first one that is possible to use as a depth buffer on the
// given physical device.
val props = VkFormatProperties.calloc()
val format = intArrayOf(
preferredFormat,
VK_FORMAT_D32_SFLOAT,
VK_FORMAT_D32_SFLOAT_S8_UINT,
VK_FORMAT_D24_UNORM_S8_UINT,
VK_FORMAT_D16_UNORM_S8_UINT,
VK_FORMAT_D16_UNORM
).filter {
vkGetPhysicalDeviceFormatProperties(device.physicalDevice, it, props)
props.optimalTilingFeatures() and VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT > 0
}
logger.debug("Using $format as depth format.")
props.free()
return format
}
/** Returns the number of current color attachments. */
fun colorAttachmentCount() = attachments.count { it.value.type == VulkanFramebufferType.COLOR_ATTACHMENT }
/** Returns the number of current depth attachments. */
fun depthAttachmentCount() = attachments.count { it.value.type == VulkanFramebufferType.DEPTH_ATTACHMENT }
/** Closes this framebuffer instance, releasing all of its resources. */
override fun close() {
if(initialized) {
attachments.values.forEach { it.close() }
device.removeDescriptorSetLayout(outputDescriptorSetLayout)
device.removeDescriptorSetLayout(imageLoadStoreDescriptorSetLayout)
vkDestroyRenderPass(device.vulkanDevice, renderPass.get(0), null)
memFree(renderPass)
vkDestroySampler(device.vulkanDevice, framebufferSampler.get(0), null)
memFree(framebufferSampler)
vkDestroyFramebuffer(device.vulkanDevice, this.framebuffer.get(0), null)
memFree(framebuffer)
initialized = false
}
}
}
| lgpl-3.0 | d3fecf1307235d3a0517e0d70a48017d | 39.126615 | 200 | 0.638579 | 4.413528 | false | false | false | false |
WilliamHester/Breadit-2 | app/app/src/main/java/me/williamhester/reddit/inject/ApplicationModule.kt | 1 | 2101 | package me.williamhester.reddit.inject
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import dagger.Module
import dagger.Provides
import me.williamhester.reddit.convert.RedditGsonConverter
import me.williamhester.reddit.models.Edited
import me.williamhester.reddit.models.managers.AccountManager
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import javax.inject.Singleton
/**
* A Module for providing dependencies that will be reused throughout the applicaiton's lifetime.
*/
@Module
class ApplicationModule(private val context: Context) {
@Provides
@Singleton
internal fun provideGson(): Gson {
return GsonBuilder()
.registerTypeAdapter(Edited::class.java, Edited.TypeAdapter())
.create()
}
@Provides
@Singleton
internal fun provideJsonParser(): JsonParser {
return JsonParser()
}
@Provides
@Singleton
internal fun provideOkClient(): OkHttpClient {
val headerInterceptor = Interceptor { chain ->
val original = chain.request()
// Customize the request
val builder = original.newBuilder()
.addHeader("User-Agent", "Breadit-2")
.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.method(original.method(), original.body())
chain.proceed(builder.build())
}
return OkHttpClient.Builder()
.addInterceptor(headerInterceptor)
.build()
}
@Provides
@Singleton
internal fun provideContext(): Context = context
@Provides
@Singleton
internal fun provideSharedPreferences(context: Context): SharedPreferences {
return context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
}
@Provides
@Singleton
internal fun provideAccountManager(sharedPreferences: SharedPreferences): AccountManager {
return AccountManager(sharedPreferences)
}
@Provides
@Singleton
internal fun provideRedditGsonConverter(gson: Gson): RedditGsonConverter {
return RedditGsonConverter(gson)
}
}
| apache-2.0 | 89a6f053437b6a3903e77f8a70e1fda8 | 25.935897 | 97 | 0.743931 | 4.731982 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/basic/CurveUniformBSplineExample.kt | 2 | 3671 | package graphics.scenery.tests.examples.basic
import org.joml.*
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.geometry.Curve
import graphics.scenery.geometry.UniformBSpline
import graphics.scenery.numerics.Random
import graphics.scenery.attribute.material.Material
/**
* Just a quick example a UniformBSpline with a triangle as a baseShape.
*
* @author Justin Buerger <[email protected]>
*/
class CurveUniformBSplineExample: SceneryBase("CurveUniformBSplineExample", windowWidth = 1280, windowHeight = 720) {
override fun init() {
renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight))
val rowSize = 10f
val points = ArrayList<Vector3f>()
points.add(Vector3f(-8f, -9f, -9f))
points.add(Vector3f(-7f, -5f, -7f))
points.add(Vector3f(-5f, -5f, -5f))
points.add(Vector3f(-4f, -2f, -3f))
points.add(Vector3f(-2f, -3f, -4f))
points.add(Vector3f(-1f, -1f, -1f))
points.add(Vector3f(0f, 0f, 0f))
points.add(Vector3f(2f, 1f, 0f))
fun triangle(splineVerticesCount: Int): ArrayList<ArrayList<Vector3f>> {
val shapeList = ArrayList<ArrayList<Vector3f>>(splineVerticesCount)
for (i in 0 until splineVerticesCount) {
val list = ArrayList<Vector3f>()
list.add(Vector3f(0.15f, 0.15f, 0f))
list.add(Vector3f(0.15f, -0.15f, 0f))
list.add(Vector3f(-0.15f, -0.15f, 0f))
shapeList.add(list)
}
return shapeList
}
val bSpline = UniformBSpline(points)
val splineSize = bSpline.splinePoints().size
val geo = Curve(bSpline) { triangle(splineSize) }
scene.addChild(geo)
val lightbox = Box(Vector3f(25.0f, 25.0f, 25.0f), insideNormals = true)
lightbox.name = "Lightbox"
lightbox.material {
diffuse = Vector3f(0.1f, 0.1f, 0.1f)
roughness = 1.0f
metallic = 0.0f
cullingMode = Material.CullingMode.None
}
scene.addChild(lightbox)
val lights = (0 until 8).map {
val l = PointLight(radius = 20.0f)
l.spatial().position = Vector3f(
Random.randomFromRange(-rowSize / 2.0f, rowSize / 2.0f),
Random.randomFromRange(-rowSize / 2.0f, rowSize / 2.0f),
Random.randomFromRange(1.0f, 5.0f)
)
l.emissionColor = Random.random3DVectorFromRange( 0.2f, 0.8f)
l.intensity = Random.randomFromRange(0.2f, 0.8f)
lightbox.addChild(l)
l
}
lights.forEach { scene.addChild(it) }
val stageLight = PointLight(radius = 10.0f)
stageLight.name = "StageLight"
stageLight.intensity = 0.5f
stageLight.spatial().position = Vector3f(0.0f, 0.0f, 5.0f)
scene.addChild(stageLight)
val cameraLight = PointLight(radius = 5.0f)
cameraLight.name = "CameraLight"
cameraLight.emissionColor = Vector3f(1.0f, 1.0f, 0.0f)
cameraLight.intensity = 0.8f
val cam: Camera = DetachedHeadCamera()
cam.spatial().position = Vector3f(0.0f, 0.0f, 10.0f)
cam.perspectiveCamera(50.0f, windowWidth, windowHeight)
scene.addChild(cam)
cam.addChild(cameraLight)
}
override fun inputSetup() {
super.inputSetup()
setupCameraModeSwitching()
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
CurveUniformBSplineExample().main()
}
}
}
| lgpl-3.0 | 6c04a8079efda1bc158e9ef293845908 | 33.308411 | 117 | 0.605557 | 3.595495 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestDetailsPanel.kt | 1 | 7799 | // 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.github.pullrequest.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.ui.*
import icons.GithubIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GithubIssueLabel
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.api.data.GithubPullRequestDetailedWithHtml
import org.jetbrains.plugins.github.api.data.GithubUser
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.util.GithubUIUtil
import java.awt.BorderLayout
import java.awt.FlowLayout
import java.awt.Font
import java.awt.Graphics
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingConstants
import kotlin.properties.Delegates
internal class GithubPullRequestDetailsPanel(iconProviderFactory: CachingGithubAvatarIconsProvider.Factory)
: Wrapper(), ComponentWithEmptyText, Disposable {
private val iconsProvider = iconProviderFactory.create(JBValue.UIInteger("Profile.Icon.Size", 20), this)
private val emptyText = object : StatusText(this) {
override fun isStatusVisible() = details == null
}
var details: GithubPullRequestDetailedWithHtml?
by Delegates.observable<GithubPullRequestDetailedWithHtml?>(null) { _, _, _ ->
update()
}
private val contentPanel: JPanel
private val metaPanel = MetadataPanel().apply {
border = JBUI.Borders.empty(4, 8, 4, 8)
}
private val bodyPanel = BodyPanel().apply {
border = JBUI.Borders.empty(4, 8, 8, 8)
}
init {
contentPanel = ScrollablePanel(BorderLayout(0, UIUtil.DEFAULT_VGAP)).apply {
isOpaque = false
add(metaPanel, BorderLayout.NORTH)
add(bodyPanel, BorderLayout.CENTER)
}
val scrollPane = ScrollPaneFactory.createScrollPane(contentPanel, true).apply {
viewport.isOpaque = false
isOpaque = false
}
setContent(scrollPane)
update()
Disposer.register(this, iconsProvider)
}
private fun update() {
bodyPanel.update()
metaPanel.update()
contentPanel.validate()
contentPanel.isVisible = details != null
}
override fun getEmptyText() = emptyText
override fun paintChildren(g: Graphics) {
super.paintChildren(g)
emptyText.paint(this, g)
}
private inner class BodyPanel : HtmlPanel() {
init {
editorKit = UIUtil.JBWordWrapHtmlEditorKit()
}
override fun update() {
super.update()
isVisible = !details?.bodyHtml.isNullOrEmpty()
}
override fun getBody() = details?.bodyHtml.orEmpty()
override fun getBodyFont(): Font = UIUtil.getLabelFont()
}
private inner class MetadataPanel : JPanel() {
private val directionPanel = DirectionPanel()
private val stateLabel = JLabel().apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0, UIUtil.DEFAULT_VGAP * 2, 0)
}
private val reviewersLabel = createLabel()
private val reviewersPanel = createPanel()
private val assigneesLabel = createLabel()
private val assigneesPanel = createPanel()
private val labelsLabel = createLabel()
private val labelsPanel = createPanel()
init {
isOpaque = false
layout = MigLayout(LC()
.fillX()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
add(directionPanel, CC()
.minWidth("0")
.spanX(2).growX()
.wrap())
add(stateLabel, CC()
.minWidth("0")
.spanX(2)
.wrap())
addSection(reviewersLabel, reviewersPanel)
addSection(assigneesLabel, assigneesPanel)
addSection(labelsLabel, labelsPanel)
}
private fun addSection(label: JLabel, panel: JPanel) {
add(label, CC().alignY("top"))
add(panel, CC().minWidth("0").growX().pushX().wrap())
}
fun update() {
directionPanel.update()
val reviewers = details?.requestedReviewers
reviewersPanel.removeAll()
if (reviewers == null || reviewers.isEmpty()) {
reviewersLabel.text = "No Reviewers"
}
else {
reviewersLabel.text = "Reviewers:"
for (reviewer in reviewers) {
reviewersPanel.add(createUserLabel(reviewer))
}
}
val assignees = details?.assignees
assigneesPanel.removeAll()
if (assignees == null || assignees.isEmpty()) {
assigneesLabel.text = "Unassigned"
}
else {
assigneesLabel.text = "Assignees:"
for (assignee in assignees) {
assigneesPanel.add(createUserLabel(assignee))
}
}
val labels = details?.labels
labelsPanel.removeAll()
if (labels == null || labels.isEmpty()) {
labelsLabel.text = "No Labels"
}
else {
labelsLabel.text = "Labels:"
for (label in labels) {
labelsPanel.add(createLabelLabel(label))
}
}
stateLabel.text = ""
stateLabel.icon = null
val details = details
if (details != null && details.state == GithubIssueState.closed)
if (details.merged) {
stateLabel.icon = GithubIcons.PullRequestClosed
stateLabel.text = "Pull request is merged"
}
else {
stateLabel.icon = GithubIcons.PullRequestClosed
stateLabel.text = "Pull request is closed"
}
}
private fun createLabel() = JLabel().apply {
foreground = UIUtil.getContextHelpForeground()
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP + 2, 0, UIUtil.DEFAULT_VGAP + 2, UIUtil.DEFAULT_HGAP / 2)
}
private fun createPanel() = NonOpaquePanel(WrapLayout(FlowLayout.LEADING, 0, 0))
private fun createUserLabel(user: GithubUser) = JLabel(user.login, iconsProvider.getIcon(user), SwingConstants.LEFT).apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP / 2, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP / 2)
}
private fun createLabelLabel(label: GithubIssueLabel) = Wrapper(GithubUIUtil.createIssueLabelLabel(label)).apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP + 1, UIUtil.DEFAULT_HGAP / 2, UIUtil.DEFAULT_VGAP + 2, UIUtil.DEFAULT_HGAP / 2)
}
}
private inner class DirectionPanel : NonOpaquePanel(WrapLayout(FlowLayout.LEFT, 0, UIUtil.DEFAULT_VGAP)) {
private val from = createLabel()
private val to = createLabel()
init {
add(from)
add(JLabel(" ${UIUtil.rightArrow()} ").apply {
foreground = CurrentBranchComponent.TEXT_COLOR
border = JBUI.Borders.empty(0, 5)
})
add(to)
}
private fun createLabel() = object : JBLabel(UIUtil.ComponentStyle.REGULAR) {
init {
updateColors()
}
override fun updateUI() {
super.updateUI()
updateColors()
}
private fun updateColors() {
foreground = CurrentBranchComponent.TEXT_COLOR
background = CurrentBranchComponent.getBranchPresentationBackground(UIUtil.getListBackground())
}
}.andOpaque()
fun update() {
from.text = " ${details?.head?.label.orEmpty()} "
to.text = " ${details?.base?.ref.orEmpty()} "
}
}
override fun dispose() {}
} | apache-2.0 | 69f4658f71f71185fd1d9ad746c9e7c9 | 30.451613 | 140 | 0.674702 | 4.406215 | false | false | false | false |
tomekby/miscellaneous | kotlin-game/android/app/src/main/java/pl/vot/tomekby/mathGame/GameResultsAdapter.kt | 1 | 1869 | package pl.vot.tomekby.mathGame
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.LinearLayout
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick
class GameResultsAdapter(
private val items: ArrayList<Long> = ArrayList(),
private val handler: (Long, View?) -> Unit
) : BaseAdapter() {
private val itemsPerRow = 2
private val buttons = HashMap<Long, Button>()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
return with(parent!!.context) {
linearLayout {
orientation = LinearLayout.HORIZONTAL
// if itemsPerRow = 3 then best works ~30
horizontalPadding = dip(60)
verticalPadding = dip(10)
getItem(position).forEach { result ->
buttons[result] = button(result.toString()) {
// Set on click handler for each created button
onClick { view -> handler(result, view) }
}.lparams(width = wrapContent) {
verticalMargin = dip(5)
horizontalMargin = dip(15)
}
}
}
}
}
// Get values for selected row
override fun getItem(position: Int): List<Long> {
val rowStart = position * itemsPerRow
return items.slice(
rowStart..(rowStart + itemsPerRow - 1)
)
}
override fun getItemId(position: Int): Long {
return 0L
}
override fun getCount(): Int {
return items.size / itemsPerRow
}
fun disableButtons() {
buttons.forEach { _, b -> b.isClickable = false }
}
} | mit | a16d28895b55674d77734bbd79b498bd | 30.258621 | 87 | 0.559658 | 4.944444 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/versions/KotlinMetadataVersionIndexBase.kt | 5 | 2593 | // 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.versions
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.indexing.FileContent
import com.intellij.util.indexing.ID
import com.intellij.util.indexing.ScalarIndexExtension
import com.intellij.util.io.DataInputOutputUtil
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import java.io.DataInput
import java.io.DataOutput
/**
* Important! This is not a stub-based index. And it has its own version
*/
abstract class KotlinMetadataVersionIndexBase<T, V : BinaryVersion>(private val classOfIndex: Class<T>) : ScalarIndexExtension<V>() {
override fun getName(): ID<V, Void> = ID.create<V, Void>(classOfIndex.canonicalName)
override fun getKeyDescriptor(): KeyDescriptor<V> = object : KeyDescriptor<V> {
override fun isEqual(val1: V, val2: V): Boolean = val1 == val2
override fun getHashCode(value: V): Int = value.hashCode()
override fun read(input: DataInput): V {
val size = DataInputOutputUtil.readINT(input)
val versionArray = (0 until size).map { DataInputOutputUtil.readINT(input) }.toIntArray()
val extraBoolean = if (isExtraBooleanNeeded()) DataInputOutputUtil.readINT(input) == 1 else null
return createBinaryVersion(versionArray, extraBoolean)
}
override fun save(output: DataOutput, value: V) {
val array = value.toArray()
DataInputOutputUtil.writeINT(output, array.size)
for (number in array) {
DataInputOutputUtil.writeINT(output, number)
}
if (isExtraBooleanNeeded()) {
DataInputOutputUtil.writeINT(output, if (getExtraBoolean(value)) 1 else 0)
}
}
}
override fun dependsOnFileContent() = true
protected abstract fun createBinaryVersion(versionArray: IntArray, extraBoolean: Boolean?): V
protected open fun isExtraBooleanNeeded(): Boolean = false
protected open fun getExtraBoolean(version: V): Boolean = throw UnsupportedOperationException()
protected val log: Logger = Logger.getInstance(classOfIndex)
protected inline fun tryBlock(inputData: FileContent, body: () -> Unit) {
try {
body()
} catch (e: Throwable) {
log.warn("Could not index ABI version for file " + inputData.file + ": " + e.message)
}
}
}
| apache-2.0 | 70abda7e91e2e0f3ae708ac469e5ec73 | 41.508197 | 158 | 0.693791 | 4.478411 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/ListInstructions.kt | 1 | 6962 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* 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.jonathanxd.kores
import java.util.*
import java.util.function.Consumer
import java.util.function.Predicate
import java.util.function.UnaryOperator
import java.util.stream.Stream
/**
* A [MutableInstructions] backing to a [ArrayList].
*/
class ListInstructions(private val backingList: MutableList<Instruction>) : MutableInstructions(),
Cloneable {
constructor() : this(mutableListOf())
constructor(iterable: Iterable<Instruction>) : this(iterable.toMutableList())
constructor(a: Array<Instruction>) : this(a.toMutableList())
override val size: Int
get() = this.backingList.size
override fun removeIf(filter: Predicate<in Instruction>): Boolean {
return this.backingList.removeIf(filter)
}
override fun replaceAll(operator: UnaryOperator<Instruction>) {
this.backingList.replaceAll(operator)
}
override fun sort(c: Comparator<in Instruction>) {
this.backingList.sortedWith(c)
}
override fun add(instruction: Instruction): Boolean {
return this.backingList.add(instruction)
}
override fun remove(o: Any): Boolean {
return this.backingList.remove(o)
}
override fun addAll(c: Collection<Instruction>): Boolean {
return this.backingList.addAll(c)
}
override fun addAll(index: Int, c: Collection<Instruction>): Boolean {
return this.backingList.addAll(index, c)
}
override fun addAll(index: Int, c: Iterable<Instruction>): Boolean {
return this.addAll(index, c.toList())
}
override fun removeAll(c: Collection<*>): Boolean {
return this.backingList.removeAll(c)
}
override fun retainAll(c: Collection<*>): Boolean {
return this.backingList.retainAll(c)
}
override fun removeAll(c: Iterable<Instruction>): Boolean {
return this.backingList.removeAll(c)
}
override fun retainAll(c: Iterable<Instruction>): Boolean {
return this.backingList.retainAll(c)
}
override fun clear() {
this.backingList.clear()
}
override fun add(index: Int, element: Instruction) {
return this.backingList.add(index, element)
}
override fun remove(index: Int): Instruction {
return this.backingList.removeAt(index)
}
override operator fun plusAssign(other: Iterable<Instruction>) {
this.addAll(other)
}
override operator fun minusAssign(other: Iterable<Instruction>) {
this.removeAll(other)
}
override operator fun plusAssign(other: Instruction) {
this.add(other)
}
override operator fun minusAssign(other: Instruction) {
this.remove(other)
}
override fun subSource(fromIndex: Int, toIndex: Int): MutableInstructions {
if (fromIndex < 0 || toIndex > this.size || fromIndex > toIndex)
throw IndexOutOfBoundsException("fromIndex: $fromIndex, toIndex: $toIndex")
return InstructionsView(this, fromIndex, toIndex)
}
override operator fun plus(other: Instruction): MutableInstructions =
ListInstructions(this.backingList + other)
override operator fun minus(other: Instruction): MutableInstructions =
ListInstructions(this.backingList - other)
override operator fun plus(other: Iterable<Instruction>): MutableInstructions =
ListInstructions(this.backingList + other)
override operator fun minus(other: Iterable<Instruction>): MutableInstructions =
ListInstructions(this.backingList - other)
override fun contains(o: Any): Boolean = this.backingList.contains(o)
override fun iterator(): Iterator<Instruction> = this.backingList.iterator()
override fun toArray(): Array<Instruction> = this.backingList.toTypedArray()
override fun containsAll(c: Collection<*>): Boolean = this.backingList.containsAll(c)
override fun getAtIndex(index: Int): Instruction = this.backingList[index]
override operator fun set(index: Int, element: Instruction): Instruction =
this.backingList.set(index, element)
override fun indexOf(o: Any): Int = this.backingList.indexOf(o)
override fun lastIndexOf(o: Any): Int = this.backingList.lastIndexOf(o)
override fun listIterator(): ListIterator<Instruction> = this.backingList.listIterator()
override fun listIterator(index: Int): ListIterator<Instruction> =
this.backingList.listIterator(index)
override fun clone(): Any = ListInstructions(this.backingList)
override fun forEach(action: Consumer<in Instruction>) {
this.backingList.forEach(action)
}
override fun spliterator(): Spliterator<Instruction> = this.backingList.spliterator()
override fun equals(other: Any?): Boolean = this.backingList == other
override fun hashCode(): Int = this.backingList.hashCode()
override fun toString(): String =
if (this.isEmpty) "ListInstructions[]" else "ListInstructions[...]"
override fun stream(): Stream<Instruction> = this.backingList.stream()
override fun parallelStream(): Stream<Instruction> = this.backingList.parallelStream()
override fun toImmutable(): Instructions = Instructions.fromArray(this.toArray())
override fun toMutable(): MutableInstructions = ListInstructions(this)
companion object {
@JvmStatic
inline fun ListInstructions(
size: Int,
init: (index: Int) -> Instruction
): ListInstructions =
ListInstructions(MutableList(size, init))
}
}
| mit | eca63f49b99fba378d9e7c1ca1dd812f | 33.81 | 118 | 0.69707 | 4.592348 | false | false | false | false |
cdietze/klay | src/main/kotlin/klay/core/Canvas.kt | 1 | 15170 | package klay.core
import euklid.f.IRectangle
import euklid.f.XY
/**
* A 2D drawing canvas. Rendering is performed by the CPU into a bitmap.
*/
abstract class Canvas(val gfx: Graphics,
/** The image that underlies this canvas. */
val image: Image) {
/**
* Values that may be used with
* [Canvas.setCompositeOperation].
*/
enum class Composite {
/** A (B is ignored). Display the source image instead of the destination image.
* `[Sa, Sc]` */
SRC,
/** B atop A. Same as source-atop but using the destination image instead of the source image
* and vice versa. `[Sa, Sa * Dc + Sc * (1 - Da)]`. */
DST_ATOP,
/** A over B. Display the source image wherever the source image is opaque. Display the
* destination image elsewhere. `[Sa + (1 - Sa)*Da, Rc = Sc + (1 - Sa)*Dc]`. */
SRC_OVER,
/** B over A. Same as source-over but using the destination image instead of the source image
* and vice versa. `[Sa + (1 - Sa)*Da, Rc = Dc + (1 - Da)*Sc]`. */
DST_OVER,
/** A in B. Display the source image wherever both the source image and destination image are
* opaque. Display transparency elsewhere. `[Sa * Da, Sc * Da]`. */
SRC_IN,
/** B in A. Same as source-in but using the destination image instead of the
* source image and vice versa. `[Sa * Da, Sa * Dc]`. */
DST_IN,
/** A out B. Display the source image wherever the source image is opaque and the destination
* image is transparent. Display transparency elsewhere.
* `[Sa * (1 - Da), Sc * (1 - Da)]`. */
SRC_OUT,
/** B out A. Same as source-out but using the destination image instead of
* the source image and vice versa. `[Da * (1 - Sa), Dc * (1 - Sa)]`. */
DST_OUT,
/** A atop B. Display the source image wherever both images are opaque. Display the destination
* image wherever the destination image is opaque but the source image is transparent. Display
* transparency elsewhere. `[Da, Sc * Da + (1 - Sa) * Dc]`. */
SRC_ATOP,
/** A xor B. Exclusive OR of the source image and destination image.
* `[Sa + Da - 2 * Sa * Da, Sc * (1 - Da) + (1 - Sa) * Dc]`. */
XOR,
/** A * B. Multiplies the source and destination images. **NOTE:** this is not supported by
* the HTML5 and Flash backends. `[Sa * Da, Sc * Dc]`. */
MULTIPLY
}
/**
* Values that may be used with [Canvas.setLineCap].
*/
enum class LineCap {
BUTT, ROUND, SQUARE
}
/**
* Values that may be used with [Canvas.setLineJoin].
*/
enum class LineJoin {
BEVEL, MITER, ROUND
}
/** Facilitates drawing images and image regions to a canvas. */
interface Drawable {
val width: Float
val height: Float
fun draw(gc: Any, x: Float, y: Float, width: Float, height: Float)
fun draw(gc: Any, dx: Float, dy: Float, dw: Float, dh: Float,
sx: Float, sy: Float, sw: Float, sh: Float)
}
/** The width of this canvas. */
val width: Float = image.width
/** The height of this canvas. */
val height: Float = image.height
/**
* Returns an immutable snapshot of the image that backs this canvas. Subsequent changes to this
* canvas will not be reflected in the returned image. If you are going to render a canvas
* image into another canvas image a lot, using a snapshot can improve performance.
*/
abstract fun snapshot(): Image
/**
* Informs the platform that this canvas, and its backing image will no longer be used. On some
* platforms this can free up memory earlier than if we waited for the canvas to be garbage
* collected.
*/
fun close() {} // nada by default
/** Clears the entire canvas to `rgba(0, 0, 0, 0)`. */
abstract fun clear(): Canvas
/** Clears the specified region to `rgba (0, 0, 0, 0)`. */
abstract fun clearRect(x: Float, y: Float, width: Float, height: Float): Canvas
/** Clears the specified region to `rgba (0, 0, 0, 0)`. */
fun clearRect(rect: IRectangle): Canvas = clearRect(rect.x, rect.y, rect.width, rect.height)
/** Intersects the current clip with the specified path. */
abstract fun clip(clipPath: Path): Canvas
/** Intersects the current clip with the supplied rectangle. */
abstract fun clipRect(x: Float, y: Float, width: Float, height: Float): Canvas
/** Intersects the current clip with the supplied rectangle. */
fun clipRect(rect: IRectangle): Canvas = clipRect(rect.x, rect.y, rect.width, rect.height)
/** Creates a path object. */
abstract fun createPath(): Path
/** Creates a gradient fill pattern. */
abstract fun createGradient(config: Gradient.Config): Gradient
/**
* Draws `image` centered at the specified location. Subtracts `image.width/2` from x
* and `image.height/2` from y.
*/
fun drawCentered(image: Drawable, x: Float, y: Float): Canvas {
return draw(image, x - image.width / 2, y - image.height / 2)
}
/**
* Draws `image` centered at the specified location. Subtracts `image.width/2` from x
* and `image.height/2` from y.
*/
fun drawCentered(image: Drawable, xy: XY): Canvas = drawCentered(image, xy.x, xy.y)
/**
* Draws a scaled image at the specified location `(x, y)` size `(w x h)`.
*/
fun draw(image: Drawable, x: Float, y: Float, w: Float = image.width, h: Float = image.height): Canvas {
image.draw(gc(), x, y, w, h)
isDirty = true
return this
}
/**
* Draws a subregion of a image `(sw x sh) @ (sx, sy)` at the specified size
* `(dw x dh)` and location `(dx, dy)`.
* TODO (jgw): Document whether out-of-bounds source coordinates clamp, repeat, or do nothing.
*/
fun draw(image: Drawable, dx: Float, dy: Float, dw: Float, dh: Float,
sx: Float, sy: Float, sw: Float, sh: Float): Canvas {
image.draw(gc(), dx, dy, dw, dh, sx, sy, sw, sh)
isDirty = true
return this
}
/**
* Draws a line between the two specified points.
*/
abstract fun drawLine(x0: Float, y0: Float, x1: Float, y1: Float): Canvas
/**
* Draws a line between the two specified points.
*/
fun drawLine(a: XY, b: XY): Canvas = drawLine(a.x, a.y, b.x, b.y)
/**
* Draws a single point at the specified location.
*/
abstract fun drawPoint(x: Float, y: Float): Canvas
/**
* Draws a single point at the specified location.
*/
fun drawPoint(location: XY): Canvas = drawPoint(location.x, location.y)
/**
* Draws text at the specified location. The text will be drawn in the current fill color.
*/
abstract fun drawText(text: String, x: Float, y: Float): Canvas
/**
* Draws text at the specified location. The text will be drawn in the current fill color.
*/
fun drawText(text: String, location: XY): Canvas = drawText(text, location.x, location.y)
/**
* Fills a circle at the specified center and radius.
*/
abstract fun fillCircle(x: Float, y: Float, radius: Float): Canvas
/**
* Fills a circle at the specified center and radius.
*/
fun fillCircle(center: XY, radius: Float): Canvas = fillCircle(center.x, center.y, radius)
/**
* Fills the specified path.
*/
abstract fun fillPath(path: Path): Canvas
/**
* Fills the specified rectangle.
*/
abstract fun fillRect(x: Float, y: Float, width: Float, height: Float): Canvas
/**
* Fills the specified rectangle.
*/
fun fillRect(rect: IRectangle): Canvas = fillRect(rect.x, rect.y, rect.width, rect.height)
/**
* Fills the specified rounded rectangle.
* @param x the x coordinate of the upper left of the rounded rectangle.
* @param y the y coordinate of the upper left of the rounded rectangle.
* @param width the width of the rounded rectangle.
* @param height the width of the rounded rectangle.
* @param radius the radius of the circle to use for the corner.
*/
abstract fun fillRoundRect(x: Float, y: Float, width: Float, height: Float, radius: Float): Canvas
/**
* Fills the specified rounded rectangle.
* @param rect the rounded rectangle.
* @param radius the radius of the circle to use for the corner.
*/
fun fillRoundRect(rect: IRectangle, radius: Float): Canvas = fillRoundRect(rect.x, rect.y, rect.width, rect.height, radius)
/**
* Fills the text at the specified location. The text will use the current fill color.
*/
abstract fun fillText(text: TextLayout, x: Float, y: Float): Canvas
/**
* Fills the text at the specified location. The text will use the current fill color.
*/
fun fillText(text: TextLayout, location: XY): Canvas = fillText(text, location.x, location.y)
/**
* Restores the canvas's previous state.
* @see .save
*/
abstract fun restore(): Canvas
/**
* Rotates the current transformation matrix by the specified angle in radians.
*/
abstract fun rotate(radians: Float): Canvas
/**
* The save and restore methods preserve and restore the state of the canvas,
* but not specific paths or graphics.
* The following values are saved:
*
* * transformation matrix
* * clipping path
* * stroke color
* * stroke width
* * line cap
* * line join
* * miter limit
* * fill color or gradient
* * composite operation
*
*/
abstract fun save(): Canvas
/**
* Scales the current transformation matrix by the specified amount.
*/
abstract fun scale(x: Float, y: Float): Canvas
/**
* Scales the current transformation matrix by the specified amount.
*/
fun scale(scale: XY): Canvas = scale(scale.x, scale.y)
/**
* Set the global alpha value to be used for all painting.
* Values outside the range [0,1] will be clamped to the range [0,1].
* @param alpha alpha value in range [0,1] where 0 is transparent and 1 is opaque
*/
abstract fun setAlpha(alpha: Float): Canvas
/**
* Sets the Porter-Duff composite operation to be used for all painting.
*/
abstract fun setCompositeOperation(composite: Composite): Canvas
/**
* Sets the color to be used for fill operations. This replaces any existing
* fill gradient or pattern.
*/
abstract fun setFillColor(color: Int): Canvas
/**
* Sets the gradient to be used for fill operations. This replaces any
* existing fill color or pattern.
*/
abstract fun setFillGradient(gradient: Gradient): Canvas
/**
* Sets the pattern to be used for fill operations. This replaces any existing
* fill color or gradient.
*/
abstract fun setFillPattern(pattern: Pattern): Canvas
/**
* Sets the line-cap mode for strokes.
*/
abstract fun setLineCap(cap: LineCap): Canvas
/**
* Sets the line-join mode for strokes.
*/
abstract fun setLineJoin(join: LineJoin): Canvas
/**
* Sets the miter limit for strokes.
*/
abstract fun setMiterLimit(miter: Float): Canvas
/**
* Sets the color for strokes.
*/
abstract fun setStrokeColor(color: Int): Canvas
/**
* Sets the width for strokes, in pixels.
*/
abstract fun setStrokeWidth(strokeWidth: Float): Canvas
/**
* Strokes a circle at the specified center and radius.
*/
abstract fun strokeCircle(x: Float, y: Float, radius: Float): Canvas
/**
* Strokes a circle at the specified center and radius.
*/
fun strokeCircle(center: XY, radius: Float): Canvas = strokeCircle(center.x, center.y, radius)
/**
* Strokes the specified path.
*/
abstract fun strokePath(path: Path): Canvas
/**
* Strokes the specified rectangle.
*/
abstract fun strokeRect(x: Float, y: Float, width: Float, height: Float): Canvas
/**
* Strokes the specified rectangle.
*/
fun strokeRect(rect: IRectangle): Canvas = strokeRect(rect.x, rect.y, rect.width, rect.height)
/**
* Strokes the specified rounded rectangle.
* @param x the x coordinate of the upper left of the rounded rectangle.
* @param y the y coordinate of the upper left of the rounded rectangle.
* @param width the width of the rounded rectangle.
* @param height the width of the rounded rectangle.
* @param radius the radius of the circle to use for the corner.
*/
abstract fun strokeRoundRect(x: Float, y: Float, width: Float, height: Float, radius: Float): Canvas
/**
* Strokes the specified rounded rectangle.
* @param rect the rounded rectangle.
* @param radius the radius of the circle to use for the corner.
*/
fun strokeRoundRect(rect: IRectangle, radius: Float): Canvas = strokeRoundRect(rect.x, rect.y, rect.width, rect.height, radius)
/**
* Strokes the text at the specified location. The text will use the current stroke configuration
* (color, width, etc.).
*/
abstract fun strokeText(text: TextLayout, x: Float, y: Float): Canvas
/**
* Strokes the text at the specified location. The text will use the current stroke configuration
* (color, width, etc.).
*/
fun strokeText(text: TextLayout, location: XY): Canvas = strokeText(text, location.x, location.y)
/** A helper function for creating a texture from this canvas's image, and then disposing this
* canvas. This is useful for situations where you create a canvas, draw something in it, turn
* it into a texture and then never use the canvas again. */
fun toTexture(config: Texture.Config = Texture.Config.DEFAULT): Texture {
try {
return image.createTexture(config)
} finally {
close()
}
}
/**
* Multiplies the current transformation matrix by the given matrix.
*/
abstract fun transform(m11: Float, m12: Float, m21: Float, m22: Float, dx: Float, dy: Float): Canvas
/**
* Translates the current transformation matrix by the given amount.
*/
abstract fun translate(x: Float, y: Float): Canvas
/**
* Translates the current transformation matrix by the given amount.
*/
fun translate(xy: XY): Canvas = translate(xy.x, xy.y)
/** Used to track modifications to our underlying image. */
protected var isDirty: Boolean = false
init {
if (width <= 0 || height <= 0)
throw IllegalArgumentException(
"Canvas must be > 0 in width and height: " + width + "x" + height)
}
/** Returns the platform dependent graphics context for this canvas. */
protected abstract fun gc(): Any
}
/**
* Draws `image` at the specified location `(x, y)`.
*/
/** Calls [.toTexture] with the default texture config. */
| apache-2.0 | 6e4d49b65e43605997d39e588a1ece77 | 34.526932 | 131 | 0.620831 | 4.084545 | false | false | false | false |
paplorinc/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModulePointerManagerImpl.kt | 6 | 5689 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.module.impl
import com.intellij.ProjectTopics
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModulePointer
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.util.Function
import com.intellij.util.containers.MultiMap
import gnu.trove.THashMap
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
/**
* @author nik
*/
@State(name = "ModuleRenamingHistory", storages = [(Storage("modules.xml"))])
class ModulePointerManagerImpl(private val project: Project) : ModulePointerManager(), PersistentStateComponent<ModuleRenamingHistoryState> {
private val unresolved = MultiMap.createSmart<String, ModulePointerImpl>()
private val pointers = MultiMap.createSmart<Module, ModulePointerImpl>()
private val lock = ReentrantReadWriteLock()
private val oldToNewName = THashMap<String, String>()
init {
project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun beforeModuleRemoved(project: Project, module: Module) {
unregisterPointer(module)
}
override fun moduleAdded(project: Project, module: Module) {
moduleAppears(module)
}
override fun modulesRenamed(project: Project, modules: List<Module>, oldNameProvider: Function<Module, String>) {
for (module in modules) {
moduleAppears(module)
}
val renamedOldToNew = modules.associateBy({ oldNameProvider.`fun`(it) }, { it.name })
oldToNewName.transformValues { newName -> renamedOldToNew[newName] ?: newName }
}
})
}
override fun getState(): ModuleRenamingHistoryState = ModuleRenamingHistoryState().apply {
lock.read {
oldToNewName.putAll([email protected])
}
}
override fun loadState(state: ModuleRenamingHistoryState) {
setRenamingScheme(state.oldToNewName)
}
fun setRenamingScheme(renamingScheme: Map<String, String>) {
lock.write {
oldToNewName.clear()
oldToNewName.putAll(renamingScheme)
val moduleManager = ModuleManager.getInstance(project)
renamingScheme.entries.forEach { (oldName, newName) ->
val oldModule = moduleManager.findModuleByName(oldName)
if (oldModule != null) {
unregisterPointer(oldModule)
}
updateUnresolvedPointers(oldName, newName, moduleManager)
}
}
}
private fun updateUnresolvedPointers(oldName: String,
newName: String,
moduleManager: ModuleManager) {
val pointers = unresolved.remove(oldName)
pointers?.forEach { pointer ->
pointer.renameUnresolved(newName)
val module = moduleManager.findModuleByName(newName)
if (module != null) {
pointer.moduleAdded(module)
registerPointer(module, pointer)
}
else {
unresolved.putValue(newName, pointer)
}
}
}
private fun moduleAppears(module: Module) {
lock.write {
unresolved.remove(module.name)?.forEach {
it.moduleAdded(module)
registerPointer(module, it)
}
}
}
private fun registerPointer(module: Module, pointer: ModulePointerImpl) {
pointers.putValue(module, pointer)
Disposer.register(module, Disposable { unregisterPointer(module) })
}
private fun unregisterPointer(module: Module) {
lock.write {
pointers.remove(module)?.forEach {
it.moduleRemoved(module)
unresolved.putValue(it.moduleName, it)
}
}
}
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
override fun create(module: Module): ModulePointer {
return lock.read { pointers.get(module).firstOrNull() } ?: lock.write {
pointers.get(module).firstOrNull()?.let {
return it
}
val pointers = unresolved.remove(module.name)
if (pointers == null || pointers.isEmpty()) {
val pointer = ModulePointerImpl(module, lock)
registerPointer(module, pointer)
pointer
}
else {
pointers.forEach {
it.moduleAdded(module)
registerPointer(module, it)
}
pointers.first()
}
}
}
override fun create(moduleName: String): ModulePointer {
ModuleManager.getInstance(project).findModuleByName(moduleName)?.let {
return create(it)
}
val newName = lock.read { oldToNewName[moduleName] }
if (newName != null) {
ModuleManager.getInstance(project).findModuleByName(newName)?.let {
return create(it)
}
}
return lock.read {
unresolved.get(moduleName).firstOrNull() ?: lock.write {
unresolved.get(moduleName).firstOrNull()?.let {
return it
}
// let's find in the pointers (if model not committed, see testDisposePointerFromUncommittedModifiableModel)
pointers.keySet().firstOrNull { it.name == moduleName }?.let {
return create(it)
}
val pointer = ModulePointerImpl(moduleName, lock)
unresolved.putValue(moduleName, pointer)
pointer
}
}
}
}
| apache-2.0 | 3b3cd9ab31c2c571da449a753d6bd7c1 | 32.269006 | 141 | 0.689401 | 4.632736 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/contents/Cell.kt | 1 | 3933 | // Copyright 2013-03-03 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr 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.
//
// PdfLayoutMgr 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 PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.contents
import com.planbase.pdf.lm2.attributes.CellStyle
import com.planbase.pdf.lm2.attributes.CellStyle.Companion.TOP_LEFT_BORDERLESS
import com.planbase.pdf.lm2.lineWrapping.LineWrappable
import com.planbase.pdf.lm2.lineWrapping.LineWrapped
import com.planbase.pdf.lm2.lineWrapping.LineWrapper
import com.planbase.pdf.lm2.lineWrapping.MultiLineWrapped.Companion.wrapLines
import com.planbase.pdf.lm2.utils.Dim
import com.planbase.pdf.lm2.utils.listToStr
import org.organicdesign.indented.IndentedStringable
// TODO: Consider making this an abstract class "Box" with subclasses TableCell and Div
/**
* A styled table cell or layout block with a pre-set horizontal width. Vertical height is calculated
* based on how the content is rendered with regard to line-breaks and page-breaks.
* @param cellStyle the style info for this cell
* @param width the width of this cell (in document units)
* @param contents the contents of this cell
* @param requiredSpaceBelow leave this much vertical space at the end of the page below this cell.
*/
data class Cell(val cellStyle: CellStyle = TOP_LEFT_BORDERLESS,
val width: Double,
private var contents: List<LineWrappable>,
private val requiredSpaceBelow : Double) : LineWrappable, IndentedStringable {
constructor(cellStyle: CellStyle = TOP_LEFT_BORDERLESS,
width: Double,
contents: List<LineWrappable>) : this(cellStyle, width, contents, 0.0)
init {
if (width < 0) {
throw IllegalArgumentException("A cell cannot have a negative width")
}
// if ( (tableRow != null) && (requiredSpaceBelow != 0.0) ) {
// throw IllegalArgumentException("Can either be a table cell or have required space below, not both.")
// }
}
fun wrap() : WrappedCell {
// println("Wrapping: $this")
val fixedLines: List<LineWrapped> = wrapLines(contents,
width - cellStyle.boxStyle.leftRightInteriorSp())
// var maxWidth = cellStyle.boxStyle.leftRightThickness()
var height = cellStyle.boxStyle.topBottomInteriorSp()
for (line in fixedLines) {
height += line.dim.height
// println("height=$height")
// maxWidth = maxOf(line.dim.width, maxWidth)
}
// if ( (tableRow != null) &&
// (height < tableRow.minRowHeight) ) {
// height = tableRow.minRowHeight
// }
return WrappedCell(Dim(width, height), this.cellStyle, fixedLines, requiredSpaceBelow)
}
override fun lineWrapper() = LineWrapper.preWrappedLineWrapper(this.wrap())
override fun indentedStr(indent: Int): String =
"Cell($cellStyle, $width, contents=\n" +
"${listToStr(indent + "Cell(".length, contents)})"
override fun toString() = indentedStr(0)
fun toStringTable() =
"\n.cell($cellStyle, ${listToStr(0, contents)})"
}
| agpl-3.0 | d3d5ee673421d74fd889fc9aa7979abc | 41.75 | 114 | 0.686245 | 4.242718 | false | false | false | false |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/EventDispatcher.kt | 7 | 6267 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.util.SystemInfo
import java.awt.Component
import java.awt.Container
import java.awt.KeyboardFocusManager
import java.awt.Point
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.awt.event.MouseEvent.*
import java.util.*
import javax.swing.JFrame
import javax.swing.KeyStroke
import javax.swing.RootPaneContainer
import javax.swing.SwingUtilities
object EventDispatcher {
private val LOG = Logger.getInstance("#${EventDispatcher::class.qualifiedName}")
private val MAC_NATIVE_ACTIONS = arrayOf("ShowSettings", "EditorEscape")
object SelectionProcessor {
private var firstEvent: MouseEvent? = null
fun processDragging(event: MouseEvent) {
if (firstEvent == null) firstEvent = event
}
fun stopDragging(event: MouseEvent) {
if (firstEvent != null) {
processSelection(firstEvent!!, event)
firstEvent = null
}
}
private fun processSelection(firstEvent: MouseEvent, lastEvent: MouseEvent) {
val firstComponent: Component? = findComponent(firstEvent)
val lastComponent: Component? = findComponent(lastEvent)
//drag and drop between components is not supported yet
if (lastComponent != firstComponent) return
if (lastComponent != null) {
val firstPoint = getPoint(firstEvent, lastComponent)
val lastPoint = getPoint(lastEvent, lastComponent)
ScriptGenerator.selectInComponent(lastComponent, firstPoint, lastPoint, lastEvent)
}
}
}
fun processMouseEvent(event: MouseEvent) {
if (isMainFrame(event.component)) return
when(event.id) {
MOUSE_PRESSED -> { processClick(event) }
MOUSE_DRAGGED -> { SelectionProcessor.processDragging(event) }
MOUSE_RELEASED -> { SelectionProcessor.stopDragging(event) }
}
}
private fun processClick(event: MouseEvent){
val actualComponent: Component? = findComponent(event)
if (actualComponent != null) {
LOG.info("Delegate click from component:${actualComponent}")
val convertedPoint = Point(event.locationOnScreen.x - actualComponent.locationOnScreen.x,
event.locationOnScreen.y - actualComponent.locationOnScreen.y)
ScriptGenerator.clickComponent(actualComponent, convertedPoint, event)
}
}
private fun getPoint(event: MouseEvent, component: Component): Point {
return Point(event.locationOnScreen.x - component.locationOnScreen.x, event.locationOnScreen.y - component.locationOnScreen.y)
}
private fun findComponent(event: MouseEvent): Component? {
val mousePoint = event.point
val eventComponent = event.component
var actualComponent: Component? = null
when (eventComponent) {
is RootPaneContainer -> {
val layeredPane = eventComponent.layeredPane
val point = SwingUtilities.convertPoint(eventComponent, mousePoint, layeredPane)
actualComponent = layeredPane.findComponentAt(point)
}
is Container -> actualComponent = eventComponent.findComponentAt(mousePoint)
}
if (actualComponent == null) actualComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner
return actualComponent
}
fun processKeyBoardEvent(keyEvent: KeyEvent) {
if (isMainFrame(keyEvent.component)) return
if (keyEvent.id == KeyEvent.KEY_TYPED) ScriptGenerator.processTyping(keyEvent)
if (SystemInfo.isMac && keyEvent.id == KeyEvent.KEY_PRESSED) {
//we are redirecting native Mac action as an Intellij actions
LOG.info(keyEvent.toString())
val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent))
for(actionId in actionIds){
if(isMacNativeAction(keyEvent)) {
val action = ActionManager.getInstance().getAction(actionId)
val actionEvent = AnActionEvent.createFromInputEvent(keyEvent, ActionPlaces.UNKNOWN, action.templatePresentation,
DataContext.EMPTY_CONTEXT)
ScriptGenerator.processKeyActionEvent(action, actionEvent)
}
}
}
}
fun processActionEvent(action: AnAction, event: AnActionEvent?) {
if (event == null) return
val inputEvent = event.inputEvent
if (inputEvent is KeyEvent) {
if(!isMacNativeAction(inputEvent)) {
ScriptGenerator.processKeyActionEvent(action, event)
}
} else {
val actionManager = ActionManager.getInstance()
val mainActions = (actionManager.getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup).getFlatIdList()
if (mainActions.contains(actionManager.getId(action))) ScriptGenerator.processMainMenuActionEvent(action, event)
}
}
private fun ActionGroup.getFlatIdList(): List<String> {
val actionManager = ActionManager.getInstance()
val result = ArrayList<String>()
this.getChildren(null).forEach { action ->
if (action is ActionGroup) result.addAll(action.getFlatIdList())
else result.add(actionManager.getId(action))
}
return result
}
private fun isMainFrame(component: Component?): Boolean {
return component is JFrame && component.title == "GUI Script Editor"
}
private fun isMacNativeAction(keyEvent: KeyEvent): Boolean{
if (!SystemInfo.isMac) return false
val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent))
return actionIds.any { it in MAC_NATIVE_ACTIONS }
}
} | apache-2.0 | 6521dbf0cfe2bdf3763aedbbfc8884ed | 37.931677 | 130 | 0.72427 | 4.736961 | false | false | false | false |
paplorinc/intellij-community | platform/platform-api/src/com/intellij/ui/tabs/newImpl/JBDefaultTabPainter.kt | 1 | 2666 | // 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.ui.tabs.newImpl
import com.intellij.ui.paint.LinePainter2D
import com.intellij.ui.tabs.JBTabPainter
import com.intellij.ui.tabs.JBTabsPosition
import com.intellij.ui.tabs.TabTheme
import com.jetbrains.rd.swing.fillRect
import java.awt.Color
import java.awt.Graphics2D
import java.awt.Point
import java.awt.Rectangle
open class JBDefaultTabPainter(val theme : TabTheme = TabTheme()) : JBTabPainter {
override fun getBackgroundColor(): Color = theme.background ?: theme.borderColor
override fun fillBackground(g: Graphics2D, rect: Rectangle) {
theme.background?.let{
g.fillRect(rect, theme.background)
}
}
override fun paintTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int, tabColor: Color?, hovered: Boolean) {
tabColor?.let {
g.fillRect(rect, tabColor)
}
if(hovered) {
g.fillRect(rect, if(tabColor != null) theme.hoverMaskColor else theme.borderColor)
return
}
tabColor ?: return
g.fillRect(rect, theme.inactiveMaskColor)
}
override fun paintSelectedTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, tabColor: Color?, active: Boolean, hovered: Boolean) {
val color = tabColor ?: theme.background
/**
* background filled for editors tab dragging
*/
color?.let {
g.fillRect(rect, color)
}
if(hovered) {
g.fillRect(rect, if(tabColor != null) theme.hoverMaskColor else theme.borderColor)
}
val underline = underlineRectangle(position, rect, theme.underlineHeight)
g.fillRect(underline, if(active) theme.underlineColor else theme.inactiveUnderlineColor)
}
override fun paintBorderLine(g: Graphics2D, thickness: Int, from: Point, to: Point) {
g.color = theme.borderColor
/**
* unexpected behaviour of {@link #LinePainter2D.paint(java.awt.Graphics2D, double, double, double, double, com.intellij.ui.paint.LinePainter2D.StrokeType, double)}
*/
if (thickness == 1) {
LinePainter2D.paint(g, from.getX(), from.getY(), to.getX(), to.getY())
return
}
LinePainter2D.paint(g, from.getX(), from.getY(), to.getX(), to.getY(), LinePainter2D.StrokeType.INSIDE,
thickness.toDouble())
}
protected open fun underlineRectangle(position: JBTabsPosition,
rect: Rectangle,
thickness: Int): Rectangle {
return Rectangle(rect.x, rect.y + rect.height - thickness, rect.width, thickness)
}
} | apache-2.0 | 5ee7e4ff89abf7585c2f753c7f15e89a | 34.56 | 168 | 0.689047 | 3.961367 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/controller/LocationController.kt | 1 | 6059 | package backend.controller
import backend.configuration.CustomUserDetails
import backend.controller.exceptions.NotFoundException
import backend.controller.exceptions.UnauthorizedException
import backend.model.event.TeamService
import backend.model.location.Location
import backend.model.location.LocationService
import backend.model.misc.Coord
import backend.model.user.Participant
import backend.model.user.UserService
import backend.util.CacheNames.LOCATIONS
import backend.util.CacheNames.POSTINGS
import backend.util.localDateTimeOf
import backend.util.speedToLocation
import backend.view.BasicLocationView
import backend.view.LocationView
import backend.view.TeamLocationView
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.cache.annotation.Caching
import org.springframework.http.HttpStatus.CREATED
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
import javax.validation.Valid
@RestController
@RequestMapping("/event/{eventId}")
class LocationController(private val locationService: LocationService,
private val teamService: TeamService,
private val userService: UserService) {
private val logger: Logger = LoggerFactory.getLogger(LocationController::class.java)
/**
* GET /event/{eventId}/location/
* Return a list of all locations for a specific event
*/
@Cacheable(LOCATIONS, sync = true)
@GetMapping("/location/")
fun getAllLocationsForEvent(@PathVariable eventId: Long,
@RequestParam(value = "perTeam", required = false) perTeam: Int?): Iterable<TeamLocationView> {
return locationService.findByEventId(eventId, perTeam ?: 20).map { data ->
TeamLocationView(data.key, data.value)
}
}
/**
* GET /event/{eventId}/team/{teamId}/location/
* Return a list of all locations for a certain team at a certain event
*/
@GetMapping("/team/{teamId}/location/")
fun getAllLocationsForEventAndTeam(@PathVariable("eventId") eventId: Long,
@PathVariable("teamId") teamId: Long,
@RequestParam(value = "perTeam", required = false) perTeam: Int?): Iterable<BasicLocationView> {
val teamLocations = locationService.findByTeamId(teamId, perTeam ?: 20)
val locationPairs: MutableList<Pair<Location, Location>> = arrayListOf()
var lastLocation: Location? = null
teamLocations.forEach { thisLocation ->
if (lastLocation != null) {
locationPairs.add(Pair(lastLocation!!, thisLocation))
}
lastLocation = thisLocation
}
val speedToLocation = locationPairs.map { (first, second) ->
Pair(speedToLocation(first, second), second)
}
return teamLocations.map { location ->
BasicLocationView(location, speedToLocation.find { it.second.id == location.id }?.first)
}
}
/**
* POST /event/{eventId}/team/{teamId}/location/
* Upload a new location for a specific team at a specific event
*/
@Caching(evict = [(CacheEvict(POSTINGS, allEntries = true)), (CacheEvict(LOCATIONS, allEntries = true))])
@PreAuthorize("isAuthenticated()")
@PostMapping("/team/{teamId}/location/")
@ResponseStatus(CREATED)
fun createLocation(@PathVariable("eventId") eventId: Long,
@PathVariable("teamId") teamId: Long,
@AuthenticationPrincipal customUserDetails: CustomUserDetails,
@Valid @RequestBody locationView: LocationView): LocationView {
val user = userService.getUserFromCustomUserDetails(customUserDetails)
val participant = user.getRole(Participant::class) ?: throw UnauthorizedException("user is no participant")
val team = teamService.findOne(teamId) ?: throw NotFoundException("no team with id $teamId found")
if (!team.isMember(participant)) throw UnauthorizedException("user is not part of team $teamId are therefor cannot upload locations on it's behalf")
val coord = Coord(locationView.latitude, locationView.longitude)
val location = locationService.create(coord, participant, localDateTimeOf(epochSeconds = locationView.date))
return LocationView(location)
}
/**
* POST /event/{eventId}/team/{teamId}/location/multiple/
* Upload multiple new locations for a specific team at a specific event
*/
@Caching(evict = [(CacheEvict(POSTINGS, allEntries = true)), (CacheEvict(LOCATIONS, allEntries = true))])
@PreAuthorize("isAuthenticated()")
@PostMapping("/team/{teamId}/location/multiple/")
@ResponseStatus(CREATED)
fun createMultipleLocation(@PathVariable("eventId") eventId: Long,
@PathVariable("teamId") teamId: Long,
@AuthenticationPrincipal customUserDetails: CustomUserDetails,
@Valid @RequestBody locationViews: List<LocationView>): List<LocationView> {
val user = userService.getUserFromCustomUserDetails(customUserDetails)
val participant = user.getRole(Participant::class) ?: throw UnauthorizedException("user is no participant")
val team = teamService.findOne(teamId) ?: throw NotFoundException("no team with id $teamId found")
if (!team.isMember(participant)) throw UnauthorizedException("user is not part of team $teamId are therefor cannot upload locations on it's behalf")
return locationViews.map {
val coord = Coord(it.latitude, it.longitude)
val savedLocation = locationService.create(coord, participant, localDateTimeOf(epochSeconds = it.date))
LocationView(savedLocation)
}
}
}
| agpl-3.0 | fc21ee56d75fb664cd4aade1e087b6f1 | 44.901515 | 156 | 0.69632 | 4.978636 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/androidarch/room/RelationController.kt | 1 | 3015 | package com.esafirm.androidplayground.androidarch.room
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import com.esafirm.androidplayground.androidarch.room.database.AppDatabase
import com.esafirm.androidplayground.androidarch.room.database.Car
import com.esafirm.androidplayground.common.BaseController
import com.esafirm.androidplayground.libs.Logger
import com.esafirm.androidplayground.utils.matchParent
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
class RelationController : BaseController() {
private val database by lazy { AppDatabase.get(applicationContext!!) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View =
LinearLayout(container.context).apply {
matchParent()
orientation = LinearLayout.VERTICAL
addView(LinearLayout(container.context).apply {
matchParent(vertical = false)
addView(Button(container.context).apply {
text = "Show me all yaris owner"
setOnClickListener {
showYarisOwners()
}
})
})
addView(Logger.getLogView(container.context))
}
private fun showYarisOwners() = Completable.fromAction {
Logger.log("Yaris owners:")
database.userDao().getUsersWithCar("Yaris").forEach {
Logger.log(it.name)
}
}.subscribeOn(Schedulers.io()).subscribe()
override fun onAttach(view: View) {
super.onAttach(view)
insertData().subscribeOn(Schedulers.io()).subscribe()
getUserWithCars().subscribeOn(Schedulers.io()).subscribe()
}
private fun insertData() = Completable.fromAction {
val userDao = database.userDao()
val carDao = database.carDao();
if (carDao.getCarCount() > 0) {
return@fromAction
}
userDao.getUsers().firstOrNull()?.let { user ->
val userId = user.userId ?: throw IllegalStateException("User ID can't be empty at this point")
val cars = listOf(
Car(name = "Yaris", owner = userId),
Car(name = "Jazz", owner = userId),
Car(name = "Ayla", owner = userId),
Car(name = "Avanza", owner = userId)
)
database.carDao()
cars.forEach {
carDao.insertCar(it)
Logger.log("Inserting car $it")
}
}
}
private fun getUserWithCars() = Completable.fromAction {
Logger.log("=========")
val userDao = database.userDao()
userDao.getUserWithCars()
.filter { it.cars?.isEmpty()?.not() ?: false }
.forEach {
Logger.log("User $it")
}
}
}
| mit | f5b40c464bf761490c11e8fa57fda0ee | 33.655172 | 107 | 0.592371 | 5.016639 | false | false | false | false |
google/intellij-community | platform/execution-impl/src/com/intellij/execution/target/TargetEnvironmentWizardStepKt.kt | 3 | 3635 | // 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.execution.target
import com.intellij.execution.ExecutionBundle
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.border.CompoundBorder
abstract class TargetEnvironmentWizardStepKt(@NlsContexts.DialogTitle title: String) : TargetEnvironmentWizardStep(title) {
private val panel = object : ClearableLazyValue<JComponent>() {
override fun compute(): JComponent = createPanel()
}
private val stepDescriptionLabel = JBLabel(ExecutionBundle.message("run.on.targets.wizard.step.description"))
private val spinningLabel = JBLabel(AnimatedIcon.Default()).also {
it.isVisible = false
}
protected var stepDescription: @Nls String
@Nls get() = stepDescriptionLabel.text
set(@Nls value) {
stepDescriptionLabel.text = value
}
protected fun setSpinningVisible(visible: Boolean) {
spinningLabel.isVisible = visible
with(component) {
revalidate()
repaint()
}
}
final override fun getComponent() = panel.value
protected open fun createPanel(): JComponent {
val result = JPanel(BorderLayout(HGAP, LARGE_VGAP))
val top = createTopPanel()
result.add(top, BorderLayout.NORTH)
val mainPanel = createMainPanel()
val center = JPanel(BorderLayout())
center.add(mainPanel, BorderLayout.CENTER)
val lineBorder = JBUI.Borders.customLine(JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground(), 1, 0, 1, 0)
center.border = if (mainPanel is DialogPanel) {
val mainDialogPanelInsets = JBUI.Borders.empty(UIUtil.LARGE_VGAP, TargetEnvironmentWizard.defaultDialogInsets().right)
CompoundBorder(lineBorder, mainDialogPanelInsets)
}
else {
lineBorder
}
result.add(center, BorderLayout.CENTER)
return result
}
protected fun createTopPanel(): JComponent {
return JPanel(HorizontalLayout(ICON_GAP)).also {
val insets = TargetEnvironmentWizard.defaultDialogInsets()
it.border = JBUI.Borders.merge(JBUI.Borders.emptyTop(LARGE_VGAP),
JBUI.Borders.empty(0, insets.left, 0, insets.right),
true)
it.add(stepDescriptionLabel)
spinningLabel.isVisible = false
it.add(spinningLabel)
}
}
protected open fun createMainPanel(): JComponent {
return JPanel()
}
override fun dispose() {
super.dispose()
panel.drop()
}
companion object {
@JvmStatic
val ICON_GAP = JBUIScale.scale(6)
@JvmStatic
val HGAP = JBUIScale.scale(UIUtil.DEFAULT_HGAP)
@JvmStatic
val VGAP = JBUIScale.scale(UIUtil.DEFAULT_VGAP)
@JvmStatic
val LARGE_VGAP = JBUIScale.scale(UIUtil.LARGE_VGAP)
@JvmStatic
@Nls
fun formatStepLabel(step: Int, totalSteps: Int = 3, @Nls message: String): String {
@NlsSafe val description = "$step/$totalSteps. $message"
return HtmlChunk.text(description).wrapWith(HtmlChunk.html()).toString()
}
}
} | apache-2.0 | 1f882a6af0bb03449db9ab3750012a06 | 31.464286 | 140 | 0.724622 | 4.317102 | false | false | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ChangesViewCommitWorkflowHandler.kt | 1 | 11468 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.application.subscribe
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER
import com.intellij.openapi.vcs.changes.*
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.CollectionFactory
import java.util.*
import kotlin.properties.Delegates.observable
private fun Collection<Change>.toPartialAwareSet() =
CollectionFactory.createCustomHashingStrategySet(ChangeListChange.HASHING_STRATEGY)
.also { it.addAll(this) }
internal class ChangesViewCommitWorkflowHandler(
override val workflow: ChangesViewCommitWorkflow,
override val ui: ChangesViewCommitWorkflowUi
) : NonModalCommitWorkflowHandler<ChangesViewCommitWorkflow, ChangesViewCommitWorkflowUi>(),
CommitAuthorListener,
ProjectManagerListener {
override val commitPanel: CheckinProjectPanel = CommitProjectPanelAdapter(this)
override val amendCommitHandler: NonModalAmendCommitHandler = NonModalAmendCommitHandler(this)
override val commitAuthorTracker: CommitAuthorTracker get() = ui
private fun getCommitState(): ChangeListCommitState {
val changes = getIncludedChanges()
val changeList = workflow.getAffectedChangeList(changes)
return ChangeListCommitState(changeList, changes, getCommitMessage())
}
private val activityEventDispatcher = EventDispatcher.create(ActivityListener::class.java)
private val changeListManager = ChangeListManagerEx.getInstanceEx(project)
private var knownActiveChanges: Collection<Change> = emptyList()
private val inclusionModel = PartialCommitInclusionModel(project)
private val commitMessagePolicy = ChangesViewCommitMessagePolicy(project)
private var currentChangeList by observable<LocalChangeList?>(null) { _, oldValue, newValue ->
if (oldValue?.id != newValue?.id) {
changeListChanged(oldValue, newValue)
changeListDataChanged()
}
else if (oldValue?.data != newValue?.data) {
changeListDataChanged()
}
}
init {
Disposer.register(this, inclusionModel)
Disposer.register(this, ui)
workflow.addListener(this, this)
workflow.addVcsCommitListener(GitCommitStateCleaner(), this)
ui.addCommitAuthorListener(this, this)
ui.addExecutorListener(this, this)
ui.addDataProvider(createDataProvider())
ui.addInclusionListener(this, this)
ui.inclusionModel = inclusionModel
Disposer.register(inclusionModel, Disposable { ui.inclusionModel = null })
ui.setCompletionContext(changeListManager.changeLists)
setupDumbModeTracking()
ProjectManager.TOPIC.subscribe(this, this)
setupCommitHandlersTracking()
setupCommitChecksResultTracking()
vcsesChanged() // as currently vcses are set before handler subscribes to corresponding event
currentChangeList = workflow.getAffectedChangeList(emptySet())
if (isToggleMode()) deactivate(false)
val busConnection = project.messageBus.connect(this)
CommitModeManager.subscribeOnCommitModeChange(busConnection, object : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
if (isToggleMode()) {
deactivate(false)
}
else {
activate()
}
}
})
DelayedCommitMessageProvider.init(project, ui, getCommitMessageFromPolicy(currentChangeList))
}
override fun createDataProvider(): DataProvider = object : DataProvider {
private val superProvider = [email protected]()
override fun getData(dataId: String): Any? =
if (COMMIT_WORKFLOW_HANDLER.`is`(dataId)) [email protected] { it.isActive }
else superProvider.getData(dataId)
}
override fun commitOptionsCreated() {
currentChangeList?.let { commitOptions.changeListChanged(it) }
}
override fun executionEnded() {
super.executionEnded()
ui.endExecution()
}
fun synchronizeInclusion(changeLists: List<LocalChangeList>, unversionedFiles: List<FilePath>) {
if (!inclusionModel.isInclusionEmpty()) {
val possibleInclusion = CollectionFactory.createCustomHashingStrategySet(ChangeListChange.HASHING_STRATEGY)
possibleInclusion.addAll(changeLists.asSequence().flatMap { it.changes })
possibleInclusion.addAll(unversionedFiles)
inclusionModel.retainInclusion(possibleInclusion)
}
if (knownActiveChanges.isNotEmpty()) {
val activeChanges = changeListManager.defaultChangeList.changes
knownActiveChanges = knownActiveChanges.intersect(activeChanges)
}
inclusionModel.changeLists = changeLists
ui.setCompletionContext(changeLists)
}
fun setCommitState(changeList: LocalChangeList, items: Collection<Any>, force: Boolean) {
setInclusion(items, force)
setSelection(changeList)
}
private fun setInclusion(items: Collection<Any>, force: Boolean) {
val activeChanges = changeListManager.defaultChangeList.changes
if (!isActive || force) {
inclusionModel.clearInclusion()
inclusionModel.addInclusion(items)
knownActiveChanges = if (!isActive) activeChanges else emptyList()
}
else {
// skip if we have inclusion from not active change lists
if ((inclusionModel.getInclusion() - activeChanges.toPartialAwareSet()).filterIsInstance<Change>().isNotEmpty()) return
// we have inclusion in active change list and/or unversioned files => include new active changes if any
val newChanges = activeChanges - knownActiveChanges
inclusionModel.addInclusion(newChanges)
// include all active changes if nothing is included
if (inclusionModel.isInclusionEmpty()) inclusionModel.addInclusion(activeChanges)
}
}
private fun setSelection(changeList: LocalChangeList) {
val inclusion = inclusionModel.getInclusion()
val isChangeListFullyIncluded = changeList.changes.run { isNotEmpty() && all { it in inclusion } }
if (isChangeListFullyIncluded) {
ui.select(changeList)
ui.expand(changeList)
}
else {
ui.selectFirst(inclusion)
}
}
val isActive: Boolean get() = ui.isActive
fun activate(): Boolean = fireActivityStateChanged { ui.activate() }
fun deactivate(isRestoreState: Boolean) {
fireActivityStateChanged { ui.deactivate(isRestoreState) }
if (isToggleMode()) {
resetCommitChecksResult()
ui.commitProgressUi.clearCommitCheckFailures()
}
}
fun addActivityListener(listener: ActivityListener) = activityEventDispatcher.addListener(listener)
private fun <T> fireActivityStateChanged(block: () -> T): T {
val oldValue = isActive
return block().also { if (oldValue != isActive) activityEventDispatcher.multicaster.activityStateChanged() }
}
private fun changeListChanged(oldChangeList: LocalChangeList?, newChangeList: LocalChangeList?) {
oldChangeList?.let { commitMessagePolicy.save(it, getCommitMessage(), false) }
val newCommitMessage = getCommitMessageFromPolicy(newChangeList)
setCommitMessage(newCommitMessage)
newChangeList?.let { commitOptions.changeListChanged(it) }
}
private fun getCommitMessageFromPolicy(changeList: LocalChangeList?): String? {
if (changeList == null) return null
return commitMessagePolicy.getCommitMessage(changeList) { getIncludedChanges() }
}
private fun changeListDataChanged() {
ui.commitAuthor = currentChangeList?.author
ui.commitAuthorDate = currentChangeList?.authorDate
}
override fun commitAuthorChanged() {
val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return
if (ui.commitAuthor == changeList.author) return
changeListManager.editChangeListData(changeList.name, ChangeListData.of(ui.commitAuthor, ui.commitAuthorDate))
}
override fun commitAuthorDateChanged() {
val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return
if (ui.commitAuthorDate == changeList.authorDate) return
changeListManager.editChangeListData(changeList.name, ChangeListData.of(ui.commitAuthor, ui.commitAuthorDate))
}
override fun inclusionChanged() {
val inclusion = inclusionModel.getInclusion()
val activeChanges = changeListManager.defaultChangeList.changes
val includedActiveChanges = activeChanges.filter { it in inclusion }
// ensure all included active changes are known => if user explicitly checks and unchecks some change, we know it is unchecked
knownActiveChanges = knownActiveChanges.union(includedActiveChanges)
currentChangeList = workflow.getAffectedChangeList(inclusion.filterIsInstance<Change>())
super.inclusionChanged()
}
override fun beforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) {
super.beforeCommitChecksEnded(sessionInfo, result)
if (result.shouldCommit) {
// commit message could be changed during before-commit checks - ensure updated commit message is used for commit
workflow.commitState = workflow.commitState.copy(getCommitMessage())
if (isToggleMode()) deactivate(true)
}
}
private fun isToggleMode(): Boolean {
val commitMode = CommitModeManager.getInstance(project).getCurrentCommitMode()
return commitMode is CommitMode.NonModalCommitMode && commitMode.isToggleMode
}
override fun updateWorkflow(sessionInfo: CommitSessionInfo): Boolean {
workflow.commitState = getCommitState()
return configureCommitSession(project, sessionInfo,
workflow.commitState.changes,
workflow.commitState.commitMessage)
}
override fun prepareForCommitExecution(sessionInfo: CommitSessionInfo): Boolean {
if (sessionInfo.isVcsCommit) {
val changeList = workflow.getAffectedChangeList(getIncludedChanges())
if (!addUnversionedFiles(project, getIncludedUnversionedFiles(), changeList, inclusionModel)) return false
}
return super.prepareForCommitExecution(sessionInfo)
}
override fun saveCommitMessage(success: Boolean) = commitMessagePolicy.save(currentChangeList, getCommitMessage(), success)
// save state on project close
// using this method ensures change list comment and commit options are updated before project state persisting
override fun projectClosingBeforeSave(project: Project) {
saveStateBeforeDispose()
disposeCommitOptions()
currentChangeList = null
}
// save state on other events - like "settings changed to use commit dialog"
override fun dispose() {
saveStateBeforeDispose()
disposeCommitOptions()
super.dispose()
}
private fun saveStateBeforeDispose() {
commitOptions.saveState()
saveCommitMessage(false)
}
interface ActivityListener : EventListener {
fun activityStateChanged()
}
private inner class GitCommitStateCleaner : CommitStateCleaner() {
override fun onSuccess() {
setCommitMessage(getCommitMessageFromPolicy(currentChangeList))
super.onSuccess()
}
}
}
| apache-2.0 | 14d607641eff3159bb0a33b7a2c34447 | 36.97351 | 140 | 0.760551 | 5.0609 | false | false | false | false |
google/intellij-community | plugins/git4idea/src/git4idea/log/GitBekParentFixer.kt | 1 | 4737 | // 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 git4idea.log
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.intellij.util.EmptyConsumer
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.TimedVcsCommit
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsLogTextFilter
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.util.BekUtil
import git4idea.history.GitLogUtil
import java.util.regex.Pattern
internal class GitBekParentFixer private constructor(private val incorrectCommits: Set<Hash>) {
fun fixCommit(commit: TimedVcsCommit): TimedVcsCommit {
return if (!incorrectCommits.contains(commit.id)) commit
else object : TimedVcsCommit by commit {
override fun getParents(): List<Hash> = ContainerUtil.reverse(commit.parents)
}
}
companion object {
private val LOG = Logger.getInstance(GitBekParentFixer::class.java)
@JvmStatic
fun prepare(project: Project, root: VirtualFile): GitBekParentFixer {
if (isEnabled()) {
try {
return GitBekParentFixer(getIncorrectCommits(project, root))
}
catch (e: VcsException) {
LOG.warn("Could not find incorrect merges ", e)
}
}
return GitBekParentFixer(emptySet())
}
@JvmStatic
fun fixCommits(commits: List<VcsCommitMetadata>): List<VcsCommitMetadata> {
if (!isEnabled()) return commits
return commits.map map@{ commit ->
if (commit.parents.size <= 1) return@map commit
if (!MAGIC_FILTER.matches(commit.fullMessage)) return@map commit
return@map object : VcsCommitMetadata by commit {
override fun getParents(): List<Hash> = ContainerUtil.reverse(commit.parents)
}
}
}
}
}
private fun isEnabled() = BekUtil.isBekEnabled() && Registry.`is`("git.log.fix.merge.commits.parents.order")
private const val MAGIC_REGEX = "^Merge remote(\\-tracking)? branch '.*/(.*)'( into \\2)?$"
private val MAGIC_FILTER = object : VcsLogTextFilter {
val pattern = Pattern.compile(MAGIC_REGEX, Pattern.MULTILINE)
override fun matchesCase(): Boolean {
return false
}
override fun isRegex(): Boolean {
return false
}
override fun getText(): String {
return "Merge remote"
}
override fun matches(message: String): Boolean {
return pattern.matcher(message).find(0)
}
}
@Throws(VcsException::class)
fun getIncorrectCommits(project: Project, root: VirtualFile): Set<Hash> {
val dataManager = VcsProjectLog.getInstance(project).dataManager
val dataGetter = dataManager?.index?.dataGetter
if (dataGetter == null || !dataManager.index.isIndexed(root)) {
return getIncorrectCommitsFromGit(project, root)
}
return getIncorrectCommitsFromIndex(dataManager, dataGetter, root)
}
fun getIncorrectCommitsFromIndex(dataManager: VcsLogData,
dataGetter: IndexDataGetter,
root: VirtualFile): MutableSet<Hash> {
TraceManager.getTracer("vcs").spanBuilder("getting incorrect merges from index").setAttribute("rootName",
root.name).useWithScope {
val commits = dataGetter.filter(listOf(MAGIC_FILTER)).asSequence()
return commits.map { dataManager.storage.getCommitId(it)!! }.filter { it.root == root }.mapTo(mutableSetOf()) { it.hash }
}
}
@Throws(VcsException::class)
fun getIncorrectCommitsFromGit(project: Project, root: VirtualFile): MutableSet<Hash> {
TraceManager.getTracer("vcs").spanBuilder("getting incorrect merges from git").setAttribute("rootName", root.name).useWithScope {
val filterParameters = mutableListOf<String>()
filterParameters.addAll(GitLogUtil.LOG_ALL)
filterParameters.add("--merges")
GitLogProvider.appendTextFilterParameters(MAGIC_REGEX, true, false, filterParameters)
val result = mutableSetOf<Hash>()
GitLogUtil.readTimedCommits(project, root, filterParameters, EmptyConsumer.getInstance(),
EmptyConsumer.getInstance(), Consumer { commit -> result.add(commit.id) })
return result
}
} | apache-2.0 | 0fd6fd34965855edce231669b2495d58 | 37.520325 | 140 | 0.714165 | 4.435393 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/IndexingFlag.kt | 6 | 2128 | // 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.util.indexing
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.openapi.vfs.newvfs.ManagingFS
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
/**
* An object dedicated to manage in memory `isIndexed` file flag.
*/
@ApiStatus.Internal
object IndexingFlag {
private val hashes = StripedIndexingStampLock()
@JvmStatic
val nonExistentHash = StripedIndexingStampLock.NON_EXISTENT_HASH
@JvmStatic
fun cleanupProcessedFlag() = VirtualFileSystemEntry.markAllFilesAsUnindexed()
@JvmStatic
fun cleanProcessedFlagRecursively(file: VirtualFile) {
if (file !is VirtualFileSystemEntry) return
cleanProcessingFlag(file)
if (file.isDirectory()) {
for (child in file.cachedChildren) {
cleanProcessedFlagRecursively(child)
}
}
}
@JvmStatic
fun cleanProcessingFlag(file: VirtualFile) {
if (file is VirtualFileSystemEntry) {
hashes.releaseHash(file.id)
file.isFileIndexed = false
}
}
@JvmStatic
fun setFileIndexed(file: VirtualFile) {
if (file is VirtualFileSystemEntry) {
file.isFileIndexed = true
}
}
@JvmStatic
fun getOrCreateHash(file: VirtualFile): Long {
if (file is VirtualFileSystemEntry) {
return hashes.getHash(file.id)
}
return nonExistentHash
}
@JvmStatic
fun unlockFile(file: VirtualFile) {
if (file is VirtualFileWithId) {
hashes.releaseHash(file.id)
}
}
@JvmStatic
fun setIndexedIfFileWithSameLock(file: VirtualFile, lockObject: Long) {
if (file is VirtualFileSystemEntry) {
val hash = hashes.releaseHash(file.id)
if (!file.isFileIndexed) {
file.isFileIndexed = hash == lockObject
}
}
}
@JvmStatic
fun unlockAllFiles() {
hashes.clear()
}
@JvmStatic
@TestOnly
fun dumpLockedFiles(): IntArray = hashes.dumpIds()
} | apache-2.0 | 15c35ea4218e601fd75db4a4bc5e12ca | 24.650602 | 120 | 0.721805 | 4.084453 | false | false | false | false |
square/okhttp | mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/bridge.kt | 2 | 3066 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.mockwebserver
import java.util.concurrent.TimeUnit.MILLISECONDS
internal fun Dispatcher.wrap(): mockwebserver3.Dispatcher {
if (this is QueueDispatcher) return this.delegate
val delegate = this
return object : mockwebserver3.Dispatcher() {
override fun dispatch(
request: mockwebserver3.RecordedRequest
): mockwebserver3.MockResponse {
return delegate.dispatch(request.unwrap()).wrap()
}
override fun peek(): mockwebserver3.MockResponse {
return delegate.peek().wrap()
}
override fun shutdown() {
delegate.shutdown()
}
}
}
internal fun MockResponse.wrap(): mockwebserver3.MockResponse {
val result = mockwebserver3.MockResponse()
val copyFromWebSocketListener = webSocketListener
if (copyFromWebSocketListener != null) {
result.withWebSocketUpgrade(copyFromWebSocketListener)
}
val body = getBody()
if (body != null) result.setBody(body)
for (pushPromise in pushPromises) {
result.withPush(pushPromise.wrap())
}
result.withSettings(settings)
result.status = status
result.headers = headers
result.trailers = trailers
result.socketPolicy = when (socketPolicy) {
SocketPolicy.EXPECT_CONTINUE, SocketPolicy.CONTINUE_ALWAYS -> {
result.add100Continue()
mockwebserver3.SocketPolicy.KEEP_OPEN
}
SocketPolicy.UPGRADE_TO_SSL_AT_END -> {
result.inTunnel()
mockwebserver3.SocketPolicy.KEEP_OPEN
}
else -> socketPolicy.wrap()
}
result.http2ErrorCode = http2ErrorCode
result.throttleBody(throttleBytesPerPeriod, getThrottlePeriod(MILLISECONDS), MILLISECONDS)
result.setBodyDelay(getBodyDelay(MILLISECONDS), MILLISECONDS)
result.setHeadersDelay(getHeadersDelay(MILLISECONDS), MILLISECONDS)
return result
}
private fun PushPromise.wrap(): mockwebserver3.PushPromise {
return mockwebserver3.PushPromise(
method = method,
path = path,
headers = headers,
response = response.wrap()
)
}
internal fun mockwebserver3.RecordedRequest.unwrap(): RecordedRequest {
return RecordedRequest(
requestLine = requestLine,
headers = headers,
chunkSizes = chunkSizes,
bodySize = bodySize,
body = body,
sequenceNumber = sequenceNumber,
failure = failure,
method = method,
path = path,
handshake = handshake,
requestUrl = requestUrl
)
}
private fun SocketPolicy.wrap(): mockwebserver3.SocketPolicy {
return mockwebserver3.SocketPolicy.valueOf(name)
}
| apache-2.0 | ca72397c4c5aaba957b642b81238500a | 28.480769 | 92 | 0.729941 | 4.469388 | false | false | false | false |
littleGnAl/Accounting | app/src/main/java/com/littlegnal/accounting/db/Accounting.kt | 1 | 1295 | /*
* Copyright (C) 2017 littlegnal
*
* 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.littlegnal.accounting.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Date
/**
* 记帐表
*/
@Entity(tableName = "accounting")
data class Accounting(
@ColumnInfo(name = "amount") var amount: Float,
@ColumnInfo(name = "createTime") var createTime: Date,
@ColumnInfo(name = "tag_name") var tagName: String,
@ColumnInfo(name = "remarks") var remarks: String?
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Int = 0
override fun toString(): String {
return "Accounting(amount=$amount, createTime=$createTime, tagName='$tagName', " +
"remarks=$remarks, id=$id)"
}
}
| apache-2.0 | a0029a5c4756a12cd9de20d39a818c4c | 28.976744 | 86 | 0.715283 | 3.824926 | false | false | false | false |
ursjoss/sipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/paper/slim/JooqPaperSlimBySearchOrderRepoTest.kt | 1 | 21973 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.persistence.paper.slim
import ch.difty.scipamato.common.persistence.JooqSortMapper
import ch.difty.scipamato.core.db.tables.records.PaperRecord
import ch.difty.scipamato.core.entity.Code
import ch.difty.scipamato.core.entity.newsletter.NewsletterTopic
import ch.difty.scipamato.core.entity.projection.PaperSlim
import ch.difty.scipamato.core.entity.search.SearchCondition
import ch.difty.scipamato.core.entity.search.SearchOrder
import ch.difty.scipamato.core.entity.search.SearchTerm
import ch.difty.scipamato.core.entity.search.SearchTermType
import io.mockk.mockk
import org.amshove.kluent.shouldBeEqualTo
import org.jooq.DSLContext
import org.junit.jupiter.api.Test
internal class JooqPaperSlimBySearchOrderRepoTest {
private val dslMock = mockk<DSLContext>()
private val mapperMock = mockk<PaperSlimRecordMapper>()
private val sortMapperMock = mockk<JooqSortMapper<PaperRecord, PaperSlim, ch.difty.scipamato.core.db.tables.Paper>>()
private var finder = JooqPaperSlimBySearchOrderRepo(dslMock, mapperMock, sortMapperMock)
@Test
fun getConditions_withEmptySearchOrder() {
val searchOrder = SearchOrder()
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo "false"
}
@Test
fun getConditions_withEmptySearchOrderWithExclusion_IgnoresTheExclusions() {
val searchOrder = SearchOrder()
searchOrder.addExclusionOfPaperWithId(3)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo "false"
}
@Test
fun getConditions_withSearchOrderWithIntegerSearchTerm() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.addSearchTerm(SearchTerm.newSearchTerm(2L, SearchTermType.INTEGER.id, 1, "publicationYear", ">2014"))
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo "publication_year > 2014"
}
@Test
fun getConditions_withSearchOrderWithAuditSearchTermForCreatedUser() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.addSearchTerm(SearchTerm.newSearchTerm(2L, SearchTermType.AUDIT.id, 1, "paper.created_by", "mkj"))
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
""""public"."paper"."id" in (
| select "public"."paper"."id"
| from "public"."paper"
| join "public"."scipamato_user"
| on paper.created_by = "public"."scipamato_user"."id"
| where lower("public"."scipamato_user"."user_name") like '%mkj%'
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithAuditSearchTermForCreationTimeStamp() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
val st = SearchTerm.newSearchTerm(
2L,
SearchTermType.AUDIT.id,
1,
"paper.created",
""">="2017-02-01 23:55:12""""
)
sc1.addSearchTerm(st)
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo "paper.created >= timestamp '2017-02-01 23:55:12.0'"
}
@Test
fun getConditions_withSearchOrderWithAuditSearchTermForLastModTimeStamp() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
val st = SearchTerm.newSearchTerm(2L, SearchTermType.AUDIT.id, 1, "paper.last_modified", "<2017-02-01 23:55:12")
sc1.addSearchTerm(st)
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo "paper.last_modified < timestamp '2017-02-01 23:55:12.0'"
}
@Test
fun getConditions_withSearchOrderWithConditions() {
val searchOrder = makeSearchOrderWithConditions()
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""(
| (
| publication_year between 2014 and 2015
| and authors ilike ('%' || replace(
| replace(
| replace(
| 'turner',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
| or (
| first_author_overridden = false
| and exists (
| select 1 "one"
| from "public"."paper_code"
| where (
| "public"."paper_code"."paper_id" = "public"."paper"."id"
| and lower("public"."paper_code"."code") = '1f'
| )
| )
| and exists (
| select 1 "one"
| from "public"."paper_code"
| where (
| "public"."paper_code"."paper_id" = "public"."paper"."id"
| and lower("public"."paper_code"."code") = '5s'
| )
| )
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithConditionsAndExclusions_ignoresExclusions() {
val searchOrder = makeSearchOrderWithConditions()
searchOrder.addExclusionOfPaperWithId(3)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""(
| (
| (
| publication_year between 2014 and 2015
| and authors ilike ('%' || replace(
| replace(
| replace(
| 'turner',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
| or (
| first_author_overridden = false
| and exists (
| select 1 "one"
| from "public"."paper_code"
| where (
| "public"."paper_code"."paper_id" = "public"."paper"."id"
| and lower("public"."paper_code"."code") = '1f'
| )
| )
| and exists (
| select 1 "one"
| from "public"."paper_code"
| where (
| "public"."paper_code"."paper_id" = "public"."paper"."id"
| and lower("public"."paper_code"."code") = '5s'
| )
| )
| )
| )
| and "public"."paper"."id" not in (3)
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithConditionsAndInvertedExclusions_onlySelectsTheExclusions() {
val searchOrder = makeSearchOrderWithConditions()
searchOrder.isShowExcluded = true
searchOrder.addExclusionOfPaperWithId(3)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo """"public"."paper"."id" in (3)"""
}
@Test
fun getConditions_withSearchOrderWithConditionsAndExclusions() {
val searchOrder = makeSearchOrderWithConditions()
searchOrder.addExclusionOfPaperWithId(5)
searchOrder.addExclusionOfPaperWithId(17)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""(
| (
| (
| publication_year between 2014 and 2015
| and authors ilike ('%' || replace(
| replace(
| replace(
| 'turner',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
| or (
| first_author_overridden = false
| and exists (
| select 1 "one"
| from "public"."paper_code"
| where (
| "public"."paper_code"."paper_id" = "public"."paper"."id"
| and lower("public"."paper_code"."code") = '1f'
| )
| )
| and exists (
| select 1 "one"
| from "public"."paper_code"
| where (
| "public"."paper_code"."paper_id" = "public"."paper"."id"
| and lower("public"."paper_code"."code") = '5s'
| )
| )
| )
| )
| and "public"."paper"."id" not in (
| 5, 17
| )
|)""".trimMargin()
}
private fun makeSearchOrderWithConditions(): SearchOrder {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.addSearchTerm(SearchTerm.newSearchTerm(1L, SearchTermType.STRING.id, 1, "authors", "turner"))
sc1.addSearchTerm(SearchTerm.newSearchTerm(2L, SearchTermType.INTEGER.id, 1, "publicationYear", "2014-2015"))
searchOrder.add(sc1)
val sc2 = SearchCondition(2L)
sc2.addSearchTerm(SearchTerm.newSearchTerm(3L, SearchTermType.BOOLEAN.id, 2, "firstAuthorOverridden", "false"))
sc2.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
sc2.addCode(Code("5S", "C5S", "", false, 5, "CC5", "", 1))
searchOrder.add(sc2)
return searchOrder
}
@Test
fun getConditions_withSearchOrderWithSingleConditionCoveringNewspaperTopicAndHeadline() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterHeadline = "hl"
sc1.setNewsletterTopic(NewsletterTopic(1, "nt1"))
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and "public"."paper_newsletter"."newsletter_topic_id" = 1
| and "paper_newsletter"."headline" ilike ('%' || replace(
| replace(
| replace(
| 'hl',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithSingleConditionCoveringNewspaperTopic() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.setNewsletterTopic(NewsletterTopic(1, "nt1"))
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and "public"."paper_newsletter"."newsletter_topic_id" = 1
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithSingleConditionCoveringNewspaperHeadline() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterHeadline = "hl"
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and "paper_newsletter"."headline" ilike ('%' || replace(
| replace(
| replace(
| 'hl',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithSingleConditionCoveringNewspaperIssue() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterIssue = "i"
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and "newsletter"."issue" ilike ('%' || replace(
| replace(
| replace(
| 'i',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithCertainStringValues1() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterIssue = ">\"\""
sc1.newsletterHeadline = "=\"\""
sc1.attachmentNameMask = " =\"\""
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""(
| exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and (
| "paper_newsletter"."headline" is null
| or char_length(cast("paper_newsletter"."headline" as varchar)) = 0
| )
| and "newsletter"."issue" is not null
| and char_length(cast("newsletter"."issue" as varchar)) > 0
| )
| )
| and exists (
| select 1 "one"
| from "public"."paper_attachment"
| where (
| "public"."paper_attachment"."paper_id" = "public"."paper"."id"
| and (
| "paper_attachment"."name" is null
| or char_length(cast("paper_attachment"."name" as varchar)) = 0
| )
| )
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithCertainStringValues2() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterIssue = "\"foo\""
sc1.newsletterHeadline = " =\"bar\" "
sc1.attachmentNameMask = "-\"baz\""
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""(
| exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and lower(cast("paper_newsletter"."headline" as varchar)) = lower('bar')
| and lower(cast("newsletter"."issue" as varchar)) = lower('foo')
| )
| )
| and exists (
| select 1 "one"
| from "public"."paper_attachment"
| where (
| "public"."paper_attachment"."paper_id" = "public"."paper"."id"
| and lower(cast("paper_attachment"."name" as varchar)) <> lower('baz')
| )
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithCertainStringValues3() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterIssue = "-foo"
searchOrder.add(sc1)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and not (coalesce(
| "newsletter"."issue",
| ''
| ) ilike ('%' || replace(
| replace(
| replace(
| 'foo',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!')
| )
|)""".trimMargin()
}
@Test
fun getConditions_withSearchOrderWithTwoConditionsCoveringNewspaperTopicAndHeadline() {
val searchOrder = SearchOrder()
val sc1 = SearchCondition(1L)
sc1.newsletterHeadline = "hl"
searchOrder.add(sc1)
val sc2 = SearchCondition(2L)
sc2.setNewsletterTopic(NewsletterTopic(1, "nt1"))
searchOrder.add(sc2)
val cond = finder.getConditionsFrom(searchOrder)
cond.toString() shouldBeEqualTo
"""(
| exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and "paper_newsletter"."headline" ilike ('%' || replace(
| replace(
| replace(
| 'hl',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
| ) || '%') escape '!'
| )
| )
| or exists (
| select 1 "one"
| from "public"."paper_newsletter"
| join "public"."newsletter"
| on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id"
| where (
| "public"."paper_newsletter"."paper_id" = "public"."paper"."id"
| and "public"."paper_newsletter"."newsletter_topic_id" = 1
| )
| )
|)""".trimMargin()
}
}
| gpl-3.0 | d9a74d86a787904bd9f8b5478564326a | 38.028419 | 121 | 0.441041 | 4.810201 | false | false | false | false |
mr-max/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/helpers/Helpers.kt | 1 | 1336 | package de.maxvogler.learningspaces.helpers
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Adapter
import de.maxvogler.learningspaces.models.Weekday
import org.joda.time.LocalDate
import org.joda.time.LocalDateTime
import org.json.simple.JSONArray
import org.json.simple.JSONObject
public fun ViewGroup.fillWithAdapter(adapter: Adapter) {
removeAllViews()
(0..adapter.count - 1).forEach { addView(adapter.getView(it, null, this)) }
}
fun JSONObject.string(key: Any): String? = this[key] as String?
fun JSONObject.int(key: Any): Int? = (this[key] as Long?)?.toInt()
fun JSONObject.obj(key: Any): JSONObject? = this[key] as JSONObject?
fun JSONObject.array(key: Any): JSONArray? = this[key] as JSONArray?
fun <K, V> Map<K, V>.containsKeys(vararg keys: Any): Boolean = keys.all { this.containsKey(it) }
fun Int.toWeekday(): Weekday = Weekday.values()[this - 1]
fun LocalDate.toWeekday(): Weekday = this.dayOfWeek.toWeekday()
fun LocalDateTime.toWeekday(): Weekday = this.dayOfWeek.toWeekday()
fun Drawable.tint(primaryColor: Int) = this.setColorFilter(primaryColor, PorterDuff.Mode.SRC_IN)
val Context.layoutInflater: LayoutInflater
get() = LayoutInflater.from(this)
| gpl-2.0 | 41046810ce466455119c01fd853ca1a8 | 33.25641 | 96 | 0.770958 | 3.67033 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHNewPRDiffVirtualFile.kt | 2 | 1465 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.diff.editor.DiffContentVirtualFile
import com.intellij.ide.actions.SplitAction
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
@Suppress("EqualsOrHashCode")
internal class GHNewPRDiffVirtualFile(fileManagerId: String,
project: Project,
repository: GHRepositoryCoordinates)
: GHRepoVirtualFile(fileManagerId, project, repository), DiffContentVirtualFile {
init {
putUserData(SplitAction.FORBID_TAB_SPLIT, true)
isWritable = false
}
override fun getName() = "newPR.diff"
override fun getPresentableName() = GithubBundle.message("pull.request.new.diff.editor.title")
override fun getPath(): String = (fileSystem as GHPRVirtualFileSystem).getPath(fileManagerId, project, repository, null, true)
override fun getPresentablePath() = "${repository.toUrl()}/pulls/newPR.diff"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GHNewPRDiffVirtualFile) return false
if (!super.equals(other)) return false
return true
}
} | apache-2.0 | cd21da1117e19c661c40715d6d7015ce | 42.117647 | 140 | 0.74471 | 4.563863 | false | false | false | false |
notsyncing/cowherd | cowherd-deploy/src/main/kotlin/io/github/notsyncing/cowherd/deploy/CowherdDeployApp.kt | 1 | 2631 | package io.github.notsyncing.cowherd.deploy
import io.github.notsyncing.cowherd.deploy.commands.ServerCommands
import org.jline.reader.LineReader
import org.jline.reader.LineReaderBuilder
import org.jline.reader.impl.DefaultParser
import org.jline.reader.impl.completer.FileNameCompleter
import org.jline.reader.impl.history.DefaultHistory
import org.jline.terminal.Terminal
import org.jline.terminal.TerminalBuilder
class CowherdDeployApp(val args: Array<String>) {
companion object {
private fun checkForDependencies(): Boolean {
val rsync = ProcessBuilder()
.command("rsync", "--version")
.inheritIO()
.start()
val r = rsync.waitFor()
if (r != 0) {
println("ERROR: rsync not found!")
return false
}
return true
}
@JvmStatic
fun main(args: Array<String>) {
if (!checkForDependencies()) {
System.exit(1)
return
}
val app = CowherdDeployApp(args)
app.run()
}
}
private val commands = listOf(ServerCommands(this))
private val terminal: Terminal
private val reader: LineReader
private var stop = false
init {
terminal = TerminalBuilder.builder()
.build()
reader = LineReaderBuilder.builder()
.terminal(terminal)
.completer(FileNameCompleter())
.history(DefaultHistory())
.parser(DefaultParser())
.build()
}
fun run() {
while (!stop) {
val rawLine = reader.readLine("> ")
val cmdLine = reader.parsedLine ?: continue
dispatchCommand(cmdLine.words())
}
}
private fun dispatchCommand(words: List<String>) {
if (words.isEmpty()) {
return
}
val cmd = words[0]
if (cmd.isNullOrBlank()) {
return
}
val args = mutableListOf<String>()
if (words.size > 1) {
args.addAll(words.subList(1, words.lastIndex + 1))
}
for (c in commands) {
val m = c::class.java.methods.firstOrNull { it.isAnnotationPresent(Command::class.java) && it.name == cmd } ?: continue
try {
m(c, *args.toTypedArray())
} catch (e: Exception) {
e.printStackTrace()
}
return
}
println("Unknown command $cmd")
}
fun stop() {
stop = true
}
} | gpl-3.0 | 2a9ea72459ea52de1a64902b50b3def7 | 24.066667 | 131 | 0.537818 | 4.664894 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/types/classifierIsTypeParameter.kt | 2 | 665 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KTypeParameter
import kotlin.test.*
class A<U> {
fun <T> foo(): T = null!!
fun bar(): Array<U>? = null!!
}
fun box(): String {
val t = A::class.members.single { it.name == "foo" }.returnType
assertFalse(t.isMarkedNullable)
val tc = t.classifier
if (tc !is KTypeParameter) fail(tc.toString())
assertEquals("T", tc.name)
val u = A::class.members.single { it.name == "bar" }.returnType
assertTrue(u.isMarkedNullable)
assertEquals(Array<Any>::class, u.classifier)
return "OK"
}
| apache-2.0 | d53840391c4fff66181d3009e5cd9c3e | 24.576923 | 72 | 0.655639 | 3.463542 | false | false | false | false |
Unic8/retroauth | retroauth/src/main/java/com/andretietz/retroauth/Authenticator.kt | 1 | 3759 | /*
* Copyright (c) 2016 Andre Tietz
*
* 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.andretietz.retroauth
import okhttp3.Request
import okhttp3.Response
import java.net.HttpURLConnection
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* The Authenticator interface is a very specific provider endpoint dependent implementation,
* to authenticate your request and defines when or if to retry.
*/
abstract class Authenticator<out OWNER_TYPE : Any, OWNER : Any, CREDENTIAL_TYPE : Any, CREDENTIAL : Any> {
companion object {
private val executors: ExecutorService by lazy { Executors.newSingleThreadExecutor() }
}
/**
* When there's no current owner set, take the existing ones and let the user choose, which one
* to pick.
*
* @param owners available [OWNER]s on that system. This will never be an empty list.
*
* @return a future that contains an owner to proceed.
*
* @throws AuthenticationCanceledException when the user cancels choosing an owner.
*/
@Throws(AuthenticationCanceledException::class)
open fun chooseOwner(owners: List<OWNER>): Future<OWNER> =
/**
* The default implementation returns the first available owner.
*/
executors.submit(Callable<OWNER> { owners[0] })
/**
* @param annotationCredentialType type of the credential reached in from the [Authenticated.credentialType]
* Annotation of the request.
*
* @return type of the credential
*/
abstract fun getCredentialType(annotationCredentialType: Int = 0): CREDENTIAL_TYPE
/**
* @param annotationOwnerType type of the owner reached in from the [Authenticated.ownerType]
* Annotation of the request.
*/
abstract fun getOwnerType(annotationOwnerType: Int = 0): OWNER_TYPE
/**
* Authenticates a [Request].
*
* @param request request to authenticate
* @param credential Token to authenticate
* @return a modified version of the incoming request, which is authenticated
*/
abstract fun authenticateRequest(request: Request, credential: CREDENTIAL): Request
/**
* Checks if the credential needs to be refreshed or not.
*
* @param count value contains how many times this request has been executed already
* @param response response to check what the result was
* @return {@code true} if a credential refresh is required, {@code false} if not
*/
open fun refreshRequired(count: Int, response: Response): Boolean =
response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && count <= 1
/**
* This method will be called when [isCredentialValid] returned false or [refreshRequired] returned true.
*
* @param credential of the local [CredentialStorage]
*/
@Suppress("UNUSED_PARAMETER")
open fun refreshCredentials(
owner: OWNER,
credentialType: CREDENTIAL_TYPE,
credential: CREDENTIAL
): CREDENTIAL? = credential
/**
* This method is called on each authenticated request, to make sure the current credential is still valid.
*
* @param credential The current credential
*/
@Suppress("UNUSED_PARAMETER")
open fun isCredentialValid(credential: CREDENTIAL): Boolean = true
}
| apache-2.0 | 03f620917dbe9eae6cdd716f34ec8030 | 34.462264 | 110 | 0.731312 | 4.539855 | false | false | false | false |
tsagi/JekyllForAndroid | app/src/main/java/com/jchanghong/data/DatabaseManager.kt | 2 | 28283 | package com.jchanghong.data
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.jchanghong.GlobalApplication
import com.jchanghong.R
import com.jchanghong.data.DatabaseManager.DB_NAME
import com.jchanghong.data.DatabaseManager.DB_VERSION
import com.jchanghong.model.Category
import com.jchanghong.model.CategoryIcon
import com.jchanghong.model.Note
import com.jchanghong.utils.Tools
@SuppressLint("StaticFieldLeak")
object DatabaseManager : SQLiteOpenHelper(GlobalApplication.mcontext, DB_NAME, null, DB_VERSION) {
@SuppressLint("StaticFieldLeak")
private val context: Context = GlobalApplication.mcontext!!
val LOG = DatabaseManager::class.java.name + "jiangchanghong"
val cat_id: IntArray
val cat_name: Array<String>
val cat_color: Array<String>
val cat_icon: Array<String>
val cat_icon_data: Array<String>
val cat_color_data: Array<String>
val defaultCAT: Category
init {
cat_id = context.resources.getIntArray(R.array.category_id)
cat_name = context.resources.getStringArray(R.array.category_name)
cat_color = context.resources.getStringArray(R.array.category_color)
cat_icon = context.resources.getStringArray(R.array.category_icon)
cat_icon_data = context.resources.getStringArray(R.array.category_icon_data)
cat_color_data = context.resources.getStringArray(R.array.category_color_data)
defaultCAT = Category()
}
override fun onCreate(DatabaseManager: SQLiteDatabase) {
createTableCategoryIcon(DatabaseManager)
createTableCategory(DatabaseManager)
createTableNote(DatabaseManager)
}
override fun onUpgrade(DatabaseManager: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion == 1 && newVersion == 2) {
val categories = getAllCategoryVersion3(DatabaseManager)
Log.e("onUpgrade", "MASUK 1 2")
val notes = getAllNotesVersion3(DatabaseManager)
deleteCategoryIconTable(DatabaseManager)
deleteNoteTable(DatabaseManager)
deleteCategoryTable(DatabaseManager)
createTableCategoryIconVersion3(DatabaseManager)
createTableCategoryVersion3(DatabaseManager)
createTableNoteVersion3(DatabaseManager)
defineCategoryIconVersion3(DatabaseManager)
insertCategoryVersion3(DatabaseManager, redefineCategoryVersion3(categories))
insertNoteVerion3(DatabaseManager, notes)
// NoteCache.clear()
// CategoryCache.clear()
}
}
private fun createTableNote(DatabaseManager: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_NOTE (" +
COL_N_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_N_TITLE +
" TEXT, " + COL_N_CONTENT + " TEXT, " + COL_N_FAV + " INTEGER, " +
COL_N_LAST_EDIT + " NUMERIC, " +
COL_N_pPATH+" TEXT, "+
COL_N_CATEGORY +
" INTEGER, " + " FOREIGN KEY(" + COL_N_CATEGORY +
") REFERENCES " + TABLE_CATEGORY + "(" + COL_C_ID + ")" + ")"
try {
DatabaseManager.execSQL(CREATE_TABLE)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
private fun createTableCategory(DatabaseManager: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_CATEGORY (" +
COL_C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_C_NAME + " TEXT, " + COL_C_COLOR +
" TEXT, " + COL_C_ICON + " TEXT " + " )"
try {
DatabaseManager.execSQL(CREATE_TABLE)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
fun log(s: String) {
Log.d(LOG, s)
}
fun defineCategory() {
val DatabaseManager = this.writableDatabase
for (i in cat_id.indices) {
val values = ContentValues()
values.put(COL_C_ID, cat_id[i])
values.put(COL_C_NAME, cat_name[i])
values.put(COL_C_COLOR, cat_color[i])
values.put(COL_C_ICON, cat_icon[i])
DatabaseManager.insert(TABLE_CATEGORY, null, values) // Inserting Row
log("insert cat:${cat_name[i]}")
}
}
private fun createTableCategoryIcon(DatabaseManager: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_CATEGORY_ICON (" +
COL_C_ID + " INTEGER PRIMARY KEY , " +
COL_C_ICON + " TEXT, " +
COL_C_COLOR + " TEXT " + " )"
try {
DatabaseManager.execSQL(CREATE_TABLE)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
fun defineCategoryIcon() {
val DatabaseManager = this.writableDatabase
for (i in cat_icon_data.indices) {
val values = ContentValues()
values.put(COL_C_ICON, cat_icon_data[i])
values.put(COL_C_COLOR, cat_color_data[i])
DatabaseManager.insert(TABLE_CATEGORY_ICON, null, values) // Inserting Row
}
}
/**
* All Note transaction
*/
fun insertNote(note: Note) {
val values = ContentValues()
values.put(COL_N_TITLE, note.tittle)
values.put(COL_N_CONTENT, note.content)
values.put(COL_N_FAV, note.favourite)
values.put(COL_N_LAST_EDIT, note.lastEdit)
values.put(COL_N_pPATH,note.parentPath)
values.put(COL_N_CATEGORY, note.category.id)
val DatabaseManager = this.writableDatabase
try {
note.id = DatabaseManager.insert(TABLE_NOTE, null, values)
log("insertnote ${note.tittle}")
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
} finally {
}
}
// @RequiresApi(Build.VERSION_CODES.N)
fun deleteNote(rowId: Long) {
val DatabaseManager = this.writableDatabase
try {
DatabaseManager.delete(TABLE_NOTE, "$COL_N_ID = $rowId", null)
log("delete note: $rowId")
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
}
}
fun updateNote(note: Note) {
val contentValues = ContentValues()
contentValues.put(COL_N_TITLE, note.tittle)
contentValues.put(COL_N_CONTENT, note.content)
contentValues.put(COL_N_LAST_EDIT, note.lastEdit)
contentValues.put(COL_N_pPATH,note.parentPath)
contentValues.put(COL_N_CATEGORY, note.category.id)
val DatabaseManager = this.writableDatabase
try {
DatabaseManager.update(TABLE_NOTE, contentValues, "$COL_N_ID = ${note.id}", null)
Log.i(LOG, "update note:${note.tittle}")
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
}
}
operator fun get(id: Long): Note? {
val DatabaseManager = this.readableDatabase
val note: Note
val cur: Cursor?
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE WHERE $COL_N_ID = ?", arrayOf(id.toString()))
if (cur?.moveToFirst() == true) {
note = getNoteFromCursor(cur)
} else {
return null
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
return null
} finally {
}
return note
}
val allNotes: List<Note>
get() {
val notes = ArrayList<Note>()
val DatabaseManager = this.readableDatabase
var cur: Cursor? = null
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE ORDER BY $COL_N_ID DESC", null)
if (cur?.moveToFirst() == true) {
if (!cur.isAfterLast) {
do {
notes.add(getNoteFromCursor(cur))
} while (cur.moveToNext())
}
}
return notes
} catch (e: Exception) {
e.printStackTrace()
Log.e("DB ERROR", e.toString())
} finally {
cur?.close()
}
// NoteCache.addAll(notes)
return notes
}
fun getNotesByCategoryId(cat_id: Long): List<Note> {
val notes = ArrayList<Note>()
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE WHERE $COL_N_CATEGORY = ?", arrayOf(cat_id.toString()))
if (cur?.moveToFirst() == true) {
if (!cur.isAfterLast) {
do {
notes.add(getNoteFromCursor(cur))
} while (cur.moveToNext())
}
} else {
return notes
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("DB ERROR", e.toString())
return notes
} finally {
cur!!.close()
}
return notes
}
fun getNotesCountByCategoryId(cat_id: Long): Int {
var returnValue = 0
var cursor: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cursor = DatabaseManager.rawQuery("SELECT COUNT($COL_N_ID) FROM $TABLE_NOTE WHERE $COL_N_CATEGORY = ?", arrayOf(cat_id.toString()))
if (cursor?.moveToFirst() == true) {
returnValue = cursor.getInt(0)
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("DB ERROR", e.toString())
return returnValue
} finally {
cursor?.close()
}
return returnValue
}
private fun getNoteFromCursor(cur: Cursor): Note {
val n = Note()
n.id = (cur.getLong(0))
n.tittle = (cur.getString(1))
n.content = (cur.getString(2))
n.favourite = (cur.getInt(3))
n.lastEdit = (cur.getLong(4))
n.parentPath=cur.getString(5)
n.category = getCategoryById(cur.getLong(6)) ?: defaultCAT
return n
}
/**
* All Category transaction
*/
fun getCategoryById(id: Long): Category? {
val category: Category?
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_CATEGORY WHERE $COL_C_ID = ?", arrayOf(id.toString()))
if (cur?.moveToFirst() == true) {
category = getCategoryByCursor(cur)
return category
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cur?.close()
}
return null
}
fun getCategoryByName(name: String): Category? {
val category: Category?
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_CATEGORY WHERE $COL_C_NAME = ?", arrayOf(name))
if (cur?.moveToFirst() == true) {
category = getCategoryByCursor(cur)
return category
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cur?.close()
}
return null
}
val allCategory: List<Category>
get() {
val categories = ArrayList<Category>()
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM " + TABLE_CATEGORY, null)
if (cur?.moveToFirst() == true) {
if (!cur.isAfterLast) {
do {
categories.add(getCategoryByCursor(cur))
} while (cur.moveToNext())
}
}
return categories
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cur?.close()
}
return categories
}
private fun getCategoryByCursor(cur: Cursor): Category {
val c = Category()
c.id = (cur.getLong(0))
c.name = (cur.getString(1))
c.color = (cur.getString(2))
c.icon = (cur.getString(3))
c.note_count = (getNotesCountByCategoryId(c.id))
return c
}
val categoryIcon: List<CategoryIcon>
get() {
val categoryIcons = ArrayList<CategoryIcon>()
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM " + TABLE_CATEGORY_ICON, null)
if (cur?.moveToFirst() == true) {
if (!cur.isAfterLast) {
do {
categoryIcons.add(getCategoryIconByCursor(cur))
} while (cur.moveToNext())
}
}
return categoryIcons
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cur!!.close()
}
return categoryIcons
}
private fun getCategoryIconByCursor(cur: Cursor): CategoryIcon {
val ci = CategoryIcon()
ci.icon = cur.getString(1)
ci.color = cur.getString(2)
return ci
}
fun insertCategory(category: Category) {
val values = ContentValues()
values.put(COL_C_NAME, category.name)
values.put(COL_C_COLOR, category.color)
values.put(COL_C_ICON, category.icon)
val DatabaseManager = this.writableDatabase
try {
category.id = DatabaseManager.insert(TABLE_CATEGORY, null, values) // Inserting Row
Log.i(LOG, "insert cate ${category.name}")
// CategoryCache.add(category)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
} finally {
}
}
fun updateCategory(category: Category) {
val contentValues = ContentValues()
contentValues.put(COL_C_ICON, category.icon)
contentValues.put(COL_C_COLOR, category.color)
contentValues.put(COL_C_NAME, category.name)
val DatabaseManager = this.writableDatabase
try {
DatabaseManager.update(TABLE_CATEGORY, contentValues, "$COL_C_ID =${category.id}", null)
Log.i(LOG, "update ca:$category")
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
}
}
fun deleteCategory(rowId: Long) {
val DatabaseManager = this.writableDatabase
try {
DatabaseManager.delete(TABLE_CATEGORY, "$COL_C_ID=$rowId", null)
Log.i(LOG, "delete ca $rowId")
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
}
}
val firstCategory: Category
get() {
var category:Category
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_CATEGORY ORDER BY ROWID ASC LIMIT 1 ", null)
if (cur?.moveToFirst() == true) {
category = getCategoryByCursor(cur)
return category
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cur?.close()
}
return defaultCAT
}
/**
* All Favorites Note transaction
*/
val allFavNote: List<Note>
get() {
val notes = ArrayList<Note>()
var cur: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE WHERE $COL_N_FAV = ? ORDER BY $COL_N_LAST_EDIT DESC", arrayOf("1"))
if (cur?.moveToFirst() == true) {
if (!cur.isAfterLast) {
do {
notes.add(getNoteFromCursor(cur))
} while (cur.moveToNext())
}
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("DB ERROR", e.toString())
} finally {
cur?.close()
}
return notes
}
fun setFav(id: Long) {
val contentValues = ContentValues()
contentValues.put(COL_N_FAV, 1)
val DatabaseManager = this.writableDatabase
try {
DatabaseManager.update(TABLE_NOTE, contentValues, "$COL_N_ID = $id", null)
log("set fav for: $id")
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
}
}
fun removeFav(id: Long) {
if (isFavoriteExist(id)) {
val contentValues = ContentValues()
contentValues.put(COL_N_FAV, 0)
val DatabaseManager = this.writableDatabase
try {
DatabaseManager.update(TABLE_NOTE, contentValues, COL_N_ID + "=" + id, null)
log("remove fav for id:$id")
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
}
}
}
/**
* Support method
*/
private fun isFavoriteExist(id: Long): Boolean {
var cursor: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cursor = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE WHERE $COL_N_ID = ?", arrayOf(id.toString()))
if (cursor?.moveToFirst() == true) {
return true
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cursor?.close()
}
return false
}
/**
* This is only for update 3.0
*/
fun getAllCategoryVersion3(DatabaseManager: SQLiteDatabase): List<Category> {
val categories = ArrayList<Category>()
var cur: Cursor? = null
try {
cur = DatabaseManager.rawQuery("SELECT * FROM " + TABLE_CATEGORY, null)
cur!!.moveToFirst()
if (!cur.isAfterLast) {
do {
categories.add(getCategoryByCursorVersion3(DatabaseManager, cur))
} while (cur.moveToNext())
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cur!!.close()
}
return categories
}
private fun getCategoryByCursorVersion3(DatabaseManager: SQLiteDatabase, cur: Cursor): Category {
val c = Category()
c.id = (cur.getLong(0))
c.name = (cur.getString(1))
c.color = (cur.getString(2))
c.icon = (cur.getString(3))
c.note_count = (getNotesCountByCategoryIdVersion3(DatabaseManager, c.id))
return c
}
fun getNotesCountByCategoryIdVersion3(DatabaseManager: SQLiteDatabase, cat_id: Long?): Int {
var returnValue = 0
var cursor: Cursor? = null
try {
cursor = DatabaseManager.rawQuery("SELECT COUNT($COL_N_ID) FROM $TABLE_NOTE WHERE $COL_N_CATEGORY = ?", arrayOf(cat_id!!.toString() + ""))
cursor!!.moveToFirst()
returnValue = cursor.getInt(0)
} catch (e: Exception) {
e.printStackTrace()
Log.e("DB ERROR", e.toString())
} finally {
cursor!!.close()
}
return returnValue
}
fun getAllNotesVersion3(DatabaseManager: SQLiteDatabase): List<Note> {
val notes = ArrayList<Note>()
var cur: Cursor? = null
try {
cur = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE ORDER BY $COL_N_ID DESC", null)
cur!!.moveToFirst()
if (!cur.isAfterLast) {
do {
notes.add(getNoteFromCursorVersion3(DatabaseManager, cur))
} while (cur.moveToNext())
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("DB ERROR", e.toString())
} finally {
cur!!.close()
}
return notes
}
private fun getNoteFromCursorVersion3(DatabaseManager: SQLiteDatabase, cur: Cursor): Note {
val n = Note()
n.id = (cur.getLong(0))
n.tittle = (cur.getString(1))
n.content = (cur.getString(2))
n.favourite = (cur.getInt(3))
n.lastEdit = (cur.getLong(4))
n.category = (Category(cur.getLong(5), "", "", ""))
return n
}
private fun deleteNoteTable(DatabaseManager: SQLiteDatabase) {
DatabaseManager.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTE)
}
private fun deleteCategoryTable(DatabaseManager: SQLiteDatabase) {
DatabaseManager.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORY)
}
private fun deleteCategoryIconTable(DatabaseManager: SQLiteDatabase) {
DatabaseManager.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORY_ICON)
}
private fun redefineCategoryVersion3(categories: List<Category>): List<Category> {
//this method is for check is the icon available or not,if not the icon will be replaced with default icon
var defaultIcon = cat_icon_data[0]
var ic = ""
for (category in categories) {
for (i in cat_icon_data.indices) {
ic = Tools.StringToResId(cat_icon_data[i], context).toString()
if (ic == category.icon) {
defaultIcon = cat_icon_data[i]
break
}
}
category.icon = (defaultIcon)
}
return categories
}
fun insertCategoryVersion3(DatabaseManager: SQLiteDatabase, categories: List<Category>) {
var values: ContentValues
try {
for ((id, name, color, icon) in categories) {
values = ContentValues()
values.put(COL_C_ID, id)
values.put(COL_C_NAME, name)
values.put(COL_C_COLOR, color)
values.put(COL_C_ICON, icon)
DatabaseManager.insert(TABLE_CATEGORY, null, values) // Inserting Row
}
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
fun insertNoteVerion3(DatabaseManager: SQLiteDatabase, notes: List<Note>) {
var values: ContentValues? = null
try {
for ((id, tittle, content, lastEdit, favourite,path, category) in notes) {
values = ContentValues()
values.put(COL_N_ID, id)
values.put(COL_N_TITLE, tittle)
values.put(COL_N_CONTENT, content)
values.put(COL_N_FAV, favourite)
values.put(COL_N_LAST_EDIT, lastEdit)
values.put(COL_N_pPATH,path )
values.put(COL_N_CATEGORY, category.id)
DatabaseManager.insert(TABLE_NOTE, null, values)
}
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
private fun createTableCategoryIconVersion3(DatabaseManager: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_CATEGORY_ICON (" +
COL_C_ID + " INTEGER PRIMARY KEY , " +
COL_C_ICON + " TEXT, " + COL_C_COLOR + " TEXT " + " )"
try {
DatabaseManager.execSQL(CREATE_TABLE)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
private fun createTableCategoryVersion3(DatabaseManager: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_CATEGORY (" +
COL_C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_C_NAME + " TEXT, " + COL_C_COLOR + " TEXT, " + COL_C_ICON + " TEXT " + " )"
try {
DatabaseManager.execSQL(CREATE_TABLE)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
private fun createTableNoteVersion3(DatabaseManager: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_NOTE (" +
COL_N_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_N_TITLE + " TEXT, " + COL_N_CONTENT + " TEXT, " + COL_N_FAV + " INTEGER, " + COL_N_LAST_EDIT + " NUMERIC, " + COL_N_CATEGORY + " INTEGER, " + " FOREIGN KEY(" + COL_N_CATEGORY + ") REFERENCES " + TABLE_NOTE + "(" + COL_C_ID + ")" + ")"
try {
DatabaseManager.execSQL(CREATE_TABLE)
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
fun defineCategoryIconVersion3(DatabaseManager: SQLiteDatabase) {
try {
for (i in cat_icon_data.indices) {
val values = ContentValues()
values.put(COL_C_ICON, cat_icon_data[i])
values.put(COL_C_COLOR, cat_color_data[i])
Log.e("ICON DATA: ", i.toString() + " | " + cat_icon_data[i])
DatabaseManager.insert(TABLE_CATEGORY_ICON, null, values) // Inserting Row
}
} catch (e: Exception) {
Log.e("DB ERROR", e.toString())
e.printStackTrace()
}
}
const internal val DB_NAME = "noolis.DatabaseManager"
const internal val TABLE_NOTE = "note"
const internal val TABLE_CATEGORY = "category"
const internal val TABLE_CATEGORY_ICON = "category_icon"
const internal val COL_N_ID = "n_id"
const internal val COL_N_TITLE = "n_title"
const internal val COL_N_CONTENT = "n_content"
const internal val COL_N_FAV = "n_favourite"
const internal val COL_N_LAST_EDIT = "n_last_edit"
const internal val COL_N_pPATH = "n_server_path"
const internal val COL_N_CATEGORY = "n_category"
const internal val COL_C_ID = "c_id"
const internal val COL_C_NAME = "c_name"
const internal val COL_C_COLOR = "c_color"
const internal val COL_C_ICON = "c_icon"
const internal val DB_VERSION = 1
fun isnoteexits(note: Note,title: String, parent: String): Boolean {
var cursor: Cursor? = null
val DatabaseManager = this.readableDatabase
try {
cursor = DatabaseManager.rawQuery("SELECT * FROM $TABLE_NOTE WHERE $COL_N_TITLE = ? AND $COL_N_pPATH = ?", arrayOf(title, parent))
if (cursor?.moveToFirst() == true) {
note.id= getNoteFromCursor(cursor).id
log("$title exits!")
return true
}
} catch (e: Exception) {
e.printStackTrace()
Log.e("Db Error", e.toString())
} finally {
cursor?.close()
}
log("$title not exits!")
return false
}
fun insertNoteorupdate(note: Note) {
if (isnoteexits(note,note.tittle, note.parentPath )) {
updateNote(note)
} else {
insertNote(note)
}
}
}
| gpl-2.0 | c80f1cf3eb0e1f979c2351f178286e73 | 33.703067 | 306 | 0.542835 | 4.409573 | false | false | false | false |
leafclick/intellij-community | uast/uast-common/src/com/intellij/patterns/uast/UastPatterns.kt | 1 | 10474 | /*
* Copyright 2000-2017 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("UastPatterns")
package com.intellij.patterns.uast
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.RecursionManager
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.ObjectPattern
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PsiJavaPatterns
import com.intellij.patterns.StandardPatterns.string
import com.intellij.psi.*
import com.intellij.util.ProcessingContext
import org.jetbrains.annotations.NonNls
import org.jetbrains.uast.*
fun literalExpression(): ULiteralExpressionPattern = ULiteralExpressionPattern()
@JvmOverloads
fun injectionHostUExpression(strict: Boolean = true): UExpressionPattern<UExpression, *> =
uExpression().filterWithContext { _, processingContext ->
val requestedPsi = processingContext.get(REQUESTED_PSI_ELEMENT)
if (requestedPsi == null) {
if (strict && ApplicationManager.getApplication().isUnitTestMode) {
throw AssertionError("no ProcessingContext with `REQUESTED_PSI_ELEMENT` passed for `injectionHostUExpression`," +
" please consider creating one using `UastPatterns.withRequestedPsi`, providing a source psi for which " +
" this pattern was originally created, or make this `injectionHostUExpression` non-strict.")
}
else return@filterWithContext !strict
}
return@filterWithContext requestedPsi is PsiLanguageInjectionHost
}
fun injectionHostOrReferenceExpression(): UExpressionPattern.Capture<UExpression> =
uExpression().filter { it is UReferenceExpression || it.isInjectionHost() }
fun callExpression(): UCallExpressionPattern = UCallExpressionPattern()
fun uExpression(): UExpressionPattern.Capture<UExpression> = expressionCapture(UExpression::class.java)
fun <T : UElement> capture(clazz: Class<T>): UElementPattern.Capture<T> = UElementPattern.Capture(clazz)
fun <T : UExpression> expressionCapture(clazz: Class<T>): UExpressionPattern.Capture<T> = UExpressionPattern.Capture(clazz)
fun ProcessingContext.withRequestedPsi(psiElement: PsiElement) = this.apply { put(REQUESTED_PSI_ELEMENT, psiElement) }
fun withRequestedPsi(psiElement: PsiElement) = ProcessingContext().withRequestedPsi(psiElement)
open class UElementPattern<T : UElement, Self : UElementPattern<T, Self>>(clazz: Class<T>) : ObjectPattern<T, Self>(clazz) {
fun withSourcePsiCondition(pattern: PatternCondition<PsiElement>): Self =
this.with(object : PatternCondition<T>("withSourcePsiPattern") {
override fun accepts(t: T, context: ProcessingContext?): Boolean {
val sourcePsiElement = t.sourcePsiElement ?: return false
return pattern.accepts(sourcePsiElement, context)
}
})
fun sourcePsiFilter(filter: (PsiElement) -> Boolean): Self =
withSourcePsiCondition(object : PatternCondition<PsiElement>("sourcePsiFilter") {
override fun accepts(t: PsiElement, context: ProcessingContext?): Boolean = filter(t)
})
fun filterWithContext(filter: (T, ProcessingContext) -> Boolean): Self =
with(object : PatternCondition<T>(null) {
override fun accepts(t: T, context: ProcessingContext?): Boolean = filter.invoke(t, context ?: ProcessingContext())
})
fun filter(filter: (T) -> Boolean): Self = filterWithContext { t, _ -> filter(t) }
fun withUastParent(parentPattern: ElementPattern<out UElement>): Self = filterWithContext { it, context ->
it.uastParent?.let { parentPattern.accepts(it, context) } ?: false
}
fun withUastParentOrSelf(parentPattern: ElementPattern<out UElement>): Self = filterWithContext { it, context ->
parentPattern.accepts(it, context) || it.uastParent?.let { parentPattern.accepts(it, context) } ?: false
}
class Capture<T : UElement>(clazz: Class<T>) : UElementPattern<T, Capture<T>>(clazz)
}
private val constructorOrMethodCall = setOf(UastCallKind.CONSTRUCTOR_CALL, UastCallKind.METHOD_CALL)
private fun isCallExpressionParameter(argumentExpression: UExpression,
parameterIndex: Int,
callPattern: ElementPattern<UCallExpression>, context: ProcessingContext): Boolean {
val call = argumentExpression.uastParent.getUCallExpression(searchLimit = 2) ?: return false
if (call.kind !in constructorOrMethodCall) return false
return callPattern.accepts(call, context)
&& call.getArgumentForParameter(parameterIndex)?.let(::wrapULiteral) == wrapULiteral(argumentExpression)
}
private fun isPropertyAssignCall(argument: UElement, methodPattern: ElementPattern<out PsiMethod>, context: ProcessingContext): Boolean {
val uBinaryExpression = (argument.uastParent as? UBinaryExpression) ?: return false
if (uBinaryExpression.operator != UastBinaryOperator.ASSIGN) return false
val uastReference = when (val leftOperand = uBinaryExpression.leftOperand) {
is UQualifiedReferenceExpression -> leftOperand.selector
is UReferenceExpression -> leftOperand
else -> return false
}
val references = RecursionManager.doPreventingRecursion(argument, false) {
uastReference.sourcePsi?.references // via `sourcePsi` because of KT-27385
} ?: return false
return references.any { methodPattern.accepts(it.resolve(), context) }
}
class UCallExpressionPattern : UElementPattern<UCallExpression, UCallExpressionPattern>(UCallExpression::class.java) {
fun withReceiver(classPattern: ElementPattern<PsiClass>): UCallExpressionPattern =
filterWithContext { it, context -> (it.receiverType as? PsiClassType)?.resolve()?.let { classPattern.accepts(it, context) } ?: false }
fun withMethodName(methodName : String): UCallExpressionPattern = withMethodName(string().equalTo(methodName))
fun withAnyResolvedMethod(method: ElementPattern<out PsiMethod>): UCallExpressionPattern = withResolvedMethod(method, true)
fun withResolvedMethod(method: ElementPattern<out PsiMethod>,
multiResolve: Boolean): UCallExpressionPattern = filterWithContext { uCallExpression, context ->
if (multiResolve && uCallExpression is UMultiResolvable)
uCallExpression.multiResolve().any { method.accepts(it.element, context) }
else
uCallExpression.resolve().let { method.accepts(it, context) }
}
fun withMethodName(namePattern: ElementPattern<String>): UCallExpressionPattern = filterWithContext { it, context ->
it.methodName?.let {
namePattern.accepts(it, context)
} ?: false
}
fun constructor(classPattern: ElementPattern<PsiClass>): UCallExpressionPattern = filterWithContext { it, context ->
val psiMethod = it.resolve() ?: return@filterWithContext false
psiMethod.isConstructor && classPattern.accepts(psiMethod.containingClass, context)
}
fun constructor(className: String): UCallExpressionPattern = constructor(PsiJavaPatterns.psiClass().withQualifiedName(className))
}
open class UExpressionPattern<T : UExpression, Self : UExpressionPattern<T, Self>>(clazz: Class<T>) : UElementPattern<T, Self>(clazz) {
fun annotationParam(@NonNls parameterName: String, annotationPattern: ElementPattern<UAnnotation>): Self =
annotationParams(annotationPattern, string().equalTo(parameterName))
fun annotationParams(annotationPattern: ElementPattern<UAnnotation>, parameterNames: ElementPattern<String>): Self =
this.with(object : PatternCondition<T>("annotationParam") {
override fun accepts(uElement: T, context: ProcessingContext?): Boolean {
val (annotation, paramName) = getContainingUAnnotationEntry(uElement) ?: return false
return parameterNames.accepts(paramName ?: "value", context) && annotationPattern.accepts(annotation, context)
}
})
fun annotationParam(annotationQualifiedName: ElementPattern<String>, @NonNls parameterName: String): Self =
annotationParam(parameterName, qualifiedNamePattern(annotationQualifiedName))
private fun qualifiedNamePattern(annotationQualifiedName: ElementPattern<String>): UElementPattern<UAnnotation, *> =
capture(UAnnotation::class.java).filterWithContext { it, context ->
it.qualifiedName?.let {
annotationQualifiedName.accepts(it, context)
} ?: false
}
fun annotationParam(@NonNls annotationQualifiedName: String, @NonNls parameterName: String): Self =
annotationParam(string().equalTo(annotationQualifiedName), parameterName)
fun annotationParams(@NonNls annotationQualifiedName: String, @NonNls parameterNames: ElementPattern<String>): Self =
annotationParams(qualifiedNamePattern(string().equalTo(annotationQualifiedName)), parameterNames)
fun inCall(callPattern: ElementPattern<UCallExpression>): Self =
filterWithContext { it, context -> it.getUCallExpression()?.let { callPattern.accepts(it, context) } ?: false }
fun callParameter(parameterIndex: Int, callPattern: ElementPattern<UCallExpression>): Self =
filterWithContext { t, processingContext -> isCallExpressionParameter(t, parameterIndex, callPattern, processingContext) }
fun constructorParameter(parameterIndex: Int, classFQN: String): Self =
callParameter(parameterIndex, callExpression().constructor(classFQN))
fun setterParameter(methodPattern: ElementPattern<out PsiMethod>): Self = filterWithContext { it, context ->
isPropertyAssignCall(it, methodPattern, context) ||
isCallExpressionParameter(it, 0, callExpression().withAnyResolvedMethod(methodPattern), context)
}
@JvmOverloads
fun methodCallParameter(parameterIndex: Int, methodPattern: ElementPattern<out PsiMethod>, multiResolve: Boolean = true): Self =
callParameter(parameterIndex, callExpression().withResolvedMethod(methodPattern, multiResolve))
fun arrayAccessParameterOf(receiverClassPattern: ElementPattern<PsiClass>): Self = filterWithContext { self, context ->
val aae: UArrayAccessExpression = self.uastParent as? UArrayAccessExpression ?: return@filterWithContext false
val receiverClass = (aae.receiver.getExpressionType() as? PsiClassType)?.resolve() ?: return@filterWithContext false
receiverClassPattern.accepts(receiverClass, context)
}
open class Capture<T : UExpression>(clazz: Class<T>) : UExpressionPattern<T, Capture<T>>(clazz)
}
class ULiteralExpressionPattern : UExpressionPattern<ULiteralExpression, ULiteralExpressionPattern>(ULiteralExpression::class.java) | apache-2.0 | a1d8891f7780b393aea7e96f7304d6b7 | 51.638191 | 140 | 0.763319 | 4.956933 | false | false | false | false |
idea4bsd/idea4bsd | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/javaView/GroovyLightInnerClassFinder.kt | 6 | 1863 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.impl.javaView
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.impl.light.LightElement
import com.intellij.psi.search.GlobalSearchScope
class GroovyLightInnerClassFinder(project: Project) : GroovyClassFinder(project) {
override fun findClasses(qualifiedName: String, scope: GlobalSearchScope): Array<out PsiClass> {
val containingClassFqn = StringUtil.getPackageName(qualifiedName)
val innerClassName = StringUtil.getShortName(qualifiedName)
return super.findClasses(containingClassFqn, scope).mapNotNull { findInnerLightClass(it, innerClassName) }.toTypedArray()
}
override fun findClass(qualifiedName: String, scope: GlobalSearchScope): PsiClass? {
val containingClassFqn = StringUtil.getPackageName(qualifiedName)
val containingClass = super.findClass(containingClassFqn, scope) ?: return null
val innerClassName = StringUtil.getShortName(qualifiedName)
return findInnerLightClass(containingClass, innerClassName)
}
fun findInnerLightClass(clazz: PsiClass, name: String): PsiClass? {
return clazz.findInnerClassByName(name, false) as? LightElement as?PsiClass
}
} | apache-2.0 | 62b4762385dff0111630c935f7ffad7d | 43.380952 | 125 | 0.785829 | 4.467626 | false | false | false | false |
ReplayMod/ReplayMod | src/main/kotlin/com/replaymod/core/gui/utils/events.kt | 1 | 2556 | package com.replaymod.core.gui.utils
import gg.essential.elementa.UIComponent
import gg.essential.elementa.effects.Effect
import gg.essential.elementa.events.UIClickEvent
import gg.essential.elementa.utils.ObservableClearEvent
import gg.essential.elementa.utils.ObservableRemoveEvent
import java.util.Observer
fun <T : UIComponent> T.onAnimationFrame(block: T.() -> Unit) = apply {
enableEffect(object : Effect() {
override fun animationFrame() = block()
})
}
fun <T : UIComponent> T.onLeftClick(clickCount: Int? = null, handler: T.(event: UIClickEvent) -> Unit) = apply {
onMouseClick { if (it.mouseButton == 0 && (clickCount == null || it.clickCount == clickCount)) handler(it) }
}
fun <T : UIComponent> T.onRightClick(clickCount: Int? = null, handler: T.(event: UIClickEvent) -> Unit) = apply {
onMouseClick { if (it.mouseButton == 1 && (clickCount == null || it.clickCount == clickCount)) handler(it) }
}
fun <T : UIComponent> T.onMiddleClick(clickCount: Int? = null, handler: T.(event: UIClickEvent) -> Unit) = apply {
onMouseClick { if (it.mouseButton == 2 && (clickCount == null || it.clickCount == clickCount)) handler(it) }
}
private fun <T : UIComponent> T.onMouse(mouseButton: Int, handler: T.(mouseX: Float, mouseY: Float) -> Unit) = apply {
var dragging = false
onMouseClick {
if (it.mouseButton == mouseButton) {
dragging = true
handler(it.absoluteX, it.absoluteY)
}
}
onMouseDrag { mouseX, mouseY, _ -> if (dragging) handler(getLeft() + mouseX, getTop() + mouseY) }
onMouseRelease { dragging = false }
}
fun <T : UIComponent> T.onLeftMouse(handler: T.(mouseX: Float, mouseY: Float) -> Unit) = onMouse(0, handler)
fun <T : UIComponent> T.onRightMouse(handler: T.(mouseX: Float, mouseY: Float) -> Unit) = onMouse(1, handler)
fun <T : UIComponent> T.onMiddleMouse(handler: T.(mouseX: Float, mouseY: Float) -> Unit) = onMouse(2, handler)
// Elementa has no unmount event, so instead we listen for changes to the children list of all our parents.
fun UIComponent.onRemoved(listener: () -> Unit): () -> Unit {
if (parent == this) {
return {}
}
val parentUnregister = parent.onRemoved(listener)
val observer = Observer { _, event ->
if (event is ObservableClearEvent<*> || event is ObservableRemoveEvent<*> && event.element.value == this) {
listener()
}
}
parent.children.addObserver(observer)
return {
parent.children.deleteObserver(observer)
parentUnregister()
}
}
| gpl-3.0 | a0f847d7563889c83e54e604e78e186f | 40.901639 | 118 | 0.670188 | 3.792285 | false | false | false | false |
JetBrains/xodus | utils/src/main/kotlin/jetbrains/exodus/system/OperatingSystem.kt | 1 | 1940 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 jetbrains.exodus.system
import com.sun.management.OperatingSystemMXBean
import jetbrains.exodus.core.execution.SharedTimer
import java.lang.management.ManagementFactory
object OperatingSystem {
private val osBean: OperatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean
private var cachedFreePhysicalMemorySize = Long.MIN_VALUE
private var cachedSystemCpuLoad = Double.MIN_VALUE
private val periodicInvalidate by lazy {
SharedTimer.registerNonExpirablePeriodicTask {
cachedFreePhysicalMemorySize = Long.MIN_VALUE
cachedSystemCpuLoad = Double.MIN_VALUE
}
}
@JvmStatic
fun getFreePhysicalMemorySize(): Long {
cachedFreePhysicalMemorySize.let { memSize ->
return if (memSize < 0L) {
periodicInvalidate
osBean.freePhysicalMemorySize.also { cachedFreePhysicalMemorySize = it }
} else {
memSize
}
}
}
@JvmStatic
fun getSystemCpuLoad(): Double {
cachedSystemCpuLoad.let { cpuLoad ->
return if (cpuLoad < 0) {
periodicInvalidate
osBean.systemCpuLoad.also { cachedSystemCpuLoad = it }
} else {
cpuLoad
}
}
}
} | apache-2.0 | 4f18abc4ce16ef99eeb1f82ab6eca234 | 33.052632 | 117 | 0.673711 | 4.85 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt | 1 | 41382 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.lang.Language
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.*
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.uast.*
import org.jetbrains.uast.analysis.UastAnalysisPlugin
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.kotlin.KotlinConverter.convertDeclaration
import org.jetbrains.uast.kotlin.KotlinConverter.convertDeclarationOrElement
import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.declarations.KotlinUMethod
import org.jetbrains.uast.kotlin.declarations.KotlinUMethodWithFakeLightDelegate
import org.jetbrains.uast.kotlin.expressions.*
import org.jetbrains.uast.kotlin.psi.*
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.ClassSetsWrapper
interface KotlinUastResolveProviderService {
fun getBindingContext(element: KtElement): BindingContext
fun getTypeMapper(element: KtElement): KotlinTypeMapper?
fun getLanguageVersionSettings(element: KtElement): LanguageVersionSettings
fun isJvmElement(psiElement: PsiElement): Boolean
fun getReferenceVariants(ktElement: KtElement, nameHint: String): Sequence<DeclarationDescriptor>
}
var PsiElement.destructuringDeclarationInitializer: Boolean? by UserDataProperty(Key.create("kotlin.uast.destructuringDeclarationInitializer"))
class KotlinUastLanguagePlugin : UastLanguagePlugin {
override val priority = 10
override val language: Language
get() = KotlinLanguage.INSTANCE
override fun isFileSupported(fileName: String): Boolean {
return fileName.endsWith(".kt", false) || fileName.endsWith(".kts", false)
}
private val PsiElement.isJvmElement: Boolean
get() {
val resolveProvider: KotlinUastResolveProviderService = project.getService(KotlinUastResolveProviderService::class.java)!!
return resolveProvider.isJvmElement(this)
}
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? {
val requiredTypes = elementTypes(requiredType)
return if (!canConvert(element, requiredTypes) || !element.isJvmElement) null
else convertDeclarationOrElement(element, parent, requiredTypes)
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? {
val requiredTypes = elementTypes(requiredType)
return when {
!canConvert(element, requiredTypes) || !element.isJvmElement -> null
element is PsiFile || element is KtLightClassForFacade -> convertDeclaration(element, null, requiredTypes)
else -> convertDeclarationOrElement(element, null, requiredTypes)
}
}
override fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): UastLanguagePlugin.ResolvedMethod? {
if (element !is KtCallExpression) return null
val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.name.asString() != methodName) return null
val parent = element.parent
val parentUElement = convertElementWithParent(parent, null) ?: return null
val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall)
val method = uExpression.resolve() ?: return null
if (method.name != methodName) return null
return UastLanguagePlugin.ResolvedMethod(uExpression, method)
}
override fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): UastLanguagePlugin.ResolvedConstructor? {
if (element !is KtCallExpression) return null
val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor !is ConstructorDescriptor
|| resultingDescriptor.returnType.constructor.declarationDescriptor?.name?.asString() != fqName) {
return null
}
val parent = KotlinConverter.unwrapElements(element.parent) ?: return null
val parentUElement = convertElementWithParent(parent, null) ?: return null
val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall)
val method = uExpression.resolve() ?: return null
val containingClass = method.containingClass ?: return null
return UastLanguagePlugin.ResolvedConstructor(uExpression, method, containingClass)
}
override fun isExpressionValueUsed(element: UExpression): Boolean {
return when (element) {
is KotlinUSimpleReferenceExpression.KotlinAccessorCallExpression -> element.setterValue != null
is KotlinAbstractUExpression -> {
val ktElement = element.sourcePsi as? KtElement ?: return false
ktElement.analyze()[BindingContext.USED_AS_EXPRESSION, ktElement] ?: false
}
else -> false
}
}
@Suppress("UNCHECKED_CAST")
fun <T : UElement> convertElement(element: PsiElement, parent: UElement?, expectedTypes: Array<out Class<out T>>): T? {
val nonEmptyExpectedTypes = expectedTypes.nonEmptyOr(DEFAULT_TYPES_LIST)
return if (!canConvert(element, nonEmptyExpectedTypes) || !element.isJvmElement) null
else convertDeclarationOrElement(element, parent, nonEmptyExpectedTypes) as? T
}
override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? {
return convertElement(element, null, requiredTypes)
}
@Suppress("UNCHECKED_CAST")
override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> =
if (!element.isJvmElement) emptySequence() else when {
element is KtFile -> KotlinConverter.convertKtFile(element, null, requiredTypes) as Sequence<T>
(element is KtProperty && !element.isLocal) ->
KotlinConverter.convertNonLocalProperty(element, null, requiredTypes) as Sequence<T>
element is KtParameter -> KotlinConverter.convertParameter(element, null, requiredTypes) as Sequence<T>
element is KtClassOrObject -> KotlinConverter.convertClassOrObject(element, null, requiredTypes) as Sequence<T>
element is UastFakeLightPrimaryConstructor ->
KotlinConverter.convertFakeLightConstructorAlternatices(element, null, requiredTypes) as Sequence<T>
else -> sequenceOf(convertElementWithParent(element, requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)) as? T).filterNotNull()
}
override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> =
when (uastTypes.size) {
0 -> getPossibleSourceTypes(UElement::class.java)
1 -> getPossibleSourceTypes(uastTypes.single())
else -> ClassSetsWrapper<PsiElement>(Array(uastTypes.size) { getPossibleSourceTypes(uastTypes[it]) })
}
override val analysisPlugin: UastAnalysisPlugin?
get() = UastAnalysisPlugin.byLanguage(KotlinLanguage.INSTANCE)
}
internal inline fun <reified ActualT : UElement> Class<*>?.el(f: () -> UElement?): UElement? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Array<out Class<out UElement>>.el(f: () -> UElement?): UElement? {
return if (isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Array<out Class<out UElement>>.expr(f: () -> UExpression?): UExpression? {
return if (isAssignableFrom(ActualT::class.java)) f() else null
}
internal fun Array<out Class<out UElement>>.isAssignableFrom(cls: Class<*>) = any { it.isAssignableFrom(cls) }
internal object KotlinConverter {
internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) {
is KtValueArgumentList -> unwrapElements(element.parent)
is KtValueArgument -> unwrapElements(element.parent)
is KtDeclarationModifierList -> unwrapElements(element.parent)
is KtContainerNode -> unwrapElements(element.parent)
is KtSimpleNameStringTemplateEntry -> unwrapElements(element.parent)
is KtLightParameterList -> unwrapElements(element.parent)
is KtTypeElement -> unwrapElements(element.parent)
is KtSuperTypeList -> unwrapElements(element.parent)
is KtFinallySection -> unwrapElements(element.parent)
is KtAnnotatedExpression -> unwrapElements(element.parent)
is KtWhenConditionWithExpression -> unwrapElements(element.parent)
is KDocLink -> unwrapElements(element.parent)
is KDocSection -> unwrapElements(element.parent)
is KDocTag -> unwrapElements(element.parent)
else -> element
}
private val identifiersTokens = setOf(
KtTokens.IDENTIFIER, KtTokens.CONSTRUCTOR_KEYWORD, KtTokens.OBJECT_KEYWORD,
KtTokens.THIS_KEYWORD, KtTokens.SUPER_KEYWORD,
KtTokens.GET_KEYWORD, KtTokens.SET_KEYWORD
)
internal fun convertPsiElement(element: PsiElement?,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
return {
@Suppress("UNCHECKED_CAST")
ctor(element as P, givenParent)
}
}
return with (expectedTypes) { when (element) {
is KtParameterList -> el<UDeclarationsExpression> {
val declarationsExpression = KotlinUDeclarationsExpression(givenParent)
declarationsExpression.apply {
declarations = element.parameters.mapIndexed { i, p ->
KotlinUParameter(UastKotlinPsiParameter.create(p, element, declarationsExpression, i), p, this)
}
}
}
is KtClassBody -> el<UExpressionList>(build(KotlinUExpressionList.Companion::createClassBody))
is KtCatchClause -> el<UCatchClause>(build(::KotlinUCatchClause))
is KtVariableDeclaration ->
if (element is KtProperty && !element.isLocal) {
convertNonLocalProperty(element, givenParent, this).firstOrNull()
}
else {
el<UVariable> { convertVariablesDeclaration(element, givenParent).declarations.singleOrNull() }
?: expr<UDeclarationsExpression> { KotlinConverter.convertExpression(element, givenParent, expectedTypes) }
}
is KtExpression -> KotlinConverter.convertExpression(element, givenParent, expectedTypes)
is KtLambdaArgument -> element.getLambdaExpression()?.let { KotlinConverter.convertExpression(it, givenParent, expectedTypes) }
is KtLightElementBase -> {
val expression = element.kotlinOrigin
when (expression) {
is KtExpression -> KotlinConverter.convertExpression(expression, givenParent, expectedTypes)
else -> el<UExpression> { UastEmptyExpression(givenParent) }
}
}
is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> el<ULiteralExpression>(build(::KotlinStringULiteralExpression))
is KtStringTemplateEntry -> element.expression?.let { convertExpression(it, givenParent, expectedTypes) } ?: expr<UExpression> { UastEmptyExpression(givenParent) }
is KtWhenEntry -> el<USwitchClauseExpressionWithBody>(build(::KotlinUSwitchEntry))
is KtWhenCondition -> convertWhenCondition(element, givenParent, expectedTypes)
is KtTypeReference ->
expectedTypes.accommodate(
alternative { LazyKotlinUTypeReferenceExpression(element, givenParent) },
alternative { convertReceiverParameter(element) }
).firstOrNull()
is KtConstructorDelegationCall ->
el<UCallExpression> { KotlinUFunctionCallExpression(element, givenParent) }
is KtSuperTypeCallEntry ->
el<UExpression> {
(element.getParentOfType<KtClassOrObject>(true)?.parent as? KtObjectLiteralExpression)
?.toUElementOfType<UExpression>()
?: KotlinUFunctionCallExpression(element, givenParent)
}
is KtImportDirective -> el<UImportStatement>(build(::KotlinUImportStatement))
is PsiComment -> el<UComment>(build(::UComment))
is KDocName -> {
if (element.getQualifier() == null)
el<USimpleNameReferenceExpression> {
element.lastChild?.let { psiIdentifier ->
KotlinStringUSimpleReferenceExpression(psiIdentifier.text, givenParent, element, element)
}
}
else el<UQualifiedReferenceExpression>(build(::KotlinDocUQualifiedReferenceExpression))
}
else -> {
if (element is LeafPsiElement) {
if (element.elementType in identifiersTokens)
if (element.elementType != KtTokens.OBJECT_KEYWORD || element.getParentOfType<KtObjectDeclaration>(false)?.nameIdentifier == null)
el<UIdentifier>(build(::KotlinUIdentifier))
else null
else if (element.elementType in KtTokens.OPERATIONS && element.parent is KtOperationReferenceExpression)
el<UIdentifier>(build(::KotlinUIdentifier))
else if (element.elementType == KtTokens.LBRACKET && element.parent is KtCollectionLiteralExpression)
el<UIdentifier> {
UIdentifier(
element,
KotlinUCollectionLiteralExpression(
element.parent as KtCollectionLiteralExpression,
null
)
)
}
else null
} else null
}
}}
}
internal fun convertReceiverParameter(receiver: KtTypeReference): UParameter? {
val call = (receiver.parent as? KtCallableDeclaration) ?: return null
if (call.receiverTypeReference != receiver) return null
return call.toUElementOfType<UMethod>()?.uastParameters?.firstOrNull()
}
internal fun convertEntry(entry: KtStringTemplateEntry,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>>
): UExpression? {
return with(requiredType) {
if (entry is KtStringTemplateEntryWithExpression) {
expr<UExpression> {
KotlinConverter.convertOrEmpty(entry.expression, givenParent)
}
}
else {
expr<ULiteralExpression> {
if (entry is KtEscapeStringTemplateEntry)
KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue)
else
KotlinStringULiteralExpression(entry, givenParent)
}
}
}
}
var forceUInjectionHost = Registry.`is`("kotlin.uast.force.uinjectionhost", false)
@TestOnly
set(value) {
field = value
}
internal fun convertExpression(expression: KtExpression,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>>
): UExpression? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
return {
@Suppress("UNCHECKED_CAST")
ctor(expression as P, givenParent)
}
}
return with (requiredType) { when (expression) {
is KtVariableDeclaration -> expr<UDeclarationsExpression>(build(::convertVariablesDeclaration))
is KtStringTemplateExpression -> {
when {
forceUInjectionHost || requiredType.contains(UInjectionHost::class.java) ->
expr<UInjectionHost> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) }
expression.entries.isEmpty() -> {
expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, givenParent, "") }
}
expression.entries.size == 1 -> convertEntry(expression.entries[0], givenParent, requiredType)
else ->
expr<KotlinStringTemplateUPolyadicExpression> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) }
}
}
is KtDestructuringDeclaration -> expr<UDeclarationsExpression> {
val declarationsExpression = KotlinUDestructuringDeclarationExpression(givenParent, expression)
declarationsExpression.apply {
val tempAssignment = KotlinULocalVariable(UastKotlinPsiVariable.create(expression, declarationsExpression), expression, declarationsExpression)
val destructuringAssignments = expression.entries.mapIndexed { i, entry ->
val psiFactory = KtPsiFactory(expression.project)
val initializer = psiFactory.createAnalyzableExpression("${tempAssignment.name}.component${i + 1}()",
expression.containingFile)
initializer.destructuringDeclarationInitializer = true
KotlinULocalVariable(UastKotlinPsiVariable.create(entry, tempAssignment.javaPsi, declarationsExpression, initializer), entry, declarationsExpression)
}
declarations = listOf(tempAssignment) + destructuringAssignments
}
}
is KtLabeledExpression -> expr<ULabeledExpression>(build(::KotlinULabeledExpression))
is KtClassLiteralExpression -> expr<UClassLiteralExpression>(build(::KotlinUClassLiteralExpression))
is KtObjectLiteralExpression -> expr<UObjectLiteralExpression>(build(::KotlinUObjectLiteralExpression))
is KtDotQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUQualifiedReferenceExpression))
is KtSafeQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUSafeQualifiedExpression))
is KtSimpleNameExpression -> expr<USimpleNameReferenceExpression>(build(::KotlinUSimpleReferenceExpression))
is KtCallExpression -> expr<UCallExpression>(build(::KotlinUFunctionCallExpression))
is KtCollectionLiteralExpression -> expr<UCallExpression>(build(::KotlinUCollectionLiteralExpression))
is KtBinaryExpression -> {
if (expression.operationToken == KtTokens.ELVIS) {
expr<UExpressionList>(build(::createElvisExpression))
}
else expr<UBinaryExpression>(build(::KotlinUBinaryExpression))
}
is KtParenthesizedExpression -> expr<UParenthesizedExpression>(build(::KotlinUParenthesizedExpression))
is KtPrefixExpression -> expr<UPrefixExpression>(build(::KotlinUPrefixExpression))
is KtPostfixExpression -> expr<UPostfixExpression>(build(::KotlinUPostfixExpression))
is KtThisExpression -> expr<UThisExpression>(build(::KotlinUThisExpression))
is KtSuperExpression -> expr<USuperExpression>(build(::KotlinUSuperExpression))
is KtCallableReferenceExpression -> expr<UCallableReferenceExpression>(build(::KotlinUCallableReferenceExpression))
is KtIsExpression -> expr<UBinaryExpressionWithType>(build(::KotlinUTypeCheckExpression))
is KtIfExpression -> expr<UIfExpression>(build(::KotlinUIfExpression))
is KtWhileExpression -> expr<UWhileExpression>(build(::KotlinUWhileExpression))
is KtDoWhileExpression -> expr<UDoWhileExpression>(build(::KotlinUDoWhileExpression))
is KtForExpression -> expr<UForEachExpression>(build(::KotlinUForEachExpression))
is KtWhenExpression -> expr<USwitchExpression>(build(::KotlinUSwitchExpression))
is KtBreakExpression -> expr<UBreakExpression>(build(::KotlinUBreakExpression))
is KtContinueExpression -> expr<UContinueExpression>(build(::KotlinUContinueExpression))
is KtReturnExpression -> expr<UReturnExpression>(build(::KotlinUReturnExpression))
is KtThrowExpression -> expr<UThrowExpression>(build(::KotlinUThrowExpression))
is KtBlockExpression -> expr<UBlockExpression> {
if (expression.parent is KtFunctionLiteral
&& expression.parent.parent is KtLambdaExpression
&& givenParent !is KotlinULambdaExpression
) {
KotlinULambdaExpression(expression.parent.parent as KtLambdaExpression, givenParent).body
} else
KotlinUBlockExpression(expression, givenParent)
}
is KtConstantExpression -> expr<ULiteralExpression>(build(::KotlinULiteralExpression))
is KtTryExpression -> expr<UTryExpression>(build(::KotlinUTryExpression))
is KtArrayAccessExpression -> expr<UArrayAccessExpression>(build(::KotlinUArrayAccessExpression))
is KtLambdaExpression -> expr<ULambdaExpression>(build(::KotlinULambdaExpression))
is KtBinaryExpressionWithTypeRHS -> expr<UBinaryExpressionWithType>(build(::KotlinUBinaryExpressionWithType))
is KtClassOrObject -> expr<UDeclarationsExpression> {
expression.toLightClass()?.let { lightClass ->
KotlinUDeclarationsExpression(givenParent).apply {
declarations = listOf(KotlinUClass.create(lightClass, this))
}
} ?: UastEmptyExpression(givenParent)
}
is KtFunction -> if (expression.name.isNullOrEmpty()) {
expr<ULambdaExpression>(build(::createLocalFunctionLambdaExpression))
}
else {
expr<UDeclarationsExpression>(build(::createLocalFunctionDeclaration))
}
is KtAnnotatedExpression -> {
expression.baseExpression
?.let { convertExpression(it, givenParent, requiredType) }
?: expr<UExpression>(build(::UnknownKotlinExpression))
}
else -> expr<UExpression>(build(::UnknownKotlinExpression))
}}
}
internal fun convertWhenCondition(condition: KtWhenCondition,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>>
): UExpression? {
return with(requiredType) {
when (condition) {
is KtWhenConditionInRange -> expr<UBinaryExpression> {
KotlinCustomUBinaryExpression(condition, givenParent).apply {
leftOperand = KotlinStringUSimpleReferenceExpression("it", this)
operator = when {
condition.isNegated -> KotlinBinaryOperators.NOT_IN
else -> KotlinBinaryOperators.IN
}
rightOperand = KotlinConverter.convertOrEmpty(condition.rangeExpression, this)
}
}
is KtWhenConditionIsPattern -> expr<UBinaryExpression> {
KotlinCustomUBinaryExpressionWithType(condition, givenParent).apply {
operand = KotlinStringUSimpleReferenceExpression("it", this)
operationKind = when {
condition.isNegated -> KotlinBinaryExpressionWithTypeKinds.NEGATED_INSTANCE_CHECK
else -> UastBinaryExpressionWithTypeKind.InstanceCheck.INSTANCE
}
val typeRef = condition.typeReference
typeReference = typeRef?.let {
LazyKotlinUTypeReferenceExpression(it, this) { typeRef.toPsiType(this, boxed = true) }
}
}
}
is KtWhenConditionWithExpression ->
condition.expression?.let { KotlinConverter.convertExpression(it, givenParent, requiredType) }
else -> expr<UExpression> { UastEmptyExpression(givenParent) }
}
}
}
private fun convertEnumEntry(original: KtEnumEntry, givenParent: UElement?): UElement? {
return LightClassUtil.getLightClassBackingField(original)?.let { psiField ->
if (psiField is KtLightField && psiField is PsiEnumConstant) {
KotlinUEnumConstant(psiField, psiField.kotlinOrigin, givenParent)
} else {
null
}
}
}
internal fun convertDeclaration(
element: PsiElement,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): UElement? {
val original = element.originalElement
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? = {
@Suppress("UNCHECKED_CAST")
ctor(original as P, givenParent)
}
fun <P : PsiElement, K : KtElement> buildKt(ktElement: K, ctor: (P, K, UElement?) -> UElement): () -> UElement? = {
@Suppress("UNCHECKED_CAST")
ctor(original as P, ktElement, givenParent)
}
fun <P : PsiElement, K : KtElement> buildKtOpt(ktElement: K?, ctor: (P, K?, UElement?) -> UElement): () -> UElement? = {
@Suppress("UNCHECKED_CAST")
ctor(original as P, ktElement, givenParent)
}
fun Array<out Class<out UElement>>.convertToUField(original: PsiField, kotlinOrigin: KtElement?): UElement? =
if (original is PsiEnumConstant)
el<UEnumConstant>(buildKtOpt(kotlinOrigin, ::KotlinUEnumConstant))
else
el<UField>(buildKtOpt(kotlinOrigin, ::KotlinUField))
return with(expectedTypes) {
when (original) {
is KtLightMethod -> el<UMethod>(build(KotlinUMethod::create))
is UastFakeLightMethod -> el<UMethod> {
val ktFunction = original.original
if (ktFunction.isLocal)
convertDeclaration(ktFunction, givenParent, expectedTypes)
else
KotlinUMethodWithFakeLightDelegate(ktFunction, original, givenParent)
}
is UastFakeLightPrimaryConstructor ->
convertFakeLightConstructorAlternatices(original, givenParent, expectedTypes).firstOrNull()
is KtLightClass -> when (original.kotlinOrigin) {
is KtEnumEntry -> el<UEnumConstant> {
convertEnumEntry(original.kotlinOrigin as KtEnumEntry, givenParent)
}
else -> el<UClass> { KotlinUClass.create(original, givenParent) }
}
is KtLightField -> convertToUField(original, original.kotlinOrigin)
is KtLightFieldForSourceDeclarationSupport ->
// KtLightFieldForDecompiledDeclaration is not a KtLightField
convertToUField(original, original.kotlinOrigin)
is KtLightParameter -> el<UParameter>(buildKtOpt(original.kotlinOrigin, ::KotlinUParameter))
is UastKotlinPsiParameter -> el<UParameter>(buildKt(original.ktParameter, ::KotlinUParameter))
is UastKotlinPsiParameterBase<*> -> el<UParameter> {
original.ktOrigin.safeAs<KtTypeReference>()?.let { convertReceiverParameter(it) }
}
is UastKotlinPsiVariable -> el<ULocalVariable>(buildKt(original.ktElement, ::KotlinULocalVariable))
is KtEnumEntry -> el<UEnumConstant> {
convertEnumEntry(original, givenParent)
}
is KtClassOrObject -> convertClassOrObject(original, givenParent, this).firstOrNull()
is KtFunction ->
if (original.isLocal) {
el<ULambdaExpression> {
val parent = original.parent
if (parent is KtLambdaExpression) {
KotlinULambdaExpression(parent, givenParent) // your parent is the ULambdaExpression
} else if (original.name.isNullOrEmpty()) {
createLocalFunctionLambdaExpression(original, givenParent)
} else {
val uDeclarationsExpression = createLocalFunctionDeclaration(original, givenParent)
val localFunctionVar = uDeclarationsExpression.declarations.single() as KotlinLocalFunctionUVariable
localFunctionVar.uastInitializer
}
}
} else {
el<UMethod> {
val lightMethod = LightClassUtil.getLightClassMethod(original)
if (lightMethod != null)
convertDeclaration(lightMethod, givenParent, expectedTypes)
else {
val ktLightClass = getLightClassForFakeMethod(original) ?: return null
KotlinUMethodWithFakeLightDelegate(original, ktLightClass, givenParent)
}
}
}
is KtPropertyAccessor -> el<UMethod> {
val lightMethod = LightClassUtil.getLightClassAccessorMethod(original) ?: return null
convertDeclaration(lightMethod, givenParent, expectedTypes)
}
is KtProperty ->
if (original.isLocal) {
KotlinConverter.convertPsiElement(original, givenParent, expectedTypes)
} else {
convertNonLocalProperty(original, givenParent, expectedTypes).firstOrNull()
}
is KtParameter -> convertParameter(original, givenParent, this).firstOrNull()
is KtFile -> convertKtFile(original, givenParent, this).firstOrNull()
is FakeFileForLightClass -> el<UFile> { KotlinUFile(original.navigationElement) }
is KtAnnotationEntry -> el<UAnnotation>(build(::KotlinUAnnotation))
is KtCallExpression ->
if (expectedTypes.isAssignableFrom(KotlinUNestedAnnotation::class.java) && !expectedTypes.isAssignableFrom(UCallExpression::class.java)) {
el<UAnnotation> { KotlinUNestedAnnotation.tryCreate(original, givenParent) }
} else null
is KtLightAnnotationForSourceEntry -> convertDeclarationOrElement(original.kotlinOrigin, givenParent, expectedTypes)
is KtDelegatedSuperTypeEntry -> el<KotlinSupertypeDelegationUExpression> {
KotlinSupertypeDelegationUExpression(original, givenParent)
}
else -> null
}
}
}
internal fun convertFakeLightConstructorAlternatices(
original: UastFakeLightPrimaryConstructor,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): Sequence<UElement> {
return expectedTypes.accommodate(
alternative { convertDeclaration(original.original, givenParent, expectedTypes) as? UClass },
alternative { KotlinConstructorUMethod(original.original, original, original.original, givenParent) }
)
}
private fun getLightClassForFakeMethod(original: KtFunction): KtLightClass? {
if (original.isLocal) return null
return getContainingLightClass(original)
}
fun convertDeclarationOrElement(
element: PsiElement,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): UElement? {
return if (element is UElement) element
else convertDeclaration(element, givenParent, expectedTypes)
?: KotlinConverter.convertPsiElement(element, givenParent, expectedTypes)
}
private fun convertToPropertyAlternatives(
methods: LightClassUtil.PropertyAccessorsPsiMethods?,
givenParent: UElement?
): Array<UElementAlternative<*>> = if (methods != null) arrayOf(
alternative { methods.backingField?.let { KotlinUField(it, (it as? KtLightElement<*, *>)?.kotlinOrigin, givenParent) } },
alternative { methods.getter?.let { convertDeclaration(it, givenParent, arrayOf(UMethod::class.java)) as? UMethod } },
alternative { methods.setter?.let { convertDeclaration(it, givenParent, arrayOf(UMethod::class.java)) as? UMethod } }
) else emptyArray()
fun convertNonLocalProperty(
property: KtProperty,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): Sequence<UElement> =
expectedTypes.accommodate(*convertToPropertyAlternatives(LightClassUtil.getLightClassPropertyMethods(property), givenParent))
fun convertParameter(
element: KtParameter,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): Sequence<UElement> = expectedTypes.accommodate(
alternative uParam@{
val lightMethod = when (val ownerFunction = element.ownerFunction) {
is KtFunction -> LightClassUtil.getLightClassMethod(ownerFunction)
?: getLightClassForFakeMethod(ownerFunction)
?.takeIf { !it.isAnnotationType }
?.let { UastFakeLightMethod(ownerFunction, it) }
is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethod(ownerFunction)
else -> null
} ?: return@uParam null
val lightParameter = lightMethod.parameterList.parameters.find { it.name == element.name } ?: return@uParam null
KotlinUParameter(lightParameter, element, givenParent)
},
alternative catch@{
val uCatchClause = element.parent?.parent?.safeAs<KtCatchClause>()?.toUElementOfType<UCatchClause>() ?: return@catch null
uCatchClause.parameters.firstOrNull { it.sourcePsi == element }
},
*convertToPropertyAlternatives(LightClassUtil.getLightClassPropertyMethods(element), givenParent)
)
fun convertClassOrObject(
element: KtClassOrObject,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>
): Sequence<UElement> {
val ktLightClass = element.toLightClass() ?: return emptySequence()
val uClass = KotlinUClass.create(ktLightClass, givenParent)
return expectedTypes.accommodate(
alternative { uClass },
alternative primaryConstructor@{
val primaryConstructor = element.primaryConstructor ?: return@primaryConstructor null
uClass.methods.asSequence()
.filter { it.sourcePsi == primaryConstructor }
.firstOrNull()
}
)
}
fun convertKtFile(
element: KtFile,
givenParent: UElement?,
requiredTypes: Array<out Class<out UElement>>
): Sequence<UElement> = requiredTypes.accommodate(
alternative { KotlinUFile(element) },
alternative { element.findFacadeClass()?.let { KotlinUClass.create(it, givenParent) } }
)
internal fun convertOrEmpty(expression: KtExpression?, parent: UElement?): UExpression {
return expression?.let { convertExpression(it, parent, DEFAULT_EXPRESSION_TYPES_LIST) } ?: UastEmptyExpression(parent)
}
internal fun convertOrNull(expression: KtExpression?, parent: UElement?): UExpression? {
return if (expression != null) convertExpression(expression, parent, DEFAULT_EXPRESSION_TYPES_LIST) else null
}
internal fun KtPsiFactory.createAnalyzableExpression(text: String, context: PsiElement): KtExpression =
createAnalyzableProperty("val x = $text", context).initializer ?: error("Failed to create expression from text: '$text'")
internal fun KtPsiFactory.createAnalyzableProperty(text: String, context: PsiElement): KtProperty =
createAnalyzableDeclaration(text, context)
internal fun <TDeclaration : KtDeclaration> KtPsiFactory.createAnalyzableDeclaration(text: String, context: PsiElement): TDeclaration {
val file = createAnalyzableFile("dummy.kt", text, context)
val declarations = file.declarations
assert(declarations.size == 1) { "${declarations.size} declarations in $text" }
@Suppress("UNCHECKED_CAST")
return declarations.first() as TDeclaration
}
}
private fun convertVariablesDeclaration(
psi: KtVariableDeclaration,
parent: UElement?
): UDeclarationsExpression {
val declarationsExpression = parent as? KotlinUDeclarationsExpression
?: psi.parent.toUElementOfType<UDeclarationsExpression>() as? KotlinUDeclarationsExpression
?: KotlinUDeclarationsExpression(null, parent, psi)
val parentPsiElement = parent?.javaPsi //TODO: looks weird. mb look for the first non-null `javaPsi` in `parents` ?
val variable = KotlinUAnnotatedLocalVariable(
UastKotlinPsiVariable.create(psi, parentPsiElement, declarationsExpression), psi, declarationsExpression) { annotationParent ->
psi.annotationEntries.map { KotlinUAnnotation(it, annotationParent) }
}
return declarationsExpression.apply { declarations = listOf(variable) }
}
val kotlinUastPlugin get() = UastLanguagePlugin.getInstances().find { it.language == KotlinLanguage.INSTANCE } ?: KotlinUastLanguagePlugin()
private fun expressionTypes(requiredType: Class<out UElement>?) = requiredType?.let { arrayOf(it) } ?: DEFAULT_EXPRESSION_TYPES_LIST
private fun elementTypes(requiredType: Class<out UElement>?) = requiredType?.let { arrayOf(it) } ?: DEFAULT_TYPES_LIST
private fun <T : UElement> Array<out Class<out T>>.nonEmptyOr(default: Array<out Class<out UElement>>) = takeIf { it.isNotEmpty() }
?: default
private fun <U : UElement> Array<out Class<out UElement>>.accommodate(vararg makers: UElementAlternative<out U>): Sequence<UElement> {
val makersSeq = makers.asSequence()
return this.asSequence()
.flatMap { requiredType -> makersSeq.filter { requiredType.isAssignableFrom(it.uType) } }
.distinct()
.mapNotNull { it.make.invoke() }
}
private inline fun <reified U : UElement> alternative(noinline make: () -> U?) = UElementAlternative(U::class.java, make)
private class UElementAlternative<U : UElement>(val uType: Class<U>, val make: () -> U?)
| apache-2.0 | 21e5baa08decb02b80d5a4750448e806 | 53.023499 | 175 | 0.648929 | 6.055312 | false | false | false | false |
lucasgomes-eti/KotlinAndroidProjects | FilmesStarWars/app/src/main/java/com/lucas/filmesstarwars/StarWarsApi.kt | 1 | 2835 | package com.lucas.filmesstarwars
import android.net.Uri
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import rx.Observable
/**
* Created by lucas on 07/09/2017.
*/
class StarWarsApi{
val service : StarWarsApiDef
init {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor(logging)
val gson = GsonBuilder().setLenient().create()
val retrofit = Retrofit.Builder()
.baseUrl("http://swapi.co/api/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient.build())
.build()
service = retrofit.create<StarWarsApiDef>(StarWarsApiDef::class.java)
}
fun loadMovies() : Observable<Movie>?{
return service.listMovies()
.flatMap { filmResults -> Observable.from(filmResults.results) }
.map { film -> Movie(film.title, film.episodeId, ArrayList<Character>()) }
}
var peopleCache = mutableMapOf<String, Person>()
fun loadMoviesFull() : Observable<Movie>?{
return service.listMovies()
.flatMap { filmResults -> Observable.from(filmResults.results) }
.flatMap { film ->
Observable.zip(
Observable.just(Movie(film.title, film.episodeId, ArrayList<Character>())),
Observable.from(film.personsUrl)
.flatMap { personUrl ->
Observable.concat(
getCache(personUrl),
service.loadPerson(Uri.parse(personUrl).lastPathSegment).doOnNext { person -> peopleCache.put(personUrl, person) }
).first()
}
.map { person -> Character(person!!.name, person.gender) }
.toList(),
{
movie, characters -> movie.characters.addAll(characters)
movie
}
)
}
}
private fun getCache(personUrl : String) : Observable<Person?>?{
return Observable.from(peopleCache.keys)
.filter { key -> key == personUrl }
.map { key -> peopleCache[key] }
}
} | cc0-1.0 | 8bfbc9ef6d13f94a1ae114f40c5a23b3 | 37.324324 | 162 | 0.540388 | 5.431034 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/run/RunConfigurationTest.kt | 1 | 17500 | // 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.run
import com.intellij.execution.Location
import com.intellij.execution.PsiLocation
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.openapi.project.DumbServiceImpl
import com.intellij.openapi.project.PossiblyDumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiManager
import com.intellij.refactoring.RefactoringFactory
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.MapDataContext
import junit.framework.TestCase
import org.jdom.Element
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.checkers.languageVersionSettingsFromText
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.project.withLanguageVersionSettings
import org.jetbrains.kotlin.idea.run.KotlinRunConfiguration.Companion.findMainClassFile
import org.jetbrains.kotlin.idea.search.allScope
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelFunctionFqnNameIndex
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.withCustomLanguageAndApiVersion
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import java.io.File
import java.util.concurrent.atomic.AtomicReference
private const val RUN_PREFIX = "// RUN:"
@RunWith(JUnit38ClassRunner::class)
class RunConfigurationTest : AbstractRunConfigurationTest() {
fun testMainInTest() {
configureProject()
val configuredModule = defaultConfiguredModule
val languageVersion = KotlinPluginLayout.instance.standaloneCompilerVersion.languageVersion
withCustomLanguageAndApiVersion(project, module, languageVersion, apiVersion = null) {
val runConfiguration = createConfigurationFromMain(project, "some.main")
val javaParameters = getJavaRunParameters(runConfiguration)
assertTrue(javaParameters.classPath.rootDirs.contains(configuredModule.srcOutputDir))
assertTrue(javaParameters.classPath.rootDirs.contains(configuredModule.testOutputDir))
fun VirtualFile.findKtFiles(): List<VirtualFile> {
return children.filter { it.isDirectory }.flatMap { it.findKtFiles() } + children.filter { it.extension == "kt" }
}
val files = configuredModule.srcDir?.findKtFiles().orEmpty()
val psiManager = PsiManager.getInstance(project)
for (file in files) {
val ktFile = psiManager.findFile(file) as? KtFile ?: continue
val languageVersionSettings = languageVersionSettingsFromText(listOf(ktFile.text))
module.withLanguageVersionSettings(languageVersionSettings) {
var functionCandidates: List<KtNamedFunction>? = null
ktFile.acceptChildren(
object : KtTreeVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
functionCandidates = functionVisitor(languageVersionSettings, function)
}
}
)
val foundMainCandidates = functionCandidates?.isNotEmpty() ?: false
TestCase.assertTrue(
"function candidates expected to be found for $file",
foundMainCandidates
)
val foundMainFileContainer = EntryPointContainerFinder.find(ktFile)
if (functionCandidates?.any { it.isMainFunction(languageVersionSettings) } == true) {
assertNotNull(
"$file: Kotlin configuration producer should produce configuration for $file",
foundMainFileContainer
)
} else {
assertNull(
"$file: Kotlin configuration producer shouldn't produce configuration for $file",
foundMainFileContainer
)
}
}
}
}
}
fun testDependencyModuleClasspath() {
configureProject()
val configuredModule = defaultConfiguredModule
val configuredModuleWithDependency = getConfiguredModule("moduleWithDependency")
ModuleRootModificationUtil.addDependency(configuredModuleWithDependency.module, configuredModule.module)
val kotlinRunConfiguration = createConfigurationFromMain(project, "some.test.main")
kotlinRunConfiguration.setModule(configuredModuleWithDependency.module)
val javaParameters = getJavaRunParameters(kotlinRunConfiguration)
assertTrue(javaParameters.classPath.rootDirs.contains(configuredModule.srcOutputDir))
assertTrue(javaParameters.classPath.rootDirs.contains(configuredModuleWithDependency.srcOutputDir))
}
fun testLongCommandLine() {
configureProject()
ModuleRootModificationUtil.addDependency(module, createLibraryWithLongPaths(project))
val kotlinRunConfiguration = createConfigurationFromMain(project, "some.test.main")
kotlinRunConfiguration.setModule(module)
val javaParameters = getJavaRunParameters(kotlinRunConfiguration)
val commandLine = javaParameters.toCommandLine().commandLineString
assert(commandLine.length > javaParameters.classPath.pathList.joinToString(File.pathSeparator).length) {
"Wrong command line length: \ncommand line = $commandLine, \nclasspath = ${javaParameters.classPath.pathList.joinToString()}"
}
}
fun testClassesAndObjects() = checkClasses()
fun testInJsModule() = checkClasses(Platform.JavaScript)
fun testRedirectInputPath() {
configureProject()
val runConfiguration1 = createConfigurationFromMain(project, "some.main")
runConfiguration1.inputRedirectOptions.apply {
isRedirectInput = true
redirectInputPath = "someFile"
}
val elementWrite = Element("temp")
runConfiguration1.writeExternal(elementWrite)
val runConfiguration2 = createConfigurationFromMain(project, "some.main")
runConfiguration2.readExternal(elementWrite)
assertEquals(runConfiguration1.inputRedirectOptions.isRedirectInput, runConfiguration2.inputRedirectOptions.isRedirectInput)
assertEquals(runConfiguration1.inputRedirectOptions.redirectInputPath, runConfiguration2.inputRedirectOptions.redirectInputPath)
}
fun testIsEditableInADumbMode() {
configureProject()
val runConfiguration = createConfigurationFromObject("foo.Bar")
with(runConfiguration.factory!!) {
assertTrue(isEditableInDumbMode)
assertTrue(safeAs<PossiblyDumbAware>()!!.isDumbAware)
}
}
fun testUpdateOnClassRename() {
configureProject()
val runConfiguration = createConfigurationFromObject("renameTest.Foo")
val obj = KotlinFullClassNameIndex.get("renameTest.Foo", project, project.allScope()).single()
val rename = RefactoringFactory.getInstance(project).createRename(obj, "Bar")
rename.run()
assertEquals("renameTest.Bar", runConfiguration.runClass)
}
fun testUpdateOnPackageRename() {
configureProject()
val runConfiguration = createConfigurationFromObject("renameTest.Foo")
val pkg = JavaPsiFacade.getInstance(project).findPackage("renameTest") ?: error("Package 'renameTest' not found")
val rename = RefactoringFactory.getInstance(project).createRename(pkg, "afterRenameTest")
rename.run()
assertEquals("afterRenameTest.Foo", runConfiguration.runClass)
}
fun testWithModuleForJdk6() {
checkModuleInfoName(null, Platform.Jvm(IdeaTestUtil.getMockJdk16()))
}
fun testWithModuleForJdk9() {
checkModuleInfoName("MAIN", Platform.Jvm(IdeaTestUtil.getMockJdk9()))
}
fun testWithModuleForJdk9WithoutModuleInfo() {
checkModuleInfoName(null, Platform.Jvm(IdeaTestUtil.getMockJdk9()))
}
private fun checkModuleInfoName(moduleName: String?, platform: Platform) {
configureProject(platform)
val javaParameters = getJavaRunParameters(createConfigurationFromMain(project, "some.main"))
assertEquals(moduleName, javaParameters.moduleName)
}
private fun checkClasses(platform: Platform = Platform.Jvm()) {
configureProject(platform)
val srcDir = defaultConfiguredModule.srcDir ?: error("Module doesn't have a production source set")
val expectedClasses = ArrayList<String>()
val actualClasses = ArrayList<String>()
val fileName = "test.kt"
val testKtVirtualFile = srcDir.findFileByRelativePath(fileName) ?: error("Can't find VirtualFile for $fileName")
val testFile = PsiManager.getInstance(project).findFile(testKtVirtualFile) ?: error("Can't find PSI for $fileName")
val visitor = object : KtTreeVisitorVoid() {
override fun visitComment(comment: PsiComment) {
val declaration = comment.getStrictParentOfType<KtNamedDeclaration>()!!
val text = comment.text ?: return
if (!text.startsWith(RUN_PREFIX)) return
val expectedClass = text.substring(RUN_PREFIX.length).trim()
if (expectedClass.isNotEmpty()) expectedClasses.add(expectedClass)
val dataContext = MapDataContext()
dataContext.put(Location.DATA_KEY, PsiLocation(project, declaration))
val context = ConfigurationContext.getFromContext(dataContext)
val actualClass = (context.configuration?.configuration as? KotlinRunConfiguration)?.runClass
if (actualClass != null) {
actualClasses.add(actualClass)
}
}
}
testFile.accept(visitor)
assertEquals(expectedClasses, actualClasses)
}
private fun createConfigurationFromObject(@Suppress("SameParameterValue") objectFqn: String): KotlinRunConfiguration {
val obj = KotlinFullClassNameIndex.get(objectFqn, project, project.allScope()).single()
val mainFunction = obj.declarations.single { it is KtFunction && it.getName() == "main" }
return createConfigurationFromElement(mainFunction, true) as KotlinRunConfiguration
}
companion object {
fun KtNamedFunction.isMainFunction(languageSettings: LanguageVersionSettings) =
MainFunctionDetector(languageSettings) { it.resolveToDescriptorIfAny() }.isMain(this)
private fun functionVisitor(fileLanguageSettings: LanguageVersionSettings, function: KtNamedFunction): List<KtNamedFunction> {
val project = function.project
val file = function.containingKtFile
val options = function.bodyExpression?.allChildren?.filterIsInstance<PsiComment>()
?.map { it.text.trim().replace("//", "").trim() }
?.filter { it.isNotBlank() }?.toList() ?: emptyList()
val functionCandidates = file.collectDescendantsOfType<PsiComment>()
.filter {
val option = it.text.trim().replace("//", "").trim()
"yes" == option || "no" == option
}
.mapNotNull { it.getParentOfType<KtNamedFunction>(true) }
if (options.isNotEmpty()) {
val assertIsMain = "yes" in options
val assertIsNotMain = "no" in options
val isMainFunction = function.isMainFunction(fileLanguageSettings)
val functionCandidatesAreMain = functionCandidates.map { it.isMainFunction(fileLanguageSettings) }
val anyFunctionCandidatesAreMain = functionCandidatesAreMain.any { it }
val allFunctionCandidatesAreNotMain = functionCandidatesAreMain.none { it }
val text = function.containingFile.text
val module = file.module!!
val mainClassName = function.toLightMethods().first().containingClass?.qualifiedName!!
val findMainClassFileSlowResolve = if (text.contains("NO-DUMB-MODE")) {
findMainClassFile(module, mainClassName, true)
} else {
val findMainClassFileResult = AtomicReference<KtFile>()
DumbServiceImpl.getInstance(project).runInDumbMode {
findMainClassFileResult.set(findMainClassFile(module, mainClassName, true))
}
findMainClassFileResult.get()
}
val findMainClassFile = findMainClassFile(module, mainClassName, false)
TestCase.assertEquals(
"findMainClassFile $mainClassName in useSlowResolve $findMainClassFileSlowResolve mode diff from normal mode $findMainClassFile",
findMainClassFileSlowResolve,
findMainClassFile
)
if (assertIsMain) {
assertTrue("$file: The function ${function.fqName?.asString()} should be main", isMainFunction)
if (anyFunctionCandidatesAreMain) {
assertEquals("$file: The function ${function.fqName?.asString()} is main", file, findMainClassFile)
}
}
if (assertIsNotMain) {
assertFalse("$file: The function ${function.fqName?.asString()} should NOT be main", isMainFunction)
if (allFunctionCandidatesAreNotMain) {
assertNull("$file / $findMainClassFile: The function ${function.fqName?.asString()} is NOT main", findMainClassFile)
}
}
val foundMainContainer = EntryPointContainerFinder.find(function)
if (isMainFunction) {
createConfigurationFromMain(project, function.fqName?.asString()!!).checkConfiguration()
assertNotNull(
"$file: Kotlin configuration producer should produce configuration for ${function.fqName?.asString()}",
foundMainContainer
)
} else {
try {
createConfigurationFromMain(project, function.fqName?.asString()!!).checkConfiguration()
fail(
"$file: configuration for function ${function.fqName?.asString()} at least shouldn't pass checkConfiguration()",
)
} catch (expected: Throwable) {
}
if (text.startsWith("// entryPointExists")) {
assertNotNull(
"$file: Kotlin configuration producer should produce configuration for ${function.fqName?.asString()}",
foundMainContainer,
)
} else {
assertNull(
"Kotlin configuration producer shouldn't produce configuration for ${function.fqName?.asString()}",
foundMainContainer,
)
}
}
}
return functionCandidates
}
private fun createConfigurationFromMain(project: Project, mainFqn: String): KotlinRunConfiguration {
val scope = project.allScope()
val mainFunction =
KotlinTopLevelFunctionFqnNameIndex.get(mainFqn, project, scope).firstOrNull()
?: run {
val className = StringUtil.getPackageName(mainFqn)
val shortName = StringUtil.getShortName(mainFqn)
KotlinFullClassNameIndex.get(className, project, scope)
.flatMap { it.declarations }
.filterIsInstance<KtNamedFunction>()
.firstOrNull { it.name == shortName }
} ?: error("unable to look up top level function $mainFqn")
return createConfigurationFromElement(mainFunction) as KotlinRunConfiguration
}
}
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("run")
}
| apache-2.0 | ccc77102954000ac164ff3060b8ee521 | 46.683924 | 158 | 0.657486 | 5.989049 | false | true | false | false |
sureshg/kotlin-starter | src/main/kotlin/io/sureshg/Idiomatic.kt | 1 | 1234 | package io.sureshg
/**
* Idiomatic kotlin
*
* @author Suresh (@sur3shg)
*/
fun main(args: Array<String>) {
//explosivePlaceHolder()
semValidation("HelloKotlin")
println(join("|", listOf("Kotlin", "is", "awesome!")))
}
/**
* Kotlin explosive place holder.
*/
fun explosivePlaceHolder(): String = TODO("Will do later!")
fun semValidation(msg: String) {
requireNotNull(msg) { "Message can't be null" }
require(msg.length > 5) { "$msg length should be > 5" }
check(msg.length > 3) { "$msg size should be > 3" }
checkNotNull(msg) { "Message can't be null" }
assert(msg.substring(2).equals("kotlin", true)) { "$msg - not a valid message." }
}
data class User(val name: String)
fun anyOrNothing(user: User?) {
val name = user?.name ?: throw IllegalStateException("User was null")
println("Name is $name")
}
@Deprecated("String strings.joinToString(sep).", ReplaceWith("strings.joinToString(separator = sep)"), level = DeprecationLevel.WARNING)
fun join(sep: String, strings: List<String>) = strings.joinToString(separator = sep)
sealed class UiOp(val name: String) {
object show : UiOp("show")
object hide : UiOp("hide")
data class Custom(val type: String) : UiOp(type)
}
| apache-2.0 | 980a1fd74c61fe2169ad037482b9e1ee | 26.422222 | 136 | 0.663695 | 3.51567 | false | false | false | false |
jwren/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/ShowCombinedDiffAction.kt | 1 | 1696 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.actions.diff
import com.intellij.diff.editor.DiffEditorTabFilesManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.history.VcsDiffUtil
class ShowCombinedDiffAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val changes = e.getData(VcsDataKeys.CHANGES)
val project = e.project
e.presentation.isEnabledAndVisible = Registry.`is`("enable.combined.diff") &&
project != null && changes != null && changes.size > 1
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val changes = e.getRequiredData(VcsDataKeys.CHANGES)
showDiff(project, changes.toList())
}
companion object {
fun showDiff(project: Project, changes: List<Change>) {
val producers = changes.mapNotNull {
val changeContext = mutableMapOf<Key<out Any>, Any?>()
VcsDiffUtil.putFilePathsIntoChangeContext(it, changeContext)
ChangeDiffRequestProducer.create(project, it, changeContext)
}
val allInOneDiffFile = CombinedChangeDiffVirtualFile(CombinedChangeDiffRequestProducer(producers))
DiffEditorTabFilesManager.getInstance(project).showDiffFile(allInOneDiffFile, true)
}
}
}
| apache-2.0 | 4799d8d37137288ef95dddd516801379 | 39.380952 | 120 | 0.75 | 4.382429 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/local/LocalBlockCopyFactory.kt | 2 | 1489 | package com.github.kerubistan.kerub.planner.steps.storage.block.copy.local
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageBlockDeviceAllocation
import com.github.kerubistan.kerub.model.expectations.CloneOfStorageExpectation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.steps.storage.block.copy.AbstractBlockCopyFactory
import io.github.kerubistan.kroki.collections.concat
object LocalBlockCopyFactory : AbstractBlockCopyFactory<LocalBlockCopy>() {
override fun produce(state: OperationalState): List<LocalBlockCopy> =
state.index.storageCloneRequirement.map { targetStorage ->
val cloneOfStorageExpectation =
targetStorage.stat.expectations.filterIsInstance<CloneOfStorageExpectation>().single()
val sourceStorage = state.vStorage.getValue(cloneOfStorageExpectation.sourceStorageId)
val unallocatedState = createUnallocatedState(state, targetStorage)
sourceStorage.dynamic!!.allocations.filterIsInstance<VirtualStorageBlockDeviceAllocation>()
.map { sourceAllocation ->
allocationFactories.map { allocationFactory ->
allocationFactory.produce(unallocatedState).map { allocationStep ->
LocalBlockCopy(
targetDevice = targetStorage.stat,
sourceAllocation = sourceAllocation,
sourceDevice = sourceStorage.stat,
allocationStep = allocationStep
)
}
}
}
}.concat().concat().concat()
} | apache-2.0 | 569d48aa686790a14f5a301e323f09e1 | 45.5625 | 95 | 0.773674 | 4.898026 | false | false | false | false |
androidx/androidx | wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/DialogSample.kt | 3 | 10297 | /*
* 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.wear.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.animation.graphics.ExperimentalAnimationGraphicsApi
import androidx.compose.animation.graphics.res.animatedVectorResource
import androidx.compose.animation.graphics.res.rememberAnimatedVectorPainter
import androidx.compose.animation.graphics.vector.AnimatedImageVector
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.dialog.Alert
import androidx.wear.compose.material.dialog.Confirmation
import androidx.wear.compose.material.dialog.Dialog
import androidx.wear.compose.material.rememberScalingLazyListState
@Sampled
@Composable
fun AlertDialogSample() {
Box {
var showDialog by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxSize().padding(horizontal = 20.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Chip(
onClick = { showDialog = true },
label = { Text("Show dialog") },
colors = ChipDefaults.secondaryChipColors(),
)
}
val scrollState = rememberScalingLazyListState()
Dialog(
showDialog = showDialog,
onDismissRequest = { showDialog = false },
scrollState = scrollState,
) {
Alert(
scrollState = scrollState,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.Top),
contentPadding =
PaddingValues(start = 10.dp, end = 10.dp, top = 24.dp, bottom = 52.dp),
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(24.dp)
.wrapContentSize(align = Alignment.Center),
)
},
title = { Text(text = "Example Title Text", textAlign = TextAlign.Center) },
message = {
Text(
text = "Message content goes here",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.body2
)
},
) {
item {
Chip(
label = { Text("Primary") },
onClick = { showDialog = false },
colors = ChipDefaults.primaryChipColors(),
)
}
item {
Chip(
label = { Text("Secondary") },
onClick = { showDialog = false },
colors = ChipDefaults.secondaryChipColors(),
)
}
}
}
}
}
@OptIn(ExperimentalAnimationGraphicsApi::class)
@Sampled
@Composable
fun ConfirmationDialogSample() {
Box {
var showDialog by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxSize().padding(horizontal = 25.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Chip(
onClick = { showDialog = true },
label = { Text("Show dialog") },
colors = ChipDefaults.secondaryChipColors(),
)
}
Dialog(showDialog = showDialog, onDismissRequest = { showDialog = false }) {
val animation =
AnimatedImageVector.animatedVectorResource(R.drawable.open_on_phone_animation)
Confirmation(
onTimeout = { showDialog = false },
icon = {
// Initially, animation is static and shown at the start position (atEnd = false).
// Then, we use the EffectAPI to trigger a state change to atEnd = true,
// which plays the animation from start to end.
var atEnd by remember { mutableStateOf(false) }
DisposableEffect(Unit) {
atEnd = true
onDispose {}
}
Image(
painter = rememberAnimatedVectorPainter(animation, atEnd),
contentDescription = "Open on phone",
modifier = Modifier.size(48.dp)
)
},
durationMillis = 3000,
) {
Text(text = "Open on phone", textAlign = TextAlign.Center)
}
}
}
}
@Sampled
@Composable
fun AlertWithButtons() {
Alert(
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(24.dp).wrapContentSize(align = Alignment.Center),
)
},
title = { Text("Title text displayed here", textAlign = TextAlign.Center) },
negativeButton = { Button(
colors = ButtonDefaults.secondaryButtonColors(),
onClick = {
/* Do something e.g. navController.popBackStack()*/
}) {
Text("No")
} },
positiveButton = { Button(onClick = {
/* Do something e.g. navController.popBackStack()*/
}) { Text("Yes") } },
contentPadding =
PaddingValues(start = 10.dp, end = 10.dp, top = 24.dp, bottom = 32.dp),
) {
Text(
text = "Body text displayed here " +
"(swipe right to dismiss)",
textAlign = TextAlign.Center
)
}
}
@Sampled
@Composable
fun AlertWithChips() {
Alert(
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.Top),
contentPadding = PaddingValues(start = 10.dp, end = 10.dp, top = 24.dp, bottom = 52.dp),
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(24.dp).wrapContentSize(align = Alignment.Center),
)
},
title = { Text(text = "Example Title Text", textAlign = TextAlign.Center) },
message = {
Text(
text = "Message content goes here " +
"(swipe right to dismiss)",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.body2
)
},
) {
item {
Chip(
label = { Text("Primary") },
onClick = { /* Do something e.g. navController.popBackStack() */ },
colors = ChipDefaults.primaryChipColors(),
)
}
item {
Chip(
label = { Text("Secondary") },
onClick = { /* Do something e.g. navController.popBackStack() */ },
colors = ChipDefaults.secondaryChipColors(),
)
}
}
}
@OptIn(ExperimentalAnimationGraphicsApi::class)
@Sampled
@Composable
fun ConfirmationWithAnimation() {
val animation = AnimatedImageVector.animatedVectorResource(R.drawable.open_on_phone_animation)
Confirmation(
onTimeout = {
/* Do something e.g. navController.popBackStack() */
},
icon = {
// Initially, animation is static and shown at the start position (atEnd = false).
// Then, we use the EffectAPI to trigger a state change to atEnd = true,
// which plays the animation from start to end.
var atEnd by remember { mutableStateOf(false) }
DisposableEffect(Unit) {
atEnd = true
onDispose {}
}
Image(
painter = rememberAnimatedVectorPainter(animation, atEnd),
contentDescription = "Open on phone",
modifier = Modifier.size(48.dp)
)
},
durationMillis = animation.totalDuration * 2L,
) {
Text(
text = "Body text displayed here " +
"(swipe right to dismiss)",
textAlign = TextAlign.Center
)
}
}
| apache-2.0 | 8403c4823ca8891ffa5c651454e083da | 37.27881 | 102 | 0.578227 | 5.264315 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/KotlinSerializationImportHandler.kt | 1 | 1793 | // 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.compilerPlugin.kotlinxSerialization
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
object KotlinSerializationImportHandler {
private const val pluginJpsJarName = "kotlinx-serialization-compiler-plugin.jar"
val PLUGIN_JPS_JAR: String
get() = File(PathUtil.kotlinPathsForIdeaPlugin.libPath, pluginJpsJarName).absolutePath
fun isPluginJarPath(path: String): Boolean {
return path.endsWith(pluginJpsJarName)
}
fun modifyCompilerArguments(facet: KotlinFacet, buildSystemPluginJar: String) {
val facetSettings = facet.configuration.settings
val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
var pluginWasEnabled = false
val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) {
val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar))
if (lastIndexOfFile < 0) {
return@filterTo true
}
val match = it.drop(lastIndexOfFile + 1).matches("$buildSystemPluginJar-.*\\.jar".toRegex())
if (match) pluginWasEnabled = true
!match
}
val newPluginClasspaths = if (pluginWasEnabled) oldPluginClasspaths + PLUGIN_JPS_JAR else oldPluginClasspaths
commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray()
facetSettings.compilerArguments = commonArguments
}
} | apache-2.0 | 08a4d24ce5498a2fee1fce877527d351 | 45 | 158 | 0.73285 | 5.050704 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.