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
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/widgets/MultiChoiceHelper.kt
1
13959
package be.digitalia.fosdem.widgets import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.util.LongSparseArray import android.util.SparseBooleanArray import android.view.View import android.widget.Checkable import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.core.util.forEach import androidx.core.util.set import androidx.core.util.size import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver import androidx.savedstate.SavedStateRegistryOwner /** * Helper class to reproduce ListView's modal MultiChoice mode with a RecyclerView. * Call setAdapter(adapter, adapterLifecycleOwner) on it as soon as the adapter data is populated. * * @author Christophe Beyls */ class MultiChoiceHelper(private val activity: AppCompatActivity, owner: SavedStateRegistryOwner, listener: MultiChoiceModeListener) { /** * A handy ViewHolder base class which works with the MultiChoiceHelper * and reproduces the default behavior of a ListView. */ abstract class ViewHolder(itemView: View, private val multiChoiceHelper: MultiChoiceHelper) : RecyclerView.ViewHolder(itemView) { private var clickListener: View.OnClickListener? = null fun setOnClickListener(clickListener: View.OnClickListener?) { this.clickListener = clickListener } fun bindSelection() { val position = bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { val isChecked = multiChoiceHelper.isItemChecked(position) val mainView = itemView if (mainView is Checkable) { mainView.isChecked = isChecked } else { mainView.isActivated = isChecked } } } val isMultiChoiceActive: Boolean get() = multiChoiceHelper.checkedItemCount > 0 init { itemView.setOnClickListener { view -> if (isMultiChoiceActive) { val position = bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { multiChoiceHelper.toggleItemChecked(position) } } else { clickListener?.onClick(view) } } itemView.setOnLongClickListener { if (isMultiChoiceActive) { return@setOnLongClickListener false } val position = bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { multiChoiceHelper.setItemChecked(position, true) } true } } } interface MultiChoiceModeListener : ActionMode.Callback { /** * Called when an item is checked or unchecked during selection mode. * * @param mode The [ActionMode] providing the selection mode * @param position Adapter position of the item that was checked or unchecked * @param id Adapter ID of the item that was checked or unchecked * @param checked `true` if the item is now checked, `false` * if the item is now unchecked. */ fun onItemCheckedStateChanged(mode: ActionMode, position: Int, id: Long, checked: Boolean) } private val multiChoiceModeCallback: MultiChoiceModeListener = MultiChoiceModeWrapper(listener) val checkedItemPositions: SparseBooleanArray private val checkedIdStates: LongSparseArray<Int> var checkedItemCount: Int private set var adapter: RecyclerView.Adapter<*>? = null private set private var adapterLifecycle: Lifecycle? = null private var choiceActionMode: ActionMode? = null /** * Make sure this constructor is called before setting the adapter on the RecyclerView * so this class will be notified before the RecyclerView in case of data set changes. */ init { val restoreBundle = owner.savedStateRegistry.consumeRestoredStateForKey(STATE_KEY) if (restoreBundle == null) { checkedItemCount = 0 checkedItemPositions = SparseBooleanArray(0) checkedIdStates = LongSparseArray(0) } else { val savedState: SavedState = restoreBundle.getParcelable(PARCELABLE_KEY)!! checkedItemCount = savedState.checkedItemCount checkedItemPositions = savedState.checkedItemPositions checkedIdStates = savedState.checkedIdStates } owner.savedStateRegistry.registerSavedStateProvider(STATE_KEY) { Bundle(1).apply { putParcelable(PARCELABLE_KEY, SavedState(checkedItemCount, checkedItemPositions.clone(), checkedIdStates.clone())) } } } private val adapterDataSetObserver = object : AdapterDataObserver() { override fun onChanged() { confirmCheckedPositions() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { confirmCheckedPositions() } override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) { confirmCheckedPositions() } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { confirmCheckedPositions() } } private val adapterLifecycleObserver = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_DESTROY) { adapter = null adapterLifecycle = null choiceActionMode?.finish() } } fun setAdapter(adapter: RecyclerView.Adapter<*>, adapterLifecycleOwner: LifecycleOwner) { if (this.adapter !== adapter) { this.adapter?.unregisterAdapterDataObserver(adapterDataSetObserver) this.adapterLifecycle?.removeObserver(adapterLifecycleObserver) this.adapter = adapter this.adapterLifecycle = adapterLifecycleOwner.lifecycle adapter.registerAdapterDataObserver(adapterDataSetObserver) adapterLifecycleOwner.lifecycle.addObserver(adapterLifecycleObserver) if (!adapter.hasStableIds()) { checkedIdStates.clear() } confirmCheckedPositions() if (checkedItemCount > 0) { startSupportActionModeIfNeeded() } } } fun isItemChecked(position: Int): Boolean { return checkedItemPositions[position] } val checkedItemIds: LongArray get() { val idStates = checkedIdStates return LongArray(idStates.size()) { idStates.keyAt(it) } } fun clearChoices() { if (checkedItemCount > 0) { val start = checkedItemPositions.keyAt(0) val end = checkedItemPositions.keyAt(checkedItemPositions.size() - 1) checkedItemPositions.clear() checkedIdStates.clear() checkedItemCount = 0 adapter?.notifyItemRangeChanged(start, end - start + 1, SELECTION_PAYLOAD) choiceActionMode?.finish() } } fun setItemChecked(position: Int, value: Boolean) { // Start selection mode if needed. We don't need it if we're unchecking something. if (value) { startSupportActionModeIfNeeded() } val oldValue = checkedItemPositions[position] checkedItemPositions[position] = value if (oldValue != value) { val id = adapter?.getItemId(position) ?: RecyclerView.NO_ID if (adapter?.hasStableIds() == true) { if (value) { checkedIdStates[id] = position } else { checkedIdStates.remove(id) } } if (value) { checkedItemCount++ } else { checkedItemCount-- } adapter?.notifyItemChanged(position, SELECTION_PAYLOAD) choiceActionMode?.let { multiChoiceModeCallback.onItemCheckedStateChanged(it, position, id, value) if (checkedItemCount == 0) { it.finish() } } } } fun toggleItemChecked(position: Int) { setItemChecked(position, !isItemChecked(position)) } private fun startSupportActionModeIfNeeded() { if (choiceActionMode == null) { choiceActionMode = activity.startSupportActionMode(multiChoiceModeCallback) } } fun confirmCheckedPositions() { val adapter = this.adapter ?: return if (checkedItemCount == 0) { return } val itemCount = adapter.itemCount var checkedCountChanged = false if (itemCount == 0) { // Optimized path for empty adapter: remove all items. checkedItemPositions.clear() checkedIdStates.clear() checkedItemCount = 0 checkedCountChanged = true } else if (adapter.hasStableIds()) { // Clear out the positional check states, we'll rebuild it below from IDs. checkedItemPositions.clear() var checkedIndex = 0 while (checkedIndex < checkedIdStates.size) { val id = checkedIdStates.keyAt(checkedIndex) val lastPos = checkedIdStates.valueAt(checkedIndex) if (lastPos >= itemCount || id != adapter.getItemId(lastPos)) { // Look around to see if the ID is nearby. If not, uncheck it. val start = (lastPos - CHECK_POSITION_SEARCH_DISTANCE).coerceAtLeast(0) val end = (lastPos + CHECK_POSITION_SEARCH_DISTANCE).coerceAtMost(itemCount) var found = false for (searchPos in start until end) { val searchId = adapter.getItemId(searchPos) if (id == searchId) { found = true checkedItemPositions[searchPos] = true checkedIdStates.setValueAt(checkedIndex, searchPos) break } } if (!found) { checkedIdStates.remove(id) checkedIndex-- checkedItemCount-- checkedCountChanged = true choiceActionMode?.let { multiChoiceModeCallback.onItemCheckedStateChanged(it, lastPos, id, false) } } } else { checkedItemPositions[lastPos] = true } checkedIndex++ } } else { // If the total number of items decreased, remove all out-of-range check indexes. for (i in checkedItemPositions.size - 1 downTo 0) { val position = checkedItemPositions.keyAt(i) if (position < itemCount) { break } if (checkedItemPositions.valueAt(i)) { checkedItemCount-- checkedCountChanged = true } checkedItemPositions.delete(position) } } if (checkedCountChanged) { if (checkedItemCount == 0) { choiceActionMode?.finish() } else { choiceActionMode?.invalidate() } } } class SavedState(val checkedItemCount: Int, val checkedItemPositions: SparseBooleanArray, val checkedIdStates: LongSparseArray<Int>) : Parcelable { override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeInt(checkedItemCount) writeSparseBooleanArray(checkedItemPositions) writeInt(checkedIdStates.size) checkedIdStates.forEach { key, value -> writeLong(key) writeInt(value) } } override fun describeContents() = 0 companion object { @JvmField @Suppress("UNUSED") val CREATOR = object : Parcelable.Creator<SavedState> { override fun createFromParcel(source: Parcel): SavedState = with(source) { val checkedItemCount = readInt() val checkedItemPositions = readSparseBooleanArray()!! val size = readInt() val checkedIdStates = LongSparseArray<Int>(size).apply { for (i in 0 until size) { val key = readLong() val value = readInt() append(key, value) } } SavedState(checkedItemCount, checkedItemPositions, checkedIdStates) } override fun newArray(size: Int) = arrayOfNulls<SavedState>(size) } } } private inner class MultiChoiceModeWrapper(private val wrapped: MultiChoiceModeListener) : MultiChoiceModeListener by wrapped { override fun onDestroyActionMode(mode: ActionMode) { wrapped.onDestroyActionMode(mode) choiceActionMode = null clearChoices() } } companion object { @JvmField val SELECTION_PAYLOAD = Any() private const val STATE_KEY = "MultiChoiceHelper" private const val PARCELABLE_KEY = "saved_state" private const val CHECK_POSITION_SEARCH_DISTANCE = 20 } }
apache-2.0
311c8b668209e701ba7e4e9dfcd7fa36
36.426273
133
0.588079
5.658289
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/network/gson/observation/ObservationDeserializer.kt
1
9711
package mil.nga.giat.mage.network.gson.observation import android.util.Log import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import mil.nga.giat.mage.network.gson.* import mil.nga.giat.mage.sdk.datastore.observation.* import mil.nga.giat.mage.sdk.utils.GeometryUtility import mil.nga.giat.mage.sdk.utils.ISO8601DateFormatFactory import java.io.IOException import java.text.ParseException import java.util.* class ObservationDeserializer { private val geometryDeserializer = GeometryTypeAdapter() private val attachmentDeserializer = AttachmentTypeAdapter() fun read(reader: JsonReader): Observation { val observation = Observation() if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return observation } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "id" -> { observation.isDirty = false observation.remoteId = reader.nextString() } "userId" -> observation.userId = reader.nextStringOrNull() "deviceId" -> observation.deviceId = reader.nextStringOrNull() "lastModified" -> { try { observation.lastModified = ISO8601DateFormatFactory.ISO8601().parse(reader.nextString()) } catch (e: Exception) { Log.e(LOG_NAME, "Error parsing observation date.", e) } } "url" -> observation.url = reader.nextString() "state" -> observation.state = readState(reader) "geometry" -> observation.geometry = geometryDeserializer.read(reader) "properties" -> readProperties(reader, observation) "attachments" -> observation.attachments = readAttachments(reader) "important" -> observation.important = readImportant(reader) "favoriteUserIds" -> observation.favorites = readFavoriteUsers(reader) else -> reader.skipValue() } } reader.endObject() return observation } @Throws(IOException::class) private fun readState(reader: JsonReader): State { var state = State.ACTIVE if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return state } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "name" -> { val stateString = reader.nextString() if (stateString != null) { try { state = State.valueOf(stateString.trim().uppercase()) } catch (e: Exception) { Log.e(LOG_NAME, "Could not parse state: $stateString") } } } else -> reader.skipValue() } } reader.endObject() return state } @Throws(IOException::class) private fun readProperties(reader: JsonReader, observation: Observation): Collection<ObservationProperty> { val properties = mutableListOf<ObservationProperty>() if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return properties } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "timestamp" -> { val timestamp = reader.nextString() try { observation.timestamp = ISO8601DateFormatFactory.ISO8601().parse(timestamp) } catch (e: ParseException) { Log.e(LOG_NAME, "Unable to parse date: " + timestamp + " for observation: " + observation.remoteId, e) } } "provider" -> observation.provider = reader.nextStringOrNull() "accuracy" -> { try { observation.accuracy = reader.nextDoubleOrNull()?.toFloat() } catch (e: Exception) { Log.e(LOG_NAME, "Error parsing observation accuracy", e) } } "forms" -> observation.forms = readForms(reader) else -> reader.skipValue() } } reader.endObject() return properties } @Throws(IOException::class) private fun readForms(reader: JsonReader): List<ObservationForm> { val forms = mutableListOf<ObservationForm>() if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue() return forms } reader.beginArray() while(reader.hasNext()) { forms.add(readForm(reader)) } reader.endArray() return forms } @Throws(IOException::class) private fun readForm(reader: JsonReader): ObservationForm { val form = ObservationForm() val properties: MutableCollection<ObservationProperty> = ArrayList() if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return form } reader.beginObject() while(reader.hasNext()) { when(val key = reader.nextName()) { "id" -> form.remoteId = reader.nextString() "formId" -> form.formId = reader.nextLong() else -> { readProperty(key, reader)?.let { properties.add(it) } } } } reader.endObject() form.properties = properties return form } private fun readProperty(key: String, reader: JsonReader): ObservationProperty? { var property: ObservationProperty? = null try { when(reader.peek()) { JsonToken.BEGIN_OBJECT -> { geometryDeserializer.read(reader)?.let { geometry -> val geometryBytes = GeometryUtility.toGeometryBytes(geometry) property = ObservationProperty(key, geometryBytes) } } JsonToken.BEGIN_ARRAY -> { val stringArrayList = ArrayList<String>() val attachments = ArrayList<Attachment>() reader.beginArray() while(reader.hasNext()) { if (reader.peek() == JsonToken.BEGIN_OBJECT) { val attachment = attachmentDeserializer.read(reader) attachments.add(attachment) } else { stringArrayList.add(reader.nextString()) } } if (stringArrayList.isNotEmpty()) { property = ObservationProperty(key, stringArrayList) } else if (attachments.isNotEmpty()) { property = ObservationProperty(key, attachments) } reader.endArray() } JsonToken.NUMBER -> { reader.nextNumberOrNull()?.let { property = ObservationProperty(key, it) } } JsonToken.BOOLEAN -> { reader.nextBooleanOrNull()?.let { property = ObservationProperty(key, it) } } JsonToken.STRING -> { reader.nextStringOrNull()?.let { property = ObservationProperty(key, it) } } else -> reader.skipValue() } } catch (e: Exception) { Log.w(LOG_NAME, "Error parsing observation property, skipping...", e) } return property } @Throws(IOException::class) private fun readAttachments(reader: JsonReader): List<Attachment> { val attachments = mutableListOf<Attachment>() if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue() return attachments } reader.beginArray() while(reader.hasNext()) { attachments.add(attachmentDeserializer.read(reader)) } reader.endArray() return attachments } @Throws(IOException::class) private fun readImportant(reader: JsonReader): ObservationImportant { val important = ObservationImportant() important.isImportant = true important.isDirty = false if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return important } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "userId" -> important.userId = reader.nextStringOrNull() "description" -> important.description = reader.nextStringOrNull() "timestamp" -> { try { important.timestamp = ISO8601DateFormatFactory.ISO8601().parse(reader.nextString()) } catch (e: Exception) { Log.e(LOG_NAME, "Unable to parse observation important date", e) } } else -> reader.skipValue() } } reader.endObject() return important } @Throws(IOException::class) private fun readFavoriteUsers(reader: JsonReader): Collection<ObservationFavorite> { val favorites = mutableListOf<ObservationFavorite>() if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue() return favorites } reader.beginArray() while(reader.hasNext()) { if (reader.peek() == JsonToken.STRING) { val userId = reader.nextString() val favorite = ObservationFavorite(userId, true) favorite.isDirty = false favorites.add(favorite) } else reader.skipValue() } reader.endArray() return favorites } companion object { private val LOG_NAME = ObservationDeserializer::class.java.name } }
apache-2.0
27f07b283757402206407d1e2ed440d1
29.445141
120
0.562558
5.063087
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-113R2/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_13_R2/NMSPetArmorstand.kt
1
18796
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_13_R2 import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.bukkit.event.PetBlocksAIPreChangeEvent import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy import com.github.shynixn.petblocks.api.business.proxy.NMSPetProxy import com.github.shynixn.petblocks.api.business.proxy.PetProxy import com.github.shynixn.petblocks.api.business.service.AIService import com.github.shynixn.petblocks.api.business.service.ConfigurationService import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.persistence.entity.* import com.github.shynixn.petblocks.core.logic.business.extension.hasChanged import com.github.shynixn.petblocks.core.logic.business.extension.relativeFront import com.github.shynixn.petblocks.core.logic.persistence.entity.PositionEntity import net.minecraft.server.v1_13_R2.* import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.craftbukkit.v1_13_R2.CraftWorld import org.bukkit.entity.ArmorStand import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.event.entity.CreatureSpawnEvent import org.bukkit.util.Vector import java.lang.reflect.Field /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class NMSPetArmorstand(owner: Player, val petMeta: PetMeta) : EntityArmorStand((owner.location.world as CraftWorld).handle), NMSPetProxy { private var internalProxy: PetProxy? = null private var jumpingField: Field = EntityLiving::class.java.getDeclaredField("bg") private var internalHitBox: EntityInsentient? = null private val aiService = PetBlocksApi.resolve(AIService::class.java) private val flyCanHitWalls = PetBlocksApi.resolve(ConfigurationService::class.java) .findValue<Boolean>("global-configuration.fly-wall-colision") private var flyHasTakenOffGround = false private var flyIsOnGround: Boolean = false private var flyHasHitFloor: Boolean = false private var flyWallCollisionVector: Vector? = null /** * Proxy handler. */ override val proxy: PetProxy get() = internalProxy!! /** * Initializes the nms design. */ init { jumpingField.isAccessible = true val location = owner.location val mcWorld = (location.world as CraftWorld).handle val position = PositionEntity() position.x = location.x position.y = location.y position.z = location.z position.yaw = location.yaw.toDouble() position.pitch = location.pitch.toDouble() position.worldName = location.world!!.name position.relativeFront(3.0) this.setPositionRotation(position.x, position.y, position.z, location.yaw, location.pitch) mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) internalProxy = Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.PetProxyImpl") .getDeclaredConstructor(PetMeta::class.java, ArmorStand::class.java, Player::class.java) .newInstance(petMeta, this.bukkitEntity, owner) as PetProxy petMeta.propertyTracker.onPropertyChanged(PetMeta::aiGoals, true) applyNBTTagForArmorstand() } /** * Spawns a new hitbox */ private fun spawnHitBox() { val shouldDeleteHitBox = shouldDeleteHitBox() if (shouldDeleteHitBox && internalHitBox != null) { (internalHitBox!!.bukkitEntity as EntityPetProxy).deleteFromWorld() internalHitBox = null proxy.changeHitBox(internalHitBox) } val player = proxy.getPlayer<Player>() this.applyNBTTagForArmorstand() val hasRidingAi = petMeta.aiGoals.count { a -> a is AIGroundRiding || a is AIFlyRiding } > 0 if (hasRidingAi) { val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (!armorstand.passengers.contains(player)) { armorstand.velocity = Vector(0, 1, 0) armorstand.addPassenger(player) } return } else { for (passenger in player.passengers) { if (passenger == this.bukkitEntity) { player.removePassenger(passenger) } } } val aiWearing = this.petMeta.aiGoals.firstOrNull { a -> a is AIWearing } if (aiWearing != null) { this.applyNBTTagForArmorstand() val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (!player.passengers.contains(armorstand)) { player.addPassenger(armorstand) } return } val flyingAi = petMeta.aiGoals.firstOrNull { a -> a is AIFlying } if (flyingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetBat(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetBat).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } val hoppingAi = petMeta.aiGoals.firstOrNull { a -> a is AIHopping } if (hoppingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetRabbit(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetRabbit).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } if (internalHitBox == null) { internalHitBox = NMSPetVillager(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetVillager).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) } /** * Disable setting slots. */ override fun setSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) { } /** * Sets the slot securely. */ fun setSecureSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) { super.setSlot(enumitemslot, itemstack) } /** * Entity tick. */ override fun doTick() { super.doTick() try { proxy.run() if (dead) { return } if (this.internalHitBox != null) { val location = internalHitBox!!.bukkitEntity.location val aiGoal = petMeta.aiGoals.lastOrNull { p -> p is AIMovement } ?: return var y = location.y + (aiGoal as AIMovement).movementYOffSet if (this.isSmall) { y += 0.6 } if (y > -100) { this.setPositionRotation(location.x, y, location.z, location.yaw, location.pitch) this.motX = this.internalHitBox!!.motX this.motY = this.internalHitBox!!.motY this.motZ = this.internalHitBox!!.motZ } } if (proxy.teleportTarget != null) { val location = proxy.teleportTarget!! as Location if (this.internalHitBox != null) { this.internalHitBox!!.setPositionRotation( location.x, location.y, location.z, location.yaw, location.pitch ) } this.setPositionRotation(location.x, location.y, location.z, location.yaw, location.pitch) proxy.teleportTarget = null } if (PetMeta::aiGoals.hasChanged(petMeta)) { val event = PetBlocksAIPreChangeEvent(proxy.getPlayer(), proxy) Bukkit.getPluginManager().callEvent(event) if (event.isCancelled) { return } spawnHitBox() proxy.aiGoals = null } } catch (e: Exception) { PetBlocksApi.resolve(LoggingService::class.java).error("Failed to execute tick.", e) } } /** * Overrides the moving of the pet design. */ override fun move(enummovetype: EnumMoveType?, d0: Double, d1: Double, d2: Double) { super.move(enummovetype, d0, d1, d2) if (passengers == null || this.passengers.firstOrNull { p -> p is EntityHuman } == null) { return } val groundAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } val airAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } var offSet = when { groundAi != null -> (groundAi as AIGroundRiding).ridingYOffSet airAi != null -> (airAi as AIFlyRiding).ridingYOffSet else -> 0.0 } if (this.isSmall) { offSet += 0.6 } val axisBoundingBox = this.boundingBox this.locX = (axisBoundingBox.minX + axisBoundingBox.maxX) / 2.0 this.locY = axisBoundingBox.minY + offSet this.locZ = (axisBoundingBox.minZ + axisBoundingBox.maxZ) / 2.0 } /** * Gets the bukkit entity. */ override fun getBukkitEntity(): CraftPetArmorstand { if (this.bukkitEntity == null) { this.bukkitEntity = CraftPetArmorstand(this.world.server, this) } return this.bukkitEntity as CraftPetArmorstand } /** * Riding function. */ override fun a(sidemot: Float, f2: Float, formot: Float) { val human = this.passengers.firstOrNull { p -> p is EntityHuman } if (this.passengers == null || human == null) { flyHasTakenOffGround = false return } val aiFlyRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } if (aiFlyRiding != null) { rideInAir(human as EntityHuman, aiFlyRiding as AIFlyRiding) return } val aiGroundRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } if (aiGroundRiding != null) { rideOnGround(human as EntityHuman, aiGroundRiding as AIGroundRiding, f2) return } } /** * Handles the riding in air. */ private fun rideInAir(human: EntityHuman, ai: AIFlyRiding) { val sideMot: Float = human.bh * 0.5f val forMot: Float = human.bj this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aQ = this.yaw this.aS = this.aQ val flyingVector = Vector() val flyingLocation = Location(this.world.world, this.locX, this.locY, this.locZ) if (sideMot < 0.0f) { flyingLocation.yaw = human.yaw - 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } else if (sideMot > 0.0f) { flyingLocation.yaw = human.yaw + 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } if (forMot < 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } else if (forMot > 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } if (!flyHasTakenOffGround) { flyHasTakenOffGround = true flyingVector.setY(1f) } if (this.isPassengerJumping()) { flyingVector.setY(0.5f) this.flyIsOnGround = true this.flyHasHitFloor = false } else if (this.flyIsOnGround) { flyingVector.setY(-0.2f) } if (this.flyHasHitFloor) { flyingVector.setY(0) flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } else { flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } val vec3d = Vec3D(this.locX, this.locY, this.locZ) val vec3d1 = Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ) val movingObjectPosition = this.world.rayTrace(vec3d, vec3d1) if (movingObjectPosition == null) { this.flyWallCollisionVector = flyingLocation.toVector() } else if (this.flyWallCollisionVector != null && flyCanHitWalls) { this.setPosition( this.flyWallCollisionVector!!.x, this.flyWallCollisionVector!!.y, this.flyWallCollisionVector!!.z ) } } /** * Handles the riding on ground. */ private fun rideOnGround(human: EntityHuman, ai: AIGroundRiding, f2: Float) { val sideMot: Float = human.bh * 0.5f var forMot: Float = human.bj this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aQ = this.yaw this.aS = this.aQ if (forMot <= 0.0f) { forMot *= 0.25f } if (this.onGround && this.isPassengerJumping()) { this.motY = 0.5 } this.Q = ai.climbingHeight.toFloat() this.aU = this.cK() * 0.1f if (!this.world.isClientSide) { this.o(0.35f) super.a(sideMot * ai.ridingSpeed.toFloat(), f2, forMot * ai.ridingSpeed.toFloat()) } this.aI = this.aJ val d0 = this.locX - this.lastX val d1 = this.locZ - this.lastZ var f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0f if (f4 > 1.0f) { f4 = 1.0f } this.aJ += (f4 - this.aJ) * 0.4f this.aK += this.aJ } /** * Applies the entity NBT to the hitbox. */ private fun applyNBTTagToHitBox(hitBox: EntityInsentient) { val compound = NBTTagCompound() hitBox.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.hitBoxNbt }.toList() ) hitBox.a(compound) // CustomNameVisible does not working via NBT Tags. hitBox.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the entity NBT to the armorstand. */ private fun applyNBTTagForArmorstand() { val compound = NBTTagCompound() this.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.armorStandNbt }.toList() ) this.a(compound) // CustomNameVisible does not working via NBT Tags. this.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the raw NbtData to the given target. */ @Suppress("UNCHECKED_CAST") private fun applyAIEntityNbt(target: NBTTagCompound, rawNbtDatas: List<String>) { val compoundMapField = NBTTagCompound::class.java.getDeclaredField("map") compoundMapField.isAccessible = true val rootCompoundMap = compoundMapField.get(target) as MutableMap<Any?, Any?> for (rawNbtData in rawNbtDatas) { if (rawNbtData.isEmpty()) { continue } val parsedCompound = try { MojangsonParser.parse(rawNbtData) } catch (e: Exception) { throw RuntimeException("NBT Tag '$rawNbtData' cannot be parsed.", e) } val parsedCompoundMap = compoundMapField.get(parsedCompound) as Map<*, *> for (key in parsedCompoundMap.keys) { rootCompoundMap[key] = parsedCompoundMap[key] } } } /** * Should the hitbox of the armorstand be deleted. */ private fun shouldDeleteHitBox(): Boolean { val hasEmptyHitBoxAi = petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding || a is AIFlyRiding || a is AIWearing } != null if (hasEmptyHitBoxAi) { return true } if (internalHitBox != null) { if (internalHitBox is NMSPetVillager && petMeta.aiGoals.firstOrNull { a -> a is AIWalking } == null) { return true } else if (internalHitBox is NMSPetRabbit && petMeta.aiGoals.firstOrNull { a -> a is AIHopping } == null) { return true } else if (internalHitBox is NMSPetBat && petMeta.aiGoals.firstOrNull { a -> a is AIFlying } == null) { return true } } return false } /** * Gets if a passenger of the pet is jumping. */ private fun isPassengerJumping(): Boolean { return passengers != null && !this.passengers.isEmpty() && jumpingField.getBoolean(this.passengers[0]) } }
apache-2.0
1d6e013bdac720261b7e57962071c29b
34.666034
119
0.612418
4.429885
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/cameras/render/SampledRenderer.kt
1
994
package net.dinkla.raytracer.cameras.render import net.dinkla.raytracer.cameras.lenses.ILens import net.dinkla.raytracer.colors.ColorAccumulator import net.dinkla.raytracer.colors.Color import net.dinkla.raytracer.math.Point2D import net.dinkla.raytracer.math.Ray import net.dinkla.raytracer.samplers.MultiJittered import net.dinkla.raytracer.samplers.Sampler import net.dinkla.raytracer.tracers.Tracer class SampledRenderer(var lens: ILens, var tracer: Tracer) : ISingleRayRenderer { // Used for anti-aliasing var sampler: Sampler var numSamples: Int = 0 init { this.numSamples = 1 this.sampler = Sampler(MultiJittered(), 2500, 10) } override fun render(r: Int, c: Int): Color { val color = ColorAccumulator() for (j in 0 until numSamples) { val sp = sampler.sampleUnitSquare() val ray = lens.getRaySampled(r, c, sp) color.plus(tracer.trace(ray!!)) } return color.average } }
apache-2.0
2eb50a921ef5c74678f01db40063120b
30.0625
81
0.698189
3.837838
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/command/RunCargoCommandActionBase.kt
2
2146
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.command import com.intellij.execution.ExecutorRegistry import com.intellij.execution.ProgramRunnerUtil import com.intellij.execution.RunManagerEx import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.module.Module import org.rust.cargo.runconfig.createCargoCommandRunConfiguration import org.rust.cargo.toolchain.CargoCommandLine import org.rust.cargo.util.modulesWithCargoProject import javax.swing.Icon abstract class RunCargoCommandActionBase(icon: Icon) : AnAction(icon) { override fun update(e: AnActionEvent) { val hasCargoModule = e.project?.modulesWithCargoProject.orEmpty().isNotEmpty() e.presentation.isEnabled = hasCargoModule e.presentation.isVisible = hasCargoModule } protected fun getAppropriateModule(e: AnActionEvent): Module? { val cargoModules = e.project?.modulesWithCargoProject.orEmpty() val current = e.getData(LangDataKeys.MODULE) return if (current in cargoModules) current else cargoModules.firstOrNull() } protected fun runCommand(module: Module, cargoCommandLine: CargoCommandLine) { val runConfiguration = createRunConfiguration(module, cargoCommandLine) val executor = ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID) ProgramRunnerUtil.executeConfiguration(module.project, runConfiguration, executor) } private fun createRunConfiguration(module: Module, cargoCommandLine: CargoCommandLine): RunnerAndConfigurationSettings { val runManager = RunManagerEx.getInstanceEx(module.project) return runManager.createCargoCommandRunConfiguration(cargoCommandLine).apply { runManager.setTemporaryConfiguration(this) } } }
mit
40265122f8124e5ae45ad67d5117f065
39.490566
124
0.77726
5.109524
false
true
false
false
rei-m/android_hyakuninisshu
app/src/main/java/me/rei_m/hyakuninisshu/ui/MainActivity.kt
1
4896
/* * Copyright (c) 2020. Rei Matsushita. * * 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 me.rei_m.hyakuninisshu.ui import android.os.Bundle import android.view.MenuItem import android.view.View import android.widget.FrameLayout import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.bottomnavigation.BottomNavigationView import hotchemi.android.rate.AppRate import me.rei_m.hyakuninisshu.App import me.rei_m.hyakuninisshu.BuildConfig import me.rei_m.hyakuninisshu.R import me.rei_m.hyakuninisshu.di.MainComponent import me.rei_m.hyakuninisshu.feature.corecomponent.ext.setupActionBar import me.rei_m.hyakuninisshu.feature.corecomponent.widget.ad.AdViewObserver import javax.inject.Inject class MainActivity : AppCompatActivity(), MainComponent.Injector { override fun mainComponent(): MainComponent = _mainComponent @Inject lateinit var adViewObserver: AdViewObserver private lateinit var _mainComponent: MainComponent private val navController by lazy { findNavController(R.id.nav_host_fragment) } override fun onCreate(savedInstanceState: Bundle?) { _mainComponent = (application as App).appComponent.mainComponent().create(this) _mainComponent.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupActionBar(findViewById(R.id.toolbar)) { } setupNavController() setupAd() setupAppRate() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { navController.popBackStack() return true } } return super.onOptionsItemSelected(item) } private fun setupNavController() { val navView: BottomNavigationView = findViewById(R.id.nav_view) val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_training_menu, R.id.navigation_exam_menu, R.id.navigation_material_list, R.id.navigation_support ) ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) val adViewContainer: FrameLayout = findViewById(R.id.ad_view_container) navController.addOnDestinationChangedListener { _, destination, _ -> when (destination.id) { R.id.splash_fragment -> { supportActionBar?.setDisplayHomeAsUpEnabled(false) navView.visibility = View.GONE } R.id.navigation_training_starter, R.id.navigation_training_re_starter, R.id.navigation_exam_practice_training_starter, R.id.navigation_exam_finisher, R.id.navigation_question, R.id.navigation_question_answer -> { navView.visibility = View.GONE adViewObserver.hideAd() } R.id.navigation_training_result, R.id.navigation_exam_result, R.id.navigation_exam_history, R.id.navigation_material_detail, R.id.navigation_material_detail_page, R.id.navigation_material_edit, R.id.navigation_material_edit_confirm_dialog -> { navView.visibility = View.GONE adViewObserver.showAd(this, adViewContainer) } else -> { navView.visibility = View.VISIBLE adViewObserver.showAd(this, adViewContainer) } } } } private fun setupAppRate() { AppRate.with(this) .setInstallDays(1) .setLaunchTimes(3) .setRemindInterval(10) .setShowLaterButton(true) .setDebug(BuildConfig.DEBUG) .monitor() AppRate.showRateDialogIfMeetsConditions(this) } private fun setupAd() { lifecycle.addObserver(adViewObserver) } }
apache-2.0
56173296a072d7f33776cce63f859774
33.723404
87
0.648693
4.818898
false
false
false
false
Aptoide/aptoide-client-v8
aptoide-views/src/main/java/cm/aptoide/aptoideviews/downloadprogressview/DownloadProgressView.kt
1
11949
package cm.aptoide.aptoideviews.downloadprogressview import android.animation.LayoutTransition import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.util.AttributeSet import android.util.Log import android.view.View import android.widget.FrameLayout import androidx.annotation.CheckResult import androidx.annotation.VisibleForTesting import cm.aptoide.aptoideviews.R import cm.aptoide.aptoideviews.common.Debouncer import com.tinder.StateMachine import kotlinx.android.synthetic.main.download_progress_view.view.* import rx.Observable import kotlin.math.max import kotlin.math.min /** * This view is responsible for handling the display of download progress. * */ class DownloadProgressView : FrameLayout { private var isPausable: Boolean = true private var payload: Any? = null private var eventListener: DownloadEventListener? = null private var debouncer = Debouncer(750) private var currentProgress: Int = 0 private var animationsEnabled = false private var downloadingText: String = "" private var pausedText: String = "" private var installingText: String = "" private var stateMachine = StateMachine.create<State, Event, Any> { initialState(State.Queue) state<State.Queue> { onEnter { Log.d("DownloadProgressView", "State.Queue") resetProgress() progressBar.isIndeterminate = true cancelButton.visibility = View.INVISIBLE resumePauseButton.visibility = View.GONE downloadProgressNumber.visibility = View.GONE downloadState.setText(downloadingText) } on<Event.DownloadStart> { debouncer.reset() transitionTo(State.InProgress) } on<Event.PauseStart> { debouncer.reset() transitionTo(State.InitialPaused) } on<Event.Reset> { dontTransition() } on<Event.CancelClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.CANCEL, payload)) transitionTo(State.Canceled) } on<Event.InstallStart> { transitionTo(State.Installing) } } state<State.Canceled> { onEnter { Log.d("DownloadProgressView", "State.Canceled") resetProgress() progressBar.isIndeterminate = true if (isPausable) { cancelButton.visibility = View.VISIBLE resumePauseButton.visibility = View.GONE } else { cancelButton.visibility = View.VISIBLE resumePauseButton.visibility = View.GONE } downloadProgressNumber.visibility = View.GONE downloadState.setText(downloadingText) } on<Event.Reset> { transitionTo(State.Queue) } on<Event.DownloadStart> { debouncer.reset() transitionTo(State.InProgress) } on<Event.PauseStart> { debouncer.reset() transitionTo(State.InitialPaused) } } state<State.InProgress> { onEnter { Log.d("DownloadProgressView", "State.InProgress") setProgress(currentProgress) progressBar.isIndeterminate = false if (isPausable) { cancelButton.visibility = View.GONE resumePauseButton.visibility = View.VISIBLE } else { cancelButton.visibility = View.VISIBLE resumePauseButton.visibility = View.GONE } resumePauseButton.play() downloadProgressNumber.visibility = View.VISIBLE downloadState.setText(downloadingText) } on<Event.PauseClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.PAUSE, payload)) transitionTo(State.Paused) } on<Event.PauseStart> { transitionTo(State.Paused) } on<Event.InstallStart> { transitionTo(State.Installing) } on<Event.Reset> { transitionTo(State.Queue) } on<Event.CancelClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.CANCEL, payload)) transitionTo(State.Canceled) } } state<State.Paused> { onEnter { Log.d("DownloadProgressView", "State.Paused") progressBar.isIndeterminate = false cancelButton.visibility = View.VISIBLE resumePauseButton.visibility = View.VISIBLE resumePauseButton.playReverse() downloadProgressNumber.visibility = View.VISIBLE downloadState.setText(pausedText) } on<Event.ResumeClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.RESUME, payload)) transitionTo(State.InProgress) } on<Event.CancelClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.CANCEL, payload)) transitionTo(State.Canceled) } on<Event.Reset> { transitionTo(State.Queue) } } state<State.InitialPaused> { onEnter { Log.d("DownloadProgressView", "State.InitialPaused") progressBar.isIndeterminate = false cancelButton.visibility = View.VISIBLE resumePauseButton.visibility = View.VISIBLE resumePauseButton.setReverseAsDefault() downloadProgressNumber.visibility = View.VISIBLE setProgress(currentProgress) downloadState.setText(pausedText) } on<Event.ResumeClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.RESUME, payload)) transitionTo(State.InProgress) } on<Event.CancelClick> { eventListener?.onActionClick( DownloadEventListener.Action(DownloadEventListener.Action.Type.CANCEL, payload)) transitionTo(State.Canceled) } on<Event.Reset> { transitionTo(State.Queue) } } state<State.Installing> { onEnter { Log.d("DownloadProgressView", "State.Installing") progressBar.isIndeterminate = true cancelButton.visibility = View.INVISIBLE resumePauseButton.visibility = View.GONE downloadProgressNumber.visibility = View.GONE downloadState.setText(installingText) } on<Event.Reset> { transitionTo(State.Queue) } } } constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { inflate(context, R.layout.download_progress_view, this) retrievePreferences(attrs, defStyleAttr) } private fun retrievePreferences(attrs: AttributeSet?, defStyleAttr: Int) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.DownloadProgressView, defStyleAttr, 0) setProgressDrawable(typedArray.getDrawable(R.styleable.DownloadProgressView_progressDrawable)) setEnableAnimations( typedArray.getBoolean(R.styleable.DownloadProgressView_enableAnimations, true)) isPausable = typedArray.getBoolean(R.styleable.DownloadProgressView_isPausable, true) downloadingText = typedArray.getString(R.styleable.DownloadProgressView_downloadingText) ?: context.getString( R.string.appview_short_downloading) pausedText = typedArray.getString(R.styleable.DownloadProgressView_pausedText) ?: context.getString( R.string.apps_short_download_paused) installingText = typedArray.getString(R.styleable.DownloadProgressView_installingText) ?: context.getString( R.string.apps_short_installing) typedArray.recycle() } private fun setupClickListeners() { cancelButton.setOnClickListener { debouncer.execute { stateMachine.transition(Event.CancelClick) } } resumePauseButton.setOnClickListener { debouncer.execute { if (isPausable) { if (stateMachine.state == State.InProgress) stateMachine.transition(Event.PauseClick) else stateMachine.transition(Event.ResumeClick) } } } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() cancelButton.setOnClickListener(null) resumePauseButton.setOnClickListener(null) } override fun onAttachedToWindow() { super.onAttachedToWindow() setupClickListeners() } /** * Should only be used if for some reason you can't use [events] directly. */ fun setEventListener(eventListener: DownloadEventListener?) { this.eventListener = eventListener if (eventListener == null) { cancelButton.setOnClickListener(null) resumePauseButton.setOnClickListener(null) } } private fun resetProgress() { currentProgress = 0 progressBar.progress = currentProgress val progressPercent = "$currentProgress%" downloadProgressNumber.text = progressPercent } @VisibleForTesting(otherwise = VisibleForTesting.NONE) internal fun setDebounceTime(time: Long) { debouncer = Debouncer(time) } /** * Sets if animations should be enabled * @param enableAnimations true to enable animations, false to disable animations */ fun setEnableAnimations(enableAnimations: Boolean) { animationsEnabled = enableAnimations resumePauseButton.isAnimationsEnabled = enableAnimations rootLayout.layoutTransition = if (enableAnimations) LayoutTransition() else null } /** * Sets a specific drawable for progress * @param progressDrawable Progress drawable */ fun setProgressDrawable(progressDrawable: Drawable?) { progressDrawable?.let { drawable -> progressBar.progressDrawable = drawable } } /** * Retrieves the events stream for this view. * * @return Observable<DownloadEventListener.Action> */ @CheckResult fun events(): Observable<DownloadEventListener.Action> { return Observable.create(DownloadProgressViewEventOnSubscribe(this)) } /** * Sets an optional payload to be retrieved with the event listener * E.g. Attaching an object identifying/describing the download * * @param payload */ fun setPayload(payload: Any?) { this.payload = payload } /** * Sets the download progress. Note that it clips to 0-100. * If the view is in a paused state, it caches the value and sets it when it's in the resume state. * * @param progress, 0-100 */ fun setProgress(progress: Int) { if (stateMachine.state == State.Queue || stateMachine.state == State.Canceled) return currentProgress = min(max(progress, 0), 100) if (stateMachine.state == State.InProgress || stateMachine.state == State.InitialPaused) { if (Build.VERSION.SDK_INT >= 24) { progressBar.setProgress(currentProgress, animationsEnabled) } else { progressBar.progress = currentProgress } val progressPercent = "$currentProgress%" downloadProgressNumber.text = progressPercent } } /** * Notifies the view that downloading will now begin. * It changes the view to a InProgress state. */ fun startDownload() { stateMachine.transition(Event.DownloadStart) } /** * Notifies the view that the download is paused. * It truly only does something if the download state is initially paused. */ fun pauseDownload() { stateMachine.transition(Event.PauseStart) } /** * Notifies the view that installation will now begin. This implies that the download has ended. * It changes the view to an Canceled state. */ fun startInstallation() { stateMachine.transition(Event.InstallStart) } /** * Notifies the view to reset the view. Use this after installing an app. */ fun reset() { stateMachine.transition(Event.Reset) } }
gpl-3.0
1692ce0309492a4a32e590f02f20ad88
31.123656
101
0.688007
4.739786
false
false
false
false
msebire/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/CompareRevisionsFromLogAction.kt
2
1858
// 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.vcs.log.ui.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.vcs.FilePath import com.intellij.vcs.log.VcsLogDataKeys import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import com.intellij.vcsUtil.VcsUtil open class CompareRevisionsFromLogAction : DumbAwareAction() { protected open fun getFilePath(e: AnActionEvent): FilePath? { val log = e.getData(VcsLogDataKeys.VCS_LOG) ?: return null val selectedCommits = log.selectedCommits if (selectedCommits.isEmpty() || selectedCommits.size > 2) return null if (selectedCommits.first().root != selectedCommits.last().root) return null return VcsUtil.getFilePath(selectedCommits.first().root) } override fun update(e: AnActionEvent) { val log = e.getData(VcsLogDataKeys.VCS_LOG) val handler = e.getData(VcsLogInternalDataKeys.LOG_DIFF_HANDLER) val filePath = getFilePath(e) if (log == null || filePath == null || handler == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = log.selectedCommits.size == 2 } override fun actionPerformed(e: AnActionEvent) { val log = e.getRequiredData(VcsLogDataKeys.VCS_LOG) val handler = e.getRequiredData(VcsLogInternalDataKeys.LOG_DIFF_HANDLER) val filePath = getFilePath(e)!! VcsLogUsageTriggerCollector.triggerUsage(e) val commits = log.selectedCommits if (commits.size == 2) { handler.showDiff(commits[1].root, filePath, commits[1].hash, filePath, commits[0].hash) } } }
apache-2.0
77c69f1de78e59c5de17d4e2ec3de030
38.553191
140
0.749731
4.290993
false
false
false
false
SergeySave/SpaceGame
core/src/com/sergey/spacegame/common/game/command/ServerCommand.kt
1
6613
package com.sergey.spacegame.common.game.command import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.sergey.spacegame.common.game.Level import com.sergey.spacegame.common.lua.LuaPredicate import com.sergey.spacegame.common.lua.LuaUtils import java.io.IOException import java.lang.reflect.Type /** * Represents a Command for the server side * * @author sergeys * * @constructor Creates a new ServerCommand * * @param executable - the command's executable * @param allowMulti - does this command allow multiple targets * @param requiresInput - does this command require an input position * @param requiresTwoInput - does this command require a secondary input position * @param id - the id of this command * @param drawableName - the name of the image to use for drawing the command's icon button * @param req - the requirements of this command to be enabled * @param drawableCheckedName - the name of the image to use for drawing the command's pressed icon button * @param orderTag - the tag to use to determine the order count */ class ServerCommand(executable: CommandExecutable, allowMulti: Boolean, requiresInput: Boolean, requiresTwoInput: Boolean, id: String, drawableName: String, req: Map<String, LuaPredicate>?, drawableCheckedName: String?, orderTag: String?) : Command(executable, allowMulti, requiresInput, requiresTwoInput, id, drawableName, req, drawableCheckedName, orderTag) { class Adapter : JsonSerializer<Command>, JsonDeserializer<Command> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Command { val obj = json.asJsonObject val executable = when (obj["type"].asString) { "lua" -> { val original = obj["lua"].asString val lua = try { LuaUtils.getLUACode(original, Level.deserializingFileSystem()) } catch (e: IOException) { throw JsonParseException(e.message, e) } LuaCommandExecutable(lua, original) } else -> { val className = obj["class"].asString try { val clazz = ClassLoader.getSystemClassLoader().loadClass(className) clazz.newInstance() as CommandExecutable } catch (e: ClassNotFoundException) { throw JsonParseException("Class $className not found. ", e) } catch (e: InstantiationException) { throw JsonParseException("Class $className unable to be instantiated. ", e) } catch (e: IllegalAccessException) { throw JsonParseException("Class $className unable to be instantiated. ", e) } catch (e: ClassCastException) { throw JsonParseException("Class $className does not implement CommandExecutable. ", e) } } } val allowMulti = obj["allowsMulti"]?.asBoolean ?: true val requiresInput = obj["requiresInput"]?.asBoolean ?: false val requiresTwoInput = obj["requiresTwoInput"]?.asBoolean ?: false val id = obj["id"]?.asString ?: throw JsonParseException("Command id not set") // Should never occur as set programmatically val drawableName = obj["iconName"]?.asString ?: throw JsonParseException("Command iconName not set") val drawableCheckedName = obj["pressedIconName"]?.asString //Nullable type val orderTag = if (!allowMulti) obj["orderTag"].asString!! else null //Nullable but cannot be null if allowMulti is false val req = obj["req"]?.asJsonObject?.run { val map = HashMap<String, LuaPredicate>() for (entry in entrySet()) { val original = entry.value.asString val code = try { LuaUtils.getLUACode(original, Level.deserializingFileSystem()) } catch (e: IOException) { throw JsonParseException(e.message, e) } map.put(entry.key, LuaPredicate(original, code)) } map } return ServerCommand(executable, allowMulti, requiresInput, requiresTwoInput, id, drawableName, req, drawableCheckedName, orderTag) } override fun serialize(src: Command, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return JsonObject().apply { if (src.executable is LuaCommandExecutable) { addProperty("type", "lua") addProperty("lua", src.executable.original) } else { addProperty("type", "java") addProperty("class", src.executable::class.java.name) } addProperty("allowsMulti", src.allowMulti) addProperty("requiresInput", src.requiresInput) addProperty("requiresTwoInput", src.requiresTwoInput) addProperty("iconName", src.drawableName) if (src.drawableCheckedName != null) addProperty("pressedIconName", src.drawableCheckedName) if (!src.allowMulti) addProperty("orderTag", src.orderTag) src.req?.let { req -> val reqObj = JsonObject() for (entry in req) { reqObj.addProperty(entry.key, entry.value.original) } add("req", reqObj) } } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ServerCommand) return false return super.equals(other) } //Unfortunately this is required for IntelliJ not to annoy me override fun hashCode(): Int = super.hashCode() * 31 + javaClass.hashCode() }
mit
1fd1925e0831bfc03f2a748cbdc0cb84
47.632353
143
0.581431
5.389568
false
false
false
false
CarrotCodes/Pellet
server/src/main/kotlin/dev/pellet/server/routing/http/HTTPRequestHandler.kt
1
7765
package dev.pellet.server.routing.http import dev.pellet.logging.PelletLogElements import dev.pellet.logging.logElements import dev.pellet.logging.pelletLogger import dev.pellet.server.CloseReason import dev.pellet.server.PelletServerClient import dev.pellet.server.buffer.PelletBufferPooling import dev.pellet.server.codec.CodecHandler import dev.pellet.server.codec.http.ContentTypeParser import dev.pellet.server.codec.http.HTTPEntity import dev.pellet.server.codec.http.HTTPHeader import dev.pellet.server.codec.http.HTTPHeaderConstants import dev.pellet.server.codec.http.HTTPRequestMessage import dev.pellet.server.codec.http.HTTPResponseMessage import dev.pellet.server.codec.http.HTTPStatusLine import dev.pellet.server.codec.http.query.QueryParser import dev.pellet.server.metrics.PelletTimer import dev.pellet.server.responder.http.PelletHTTPResponder import dev.pellet.server.responder.http.PelletHTTPRouteContext import java.time.Instant import java.time.ZoneOffset.UTC import java.time.format.DateTimeFormatterBuilder import java.time.format.TextStyle import java.time.temporal.ChronoField internal class HTTPRequestHandler( private val router: HTTPRouting, private val pool: PelletBufferPooling, private val logRequests: Boolean ) : CodecHandler<HTTPRequestMessage> { private val logger = pelletLogger<HTTPRequestHandler>() companion object { val commonDateFormat = DateTimeFormatterBuilder() .appendValue(ChronoField.DAY_OF_MONTH, 2) .appendLiteral('/') .appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT) .appendLiteral('/') .appendValue(ChronoField.YEAR, 4) .appendLiteral(':') .appendValue(ChronoField.HOUR_OF_DAY, 2) .appendLiteral(':') .appendValue(ChronoField.MINUTE_OF_HOUR, 2) .appendLiteral(':') .appendValue(ChronoField.SECOND_OF_MINUTE, 2) .appendLiteral(' ') .appendOffset("+HHMM", "0000") .toFormatter()!! const val requestMethodKey = "request.method" const val requestUriKey = "request.uri" const val responseCodeKey = "response.code" const val responseDurationKey = "response.duration_ms" } override suspend fun handle( output: HTTPRequestMessage, client: PelletServerClient ) { val timer = PelletTimer() val responder = PelletHTTPResponder(client, pool) val resolvedRoute = router.route(output) if (resolvedRoute == null) { val response = HTTPRouteResponse.Builder() .notFound() .build() respond(output, response, responder, timer, client) } else { val response = handleRoute(resolvedRoute, output, client) respond(output, response, responder, timer, client) } val connectionHeader = output.headers.getSingleOrNull(HTTPHeaderConstants.connection) handleConnectionHeader(connectionHeader, client) output.release(pool) } private suspend fun handleRoute( resolvedRoute: HTTPRouting.ResolvedRoute, rawMessage: HTTPRequestMessage, client: PelletServerClient ): HTTPRouteResponse { val (route, valueMap) = resolvedRoute val query = rawMessage.requestLine.resourceUri.rawQuery ?: "" val queryParameters = QueryParser.parseEncodedQuery(query).getOrElse { return HTTPRouteResponse.Builder() .badRequest() .build() } val entityContext = when (rawMessage.entity) { is HTTPEntity.Content -> { val contentTypeHeader = rawMessage .headers[HTTPHeaderConstants.contentType] ?.rawValue if (contentTypeHeader == null) { logger.debug { "got an entity but didn't receive a content type" } return HTTPRouteResponse.Builder() .badRequest() .build() } val contentType = ContentTypeParser.parse(contentTypeHeader).getOrElse { logger.debug { "received a malformed content type" } return HTTPRouteResponse.Builder() .badRequest() .build() } PelletHTTPRouteContext.EntityContext( rawEntity = rawMessage.entity, contentType = contentType ) } else -> null } val context = PelletHTTPRouteContext(rawMessage, entityContext, client, valueMap, queryParameters) val routeResult = runCatching { route.handler.handle(context) } return routeResult.getOrElse { logger.error(routeResult.exceptionOrNull()) { "failed to handle request" } HTTPRouteResponse.Builder() .internalServerError() .build() } } private suspend fun respond( request: HTTPRequestMessage, response: HTTPRouteResponse, responder: PelletHTTPResponder, timer: PelletTimer, client: PelletServerClient ) { val message = mapRouteResponseToMessage(response) val requestDuration = timer.markAndReset() if (logRequests) { val elements = logElements { add(requestMethodKey, request.requestLine.method.toString()) add(requestUriKey, request.requestLine.resourceUri.toString()) add(responseCodeKey, message.statusLine.statusCode) add(responseDurationKey, requestDuration.toMillis()) } logResponse(request, response, client, elements) } responder.respond(message) } private fun logResponse( request: HTTPRequestMessage, response: HTTPRouteResponse, client: PelletServerClient, elements: () -> PelletLogElements ) { val dateTime = commonDateFormat.format(Instant.now().atZone(UTC)) val (method, uri, version) = request.requestLine val responseSize = response.entity.sizeBytes logger.info(elements) { "${client.remoteHostString} - - [$dateTime] \"$method $uri $version\" ${response.statusCode} $responseSize" } } private fun handleConnectionHeader( connectionHeader: HTTPHeader?, client: PelletServerClient ) { if (connectionHeader == null) { // keep alive by default return } if (connectionHeader.rawValue.equals(HTTPHeaderConstants.keepAlive, ignoreCase = true)) { return } if (connectionHeader.rawValue.equals(HTTPHeaderConstants.close, ignoreCase = true)) { client.close(CloseReason.ServerInitiated) } } private fun mapRouteResponseToMessage( routeResult: HTTPRouteResponse ): HTTPResponseMessage { val effectiveStatusCode = when (routeResult.statusCode) { 0 -> 200 else -> routeResult.statusCode } return HTTPResponseMessage( statusLine = HTTPStatusLine( version = "HTTP/1.1", statusCode = effectiveStatusCode, reasonPhrase = mapCodeToReasonPhrase(effectiveStatusCode) ), headers = routeResult.headers, entity = routeResult.entity ) } private fun mapCodeToReasonPhrase(code: Int) = when (code) { 200 -> "OK" 204 -> "No Content" 400 -> "Bad Request" 404 -> "Not Found" 500 -> "Internal Server Error" else -> "Unknown" } }
apache-2.0
038d5bb1b7848370a97e18a7ffb82f42
36.694175
141
0.628976
4.850094
false
false
false
false
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/paynym/PayNymViewModel.kt
1
10791
package com.samourai.wallet.paynym import android.app.Application import android.util.Log import androidx.lifecycle.* import com.google.gson.Gson import com.samourai.wallet.access.AccessFactory import com.samourai.wallet.bip47.BIP47Meta import com.samourai.wallet.bip47.BIP47Util import com.samourai.wallet.bip47.paynym.WebUtil import com.samourai.wallet.payload.PayloadUtil import com.samourai.wallet.paynym.api.PayNymApiService import com.samourai.wallet.paynym.models.NymResponse import com.samourai.wallet.util.* import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.* import okhttp3.Response import org.bitcoinj.core.AddressFormatException import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.* import kotlin.collections.ArrayList class PayNymViewModel(application: Application) : AndroidViewModel(application) { private var paymentCode = MutableLiveData<String>() private var errors = MutableLiveData<String>() private var loader = MutableLiveData(false) private var refreshTaskProgress = MutableLiveData(Pair(0, 0)) private var followersList = MutableLiveData<ArrayList<String>>() private var followingList = MutableLiveData<ArrayList<String>>() private var refreshJob: Job = Job() private val TAG = "PayNymHomeViewModel" val followers: LiveData<ArrayList<String>> get() = followersList val errorsLiveData: LiveData<String> get() = errors val pcode: LiveData<String> get() = paymentCode val following: LiveData<ArrayList<String>> get() = followingList val loaderLiveData: LiveData<Boolean> get() = loader val refreshTaskProgressLiveData: LiveData<Pair<Int, Int>> get() = refreshTaskProgress private suspend fun setPaynymPayload(jsonObject: JSONObject) = withContext(Dispatchers.IO) { var array = JSONArray() try { val nym = Gson().fromJson(jsonObject.toString(), NymResponse::class.java); array = jsonObject.getJSONArray("codes") if (array.getJSONObject(0).has("claimed") && array.getJSONObject(0).getBoolean("claimed")) { val strNymName = jsonObject.getString("nymName") viewModelScope.launch(Dispatchers.Main) { paymentCode.postValue(strNymName) } } nym.following?.let { codes -> codes.forEach { paynym -> BIP47Meta.getInstance().setSegwit(paynym.code, paynym.segwit) if (BIP47Meta.getInstance().getDisplayLabel(paynym.code).contains(paynym.code.substring(0, 4))) { BIP47Meta.getInstance().setLabel(paynym.code, paynym.nymName) } } val followings = ArrayList(codes.distinctBy { it.code }.map { it.code }) BIP47Meta.getInstance().addFollowings(followings) sortByLabel(followings); viewModelScope.launch(Dispatchers.Main) { followingList.postValue(followings) } } nym.followers?.let { codes -> codes.forEach { paynym -> BIP47Meta.getInstance().setSegwit(paynym.code, paynym.segwit) if (BIP47Meta.getInstance().getDisplayLabel(paynym.code).contains(paynym.code.substring(0, 4))) { BIP47Meta.getInstance().setLabel(paynym.code, paynym.nymName) } } val followers = ArrayList(codes.distinctBy { it.code }.map { it.code }) sortByLabel(followers); viewModelScope.launch(Dispatchers.Main) { followersList.postValue(followers) } } PayloadUtil.getInstance(getApplication()).serializePayNyms(jsonObject); } catch (e: JSONException) { e.printStackTrace() } } private fun sortByLabel(list: ArrayList<String>) { list.sortWith { pcode1: String?, pcode2: String? -> var res = java.lang.String.CASE_INSENSITIVE_ORDER.compare(BIP47Meta.getInstance().getDisplayLabel(pcode1), BIP47Meta.getInstance().getDisplayLabel(pcode2)) if (res == 0) { res = BIP47Meta.getInstance().getDisplayLabel(pcode1).compareTo(BIP47Meta.getInstance().getDisplayLabel(pcode2)) } res } } private suspend fun getPayNymData() { val strPaymentCode = BIP47Util.getInstance(getApplication()).paymentCode.toString() val apiService = PayNymApiService.getInstance(strPaymentCode, getApplication()) try { val response = apiService.getNymInfo() withContext(Dispatchers.Main) { loader.postValue(false) } if (response.isSuccessful) { val responseJson = response.body?.string() if (responseJson != null) setPaynymPayload(JSONObject(responseJson)) else throw Exception("Invalid response ") } } catch (ex: Exception) { LogUtil.error(TAG, ex) } } fun refreshPayNym() { if (refreshJob.isActive) { refreshJob.cancel("") } refreshJob = viewModelScope.launch(Dispatchers.Main) { loader.postValue(true) withContext(Dispatchers.IO) { try { getPayNymData() } catch (error: Exception) { error.printStackTrace() throw CancellationException(error.message) } } } refreshJob.invokeOnCompletion { viewModelScope.launch(Dispatchers.Main) { loader.postValue(false) } } } fun doSyncAll(silentSync: Boolean = false) { val strPaymentCode = BIP47Util.getInstance(getApplication()).paymentCode.toString() val apiService = PayNymApiService.getInstance(strPaymentCode, getApplication()) val _pcodes = BIP47Meta.getInstance().getSortedByLabels(false) if (_pcodes.size == 0) { return } refreshJob = viewModelScope.launch(Dispatchers.IO) { try { if (_pcodes.contains(BIP47Util.getInstance(getApplication()).paymentCode.toString())) { _pcodes.remove(BIP47Util.getInstance(getApplication()).paymentCode.toString()) BIP47Meta.getInstance().remove(BIP47Util.getInstance(getApplication()).paymentCode.toString()) } } catch (afe: AddressFormatException) { afe.printStackTrace() } var progress = 0; val jobs = arrayListOf<Deferred<Unit>>() if (!silentSync) refreshTaskProgress.postValue(Pair(0, _pcodes.size)) _pcodes.forEachIndexed { _, pcode -> val job = async(Dispatchers.IO) { apiService.syncPcode(pcode) } jobs.add(job) job.invokeOnCompletion { if (it == null) { progress++ if (!silentSync) refreshTaskProgress.postValue(Pair(progress, _pcodes.size)) } else { it.printStackTrace() } } } jobs.awaitAll() } } fun init() { paymentCode.postValue("") //Load offline viewModelScope.launch { withContext(Dispatchers.IO) { try { val res = PayloadUtil.getInstance(getApplication()).deserializePayNyms().toString() setPaynymPayload(JSONObject(res)) } catch (ex: Exception) { throw CancellationException(ex.message) } } } } public fun doFollow(pcode: String) { viewModelScope.launch { withContext(Dispatchers.Main) { loader.postValue(true) } withContext(Dispatchers.IO) { try { val strPaymentCode = BIP47Util.getInstance(getApplication()).paymentCode.toString() val apiService = PayNymApiService.getInstance(strPaymentCode, getApplication()) apiService.follow(pcode) BIP47Meta.getInstance().isRequiredRefresh = true PayloadUtil.getInstance(getApplication()).saveWalletToJSON(CharSequenceX(AccessFactory.getInstance(getApplication()).guid + AccessFactory.getInstance(getApplication()).pin)) //Refresh getPayNymData() } catch (ex: Exception) { throw CancellationException(ex.message) } } }.invokeOnCompletion { viewModelScope.launch(Dispatchers.Main) { loader.postValue(false) } if (it != null) { errors.postValue(it.message) } } } public fun doUnFollow(pcode: String): Job { val job = viewModelScope.launch { withContext(Dispatchers.Main) { loader.postValue(true) } withContext(Dispatchers.IO) { try { val strPaymentCode = BIP47Util.getInstance(getApplication()).paymentCode.toString() val apiService = PayNymApiService.getInstance(strPaymentCode, getApplication()) apiService.unfollow(pcode) BIP47Meta.getInstance().remove(pcode) BIP47Meta.getInstance().isRequiredRefresh = true //Refresh PayloadUtil.getInstance(getApplication()).saveWalletToJSON(CharSequenceX(AccessFactory.getInstance(getApplication()).guid + AccessFactory.getInstance(getApplication()).pin)) getPayNymData() } catch (ex: Exception) { throw CancellationException(ex.message) } } } job.invokeOnCompletion { viewModelScope.launch(Dispatchers.Main) { loader.postValue(false) } if (it != null) { errors.postValue(it.message) } } return job } init { if (PrefsUtil.getInstance(getApplication()).getValue(PrefsUtil.PAYNYM_CLAIMED, false)) { init() } } }
unlicense
adfd700c976eab2dc88ff03908665fee
37.960289
193
0.580669
4.943197
false
false
false
false
sabi0/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/ex/PartialLocalLineStatusTracker.kt
1
28541
/* * 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.openapi.vcs.ex import com.intellij.diff.util.Side import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Separator import com.intellij.openapi.application.runReadAction import com.intellij.openapi.command.CommandEvent import com.intellij.openapi.command.CommandListener import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.undo.BasicUndoableAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ChangeListManagerImpl import com.intellij.openapi.vcs.changes.ChangeListWorker import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.openapi.vcs.ex.DocumentTracker.Block import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker.LocalRange import com.intellij.openapi.vcs.impl.LineStatusTrackerManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.labels.ActionGroupLink import com.intellij.util.EventDispatcher import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.WeakList import com.intellij.util.ui.JBUI import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.CalledInAwt import java.awt.BorderLayout import java.awt.Point import java.lang.ref.WeakReference import java.util.* import javax.swing.JComponent import javax.swing.JPanel import kotlin.collections.HashSet class PartialLocalLineStatusTracker(project: Project, document: Document, virtualFile: VirtualFile, mode: Mode ) : LineStatusTracker<LocalRange>(project, document, virtualFile, mode), ChangeListWorker.PartialChangeTracker { private val changeListManager = ChangeListManagerImpl.getInstanceImpl(project) private val lstManager = LineStatusTrackerManager.getInstance(project) as LineStatusTrackerManager private val undoManager = UndoManager.getInstance(project) private val undoStateRecordingEnabled = Registry.`is`("vcs.enable.partial.changelists.undo") private val redoStateRecordingEnabled = Registry.`is`("vcs.enable.partial.changelists.redo") override val renderer: MyLineStatusMarkerRenderer = MyLineStatusMarkerRenderer(this) private var defaultMarker: ChangeListMarker private var currentMarker: ChangeListMarker? = null private var initialChangeListId: String? = null private var lastKnownTrackerChangeListId: String? = null private val affectedChangeLists = HashSet<String>() private var hasUndoInCommand: Boolean = false private var shouldInitializeWithExcludedFromCommit: Boolean = false private val undoableActions: WeakList<MyUndoableAction> = WeakList() init { defaultMarker = ChangeListMarker(changeListManager.defaultChangeList) affectedChangeLists.add(defaultMarker.changelistId) if (undoStateRecordingEnabled) { document.addDocumentListener(MyUndoDocumentListener(), disposable) CommandProcessor.getInstance().addCommandListener(MyUndoCommandListener(), disposable) Disposer.register(disposable, Disposable { dropExistingUndoActions() }) } assert(blocks.isEmpty()) } override fun Block.toRange(): LocalRange = LocalRange(this.start, this.end, this.vcsStart, this.vcsEnd, this.innerRanges, this.marker.changelistId, this.excludedFromCommit) override fun createDocumentTrackerHandler(): DocumentTracker.Handler = PartialDocumentTrackerHandler() override fun getAffectedChangeListsIds(): List<String> { return documentTracker.readLock { assert(!affectedChangeLists.isEmpty()) affectedChangeLists.toList() } } private fun updateAffectedChangeLists(notifyChangeListManager: Boolean = true) { val oldIds = HashSet<String>() val newIds = HashSet<String>() for (block in blocks) { newIds.add(block.marker.changelistId) } if (!isInitialized) initialChangeListId?.let { newIds.add(it) } if (newIds.isEmpty()) { val listId = lastKnownTrackerChangeListId ?: defaultMarker.changelistId newIds.add(listId) } if (newIds.size == 1) { lastKnownTrackerChangeListId = newIds.single() } oldIds.addAll(affectedChangeLists) affectedChangeLists.clear() affectedChangeLists.addAll(newIds) if (oldIds != newIds) { if (notifyChangeListManager) { // It's OK to call this under documentTracker.writeLock, as this method will not grab CLM lock. changeListManager.notifyChangelistsChanged(VcsUtil.getFilePath(virtualFile), oldIds.toList(), newIds.toList()) } eventDispatcher.multicaster.onChangeListsChange(this) } eventDispatcher.multicaster.onChangeListMarkerChange(this) } @CalledInAwt override fun setBaseRevision(vcsContent: CharSequence) { val changelistId = if (!isInitialized) initialChangeListId else null initialChangeListId = null setBaseRevision(vcsContent) { if (changelistId != null) { changeListManager.executeUnderDataLock { if (changeListManager.getChangeList(changelistId) != null) { documentTracker.writeLock { currentMarker = ChangeListMarker(changelistId) documentTracker.updateFrozenContentIfNeeded() currentMarker = null } } } } } documentTracker.writeLock { updateAffectedChangeLists() } dropExistingUndoActions() if (isValid()) eventDispatcher.multicaster.onBecomingValid(this) } @CalledInAwt fun replayChangesFromDocumentEvents(events: List<DocumentEvent>) { if (events.isEmpty() || !blocks.isEmpty()) return updateDocument(Side.LEFT) { vcsDocument -> for (event in events.reversed()) { vcsDocument.replaceString(event.offset, event.offset + event.newLength, event.oldFragment) } } } override fun initChangeTracking(defaultId: String, changelistsIds: List<String>, fileChangelistId: String?) { documentTracker.writeLock { defaultMarker = ChangeListMarker(defaultId) if (!isInitialized) initialChangeListId = fileChangelistId lastKnownTrackerChangeListId = fileChangelistId val idsSet = changelistsIds.toSet() moveMarkers({ !idsSet.contains(it.marker.changelistId) }, defaultMarker) // no need to notify CLM, as we're inside it's action updateAffectedChangeLists(false) } } override fun defaultListChanged(oldListId: String, newListId: String) { documentTracker.writeLock { defaultMarker = ChangeListMarker(newListId) } } override fun changeListRemoved(listId: String) { documentTracker.writeLock { if (!affectedChangeLists.contains(listId)) return@writeLock if (!isInitialized && initialChangeListId == listId) initialChangeListId = null if (lastKnownTrackerChangeListId == listId) lastKnownTrackerChangeListId = null moveMarkers({ it.marker.changelistId == listId }, defaultMarker) updateAffectedChangeLists(false) } } override fun moveChanges(fromListId: String, toListId: String) { documentTracker.writeLock { if (!affectedChangeLists.contains(fromListId)) return@writeLock if (!isInitialized && initialChangeListId == fromListId) initialChangeListId = toListId if (lastKnownTrackerChangeListId == fromListId) lastKnownTrackerChangeListId = toListId moveMarkers({ it.marker.changelistId == fromListId }, ChangeListMarker(toListId)) updateAffectedChangeLists(false) } } override fun moveChangesTo(toListId: String) { documentTracker.writeLock { if (!isInitialized) initialChangeListId = toListId lastKnownTrackerChangeListId = toListId moveMarkers({ true }, ChangeListMarker(toListId)) updateAffectedChangeLists(false) } } private fun moveMarkers(condition: (Block) -> Boolean, toMarker: ChangeListMarker) { val affectedBlocks = mutableListOf<Block>() for (block in blocks) { if (block.marker != toMarker && condition(block)) { block.marker = toMarker affectedBlocks.add(block) } } if (!affectedBlocks.isEmpty()) { dropExistingUndoActions() updateHighlighters() } } private inner class MyUndoDocumentListener : DocumentListener { override fun beforeDocumentChange(event: DocumentEvent?) { if (hasUndoInCommand) return if (undoManager.isRedoInProgress || undoManager.isUndoInProgress) return hasUndoInCommand = true registerUndoAction(true) } } private inner class MyUndoCommandListener : CommandListener { override fun commandStarted(event: CommandEvent?) { if (!CommandProcessor.getInstance().isUndoTransparentActionInProgress) { hasUndoInCommand = false } } override fun commandFinished(event: CommandEvent?) { if (!CommandProcessor.getInstance().isUndoTransparentActionInProgress) { hasUndoInCommand = false } } override fun undoTransparentActionStarted() { if (CommandProcessor.getInstance().currentCommand == null) { hasUndoInCommand = false } } override fun undoTransparentActionFinished() { if (CommandProcessor.getInstance().currentCommand == null) { hasUndoInCommand = false } } override fun beforeCommandFinished(event: CommandEvent?) { registerRedoAction() } override fun beforeUndoTransparentActionFinished() { registerRedoAction() } private fun registerRedoAction() { if (hasUndoInCommand && redoStateRecordingEnabled) { registerUndoAction(false) } } } private fun dropExistingUndoActions() { val actions = undoableActions.copyAndClear() for (action in actions) { action.drop() } } @CalledInAwt private fun registerUndoAction(undo: Boolean) { val undoState = collectRangeStates() val action = MyUndoableAction(project, document, undoState, undo) undoManager.undoableActionPerformed(action) undoableActions.add(action) } private inner class PartialDocumentTrackerHandler : LineStatusTrackerBase<LocalRange>.MyDocumentTrackerHandler() { override fun onRangeAdded(block: Block) { super.onRangeAdded(block) if (block.ourData.marker == null) { // do not override markers, that are set via other methods of this listener block.marker = defaultMarker } } override fun onRangeRefreshed(before: Block, after: List<Block>) { super.onRangeRefreshed(before, after) val isExcludedFromCommit = before.excludedFromCommit val marker = before.marker for (block in after) { block.excludedFromCommit = isExcludedFromCommit block.marker = marker } } override fun onRangesChanged(before: List<Block>, after: Block) { super.onRangesChanged(before, after) after.excludedFromCommit = mergeExcludedFromCommitRanges(before) val affectedMarkers = before.map { it.marker }.distinct() val _currentMarker = currentMarker if (affectedMarkers.isEmpty() && _currentMarker != null) { after.marker = _currentMarker } else if (affectedMarkers.size == 1) { after.marker = affectedMarkers.single() } else { if (!affectedMarkers.isEmpty()) { lstManager.notifyInactiveRangesDamaged(virtualFile) } after.marker = defaultMarker } } override fun onRangeShifted(before: Block, after: Block) { super.onRangeShifted(before, after) after.excludedFromCommit = before.excludedFromCommit after.marker = before.marker } override fun onRangesMerged(range1: Block, range2: Block, merged: Block): Boolean { val superMergeable = super.onRangesMerged(range1, range2, merged) merged.excludedFromCommit = mergeExcludedFromCommitRanges(listOf(range1, range2)) if (range1.marker == range2.marker) { merged.marker = range1.marker return superMergeable } if (range1.range.isEmpty || range2.range.isEmpty) { if (range1.range.isEmpty && range2.range.isEmpty) { merged.marker = defaultMarker } else if (range1.range.isEmpty) { merged.marker = range2.marker } else { merged.marker = range1.marker } return superMergeable } return false } override fun afterRefresh() { super.afterRefresh() updateAffectedChangeLists() fireExcludedFromCommitChanged() } override fun afterRangeChange() { super.afterRangeChange() updateAffectedChangeLists() fireExcludedFromCommitChanged() } override fun afterExplicitChange() { super.afterExplicitChange() updateAffectedChangeLists() fireExcludedFromCommitChanged() } override fun onUnfreeze() { super.onUnfreeze() if (shouldInitializeWithExcludedFromCommit) { shouldInitializeWithExcludedFromCommit = false for (block in blocks) { block.excludedFromCommit = true } } if (isValid()) eventDispatcher.multicaster.onBecomingValid(this@PartialLocalLineStatusTracker) } private fun mergeExcludedFromCommitRanges(ranges: List<DocumentTracker.Block>): Boolean { if (ranges.isEmpty()) return false return ranges.all { it.excludedFromCommit } } } fun hasPartialChangesToCommit(): Boolean { return documentTracker.readLock { affectedChangeLists.size > 1 || hasBlocksExcludedFromCommit() } } fun getPartiallyAppliedContent(side: Side, changelistIds: List<String>): String { return runReadAction { val markers = changelistIds.mapTo(HashSet()) { ChangeListMarker(it) } val toCommitCondition: (Block) -> Boolean = { markers.contains(it.marker) && !it.excludedFromCommit } documentTracker.getContentWithPartiallyAppliedBlocks(side, toCommitCondition) } } @CalledInAwt fun handlePartialCommit(side: Side, changelistIds: List<String>): PartialCommitHelper { val markers = changelistIds.mapTo(HashSet()) { ChangeListMarker(it) } val toCommitCondition: (Block) -> Boolean = { markers.contains(it.marker) && !it.excludedFromCommit } val contentToCommit = documentTracker.getContentWithPartiallyAppliedBlocks(side, toCommitCondition) return object : PartialCommitHelper(contentToCommit) { override fun applyChanges() { if (isReleased) return val success = updateDocument(side) { doc -> documentTracker.doFrozen(side) { documentTracker.partiallyApplyBlocks(side, toCommitCondition, { _, _ -> }) doc.setText(contentToCommit) } } if (!success) { LOG.warn("Can't update document state on partial commit: $virtualFile") } } } } abstract class PartialCommitHelper(val content: String) { @CalledInAwt abstract fun applyChanges() } @CalledInAwt fun rollbackChangelistChanges(changelistsIds: List<String>, rollbackRangesExcludedFromCommit: Boolean) { val idsSet = changelistsIds.toSet() runBulkRollback { idsSet.contains(it.marker.changelistId) && (rollbackRangesExcludedFromCommit || !it.excludedFromCommit) } } protected class MyLineStatusMarkerRenderer(override val tracker: PartialLocalLineStatusTracker) : LineStatusTracker.LocalLineStatusMarkerRenderer(tracker) { override fun createMerger(editor: Editor): VisibleRangeMerger { return object : VisibleRangeMerger(editor) { override fun isIgnored(range: Range): Boolean { return range is LocalRange && range.changelistId != tracker.defaultMarker.changelistId } } } override fun createAdditionalInfoPanel(editor: Editor, range: Range, mousePosition: Point?, disposable: Disposable): JComponent? { if (range !is LocalRange) return null val changeLists = ChangeListManager.getInstance(tracker.project).changeLists val rangeList = changeLists.find { it.id == range.changelistId } ?: return null val group = DefaultActionGroup() if (changeLists.size > 1) { group.add(Separator("Changelists")) for (changeList in changeLists) { group.add(MoveToChangeListAction(editor, range, mousePosition, changeList)) } group.add(Separator.getInstance()) } group.add(MoveToAnotherChangeListAction(editor, range, mousePosition)) val link = ActionGroupLink(rangeList.name, null, group) val moveChangesShortcutSet = ActionManager.getInstance().getAction("Vcs.MoveChangedLinesToChangelist").shortcutSet object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { link.linkLabel.doClick() } }.registerCustomShortcutSet(moveChangesShortcutSet, editor.component, disposable) val shortcuts = moveChangesShortcutSet.shortcuts if (shortcuts.isNotEmpty()) { link.linkLabel.toolTipText = "Move lines to another changelist (${KeymapUtil.getShortcutText(shortcuts.first())})" } val panel = JPanel(BorderLayout()) panel.add(link, BorderLayout.CENTER) panel.border = JBUI.Borders.emptyLeft(7) panel.isOpaque = false return panel } private inner class MoveToAnotherChangeListAction(editor: Editor, range: Range, val mousePosition: Point?) : RangeMarkerAction(editor, range, null) { init { templatePresentation.text = "New Changelist..." } override fun isEnabled(editor: Editor, range: Range): Boolean = range is LocalRange override fun actionPerformed(editor: Editor, range: Range) { MoveChangesLineStatusAction.moveToAnotherChangelist(tracker, range as LocalRange) reopenRange(editor, range, mousePosition) } } private inner class MoveToChangeListAction(editor: Editor, range: Range, val mousePosition: Point?, val changelist: LocalChangeList) : RangeMarkerAction(editor, range, null) { init { templatePresentation.text = StringUtil.trimMiddle(changelist.name, 60) } override fun isEnabled(editor: Editor, range: Range): Boolean = range is LocalRange override fun actionPerformed(editor: Editor, range: Range) { tracker.moveToChangelist(range, changelist) reopenRange(editor, range, mousePosition) } } private fun reopenRange(editor: Editor, range: Range, mousePosition: Point?) { val newRange = tracker.findRange(range) if (newRange != null) tracker.renderer.showHintAt(editor, newRange, mousePosition) } } @CalledInAwt fun moveToChangelist(range: Range, changelist: LocalChangeList) { val newRange = findBlock(range) if (newRange != null) { moveToChangelist({ it == newRange }, changelist) } } @CalledInAwt fun moveToChangelist(lines: BitSet, changelist: LocalChangeList) { moveToChangelist({ it.isSelectedByLine(lines) }, changelist) } @CalledInAwt private fun moveToChangelist(condition: (Block) -> Boolean, changelist: LocalChangeList) { changeListManager.executeUnderDataLock { if (changeListManager.getChangeList(changelist.id) == null) return@executeUnderDataLock val newMarker = ChangeListMarker(changelist) documentTracker.writeLock { moveMarkers(condition, newMarker) updateAffectedChangeLists() } } } enum class ExclusionState { ALL_INCLUDED, ALL_EXCLUDED, PARTIALLY, NO_CHANGES } fun hasBlocksExcludedFromCommit(): Boolean { return documentTracker.readLock { blocks.any { it.excludedFromCommit } } } fun getExcludedFromCommitState(changelistId: String): ExclusionState { val marker = ChangeListMarker(changelistId) var hasIncluded = false var hasExcluded = false documentTracker.readLock { for (block in blocks) { if (block.marker == marker) { if (block.excludedFromCommit) { hasExcluded = true } else { hasIncluded = true } } } } if (!hasExcluded && !hasIncluded) return ExclusionState.NO_CHANGES if (hasExcluded && hasIncluded) return ExclusionState.PARTIALLY if (hasExcluded) return ExclusionState.ALL_EXCLUDED return ExclusionState.ALL_INCLUDED // no changes - all included } @CalledInAwt fun setExcludedFromCommit(isExcluded: Boolean) { setExcludedFromCommit({ true }, isExcluded) if (!isOperational() || !isExcluded) shouldInitializeWithExcludedFromCommit = isExcluded } fun setExcludedFromCommit(range: Range, isExcluded: Boolean) { val newRange = findBlock(range) setExcludedFromCommit({ it == newRange }, isExcluded) } fun setExcludedFromCommit(lines: BitSet, isExcluded: Boolean) { setExcludedFromCommit({ it.isSelectedByLine(lines) }, isExcluded) } private fun setExcludedFromCommit(condition: (Block) -> Boolean, isExcluded: Boolean) { documentTracker.writeLock { for (block in blocks) { if (condition(block)) { block.excludedFromCommit = isExcluded } } } fireExcludedFromCommitChanged() } private fun fireExcludedFromCommitChanged() { eventDispatcher.multicaster.onExcludedFromCommitChange(this) } @CalledInAwt internal fun storeTrackerState(): FullState { return documentTracker.readLock { val vcsContent = documentTracker.getContent(Side.LEFT) val currentContent = documentTracker.getContent(Side.RIGHT) val rangeStates = collectRangeStates() FullState(virtualFile, rangeStates, vcsContent.toString(), currentContent.toString()) } } @CalledInAwt internal fun restoreState(state: State): Boolean { if (state is FullState) { return restoreFullState(state) } else { return restoreState(state.ranges) } } @CalledInAwt private fun collectRangeStates(): List<RangeState> { return documentTracker.readLock { blocks.map { RangeState(it.range, it.marker.changelistId) } } } private fun restoreFullState(state: FullState): Boolean { var success = false documentTracker.doFrozen { // ensure that changelist can't disappear in the middle of operation changeListManager.executeUnderDataLock { documentTracker.writeLock { success = documentTracker.setFrozenState(state.vcsContent, state.currentContent, state.ranges.map { it.range }) if (success) { restoreChangelistsState(state.ranges) } } } if (success) { updateDocument(Side.LEFT) { vcsDocument.setText(state.vcsContent) } } } return success } @CalledInAwt private fun restoreState(states: List<RangeState>): Boolean { var success = false documentTracker.doFrozen { // ensure that changelist can't disappear in the middle of operation changeListManager.executeUnderDataLock { documentTracker.writeLock { success = documentTracker.setFrozenState(states.map { it.range }) if (success) { restoreChangelistsState(states) } } } } return success } private fun restoreChangelistsState(states: List<RangeState>) { val changelistIds = changeListManager.changeLists.map { it.id } val idToMarker = ContainerUtil.newMapFromKeys(changelistIds.iterator(), { ChangeListMarker(it) }) assert(blocks.size == states.size) blocks.forEachIndexed { i, block -> block.marker = idToMarker[states[i].changelistId] ?: defaultMarker } updateAffectedChangeLists() updateHighlighters() } private class MyUndoableAction( project: Project, document: Document, var states: List<RangeState>?, val undo: Boolean ) : BasicUndoableAction(document) { val projectRef: WeakReference<Project> = WeakReference(project) fun drop() { states = null } override fun undo() { if (undo) restore() } override fun redo() { if (!undo) restore() } private fun restore() { val document = affectedDocuments!!.single().document val project = projectRef.get() val rangeStates = states if (document != null && project != null && rangeStates != null) { val tracker = LineStatusTrackerManager.getInstance(project).getLineStatusTracker(document) if (tracker is PartialLocalLineStatusTracker) { tracker.restoreState(rangeStates) } } } } private val eventDispatcher = EventDispatcher.create(Listener::class.java) fun addListener(listener: Listener, disposable: Disposable) { eventDispatcher.addListener(listener, disposable) } open class ListenerAdapter : Listener interface Listener : EventListener { @CalledInAwt fun onBecomingValid(tracker: PartialLocalLineStatusTracker) { } fun onChangeListsChange(tracker: PartialLocalLineStatusTracker) { } fun onChangeListMarkerChange(tracker: PartialLocalLineStatusTracker) { } fun onExcludedFromCommitChange(tracker: PartialLocalLineStatusTracker) { } } internal class FullState(virtualFile: VirtualFile, ranges: List<RangeState>, val vcsContent: String, val currentContent: String) : State(virtualFile, ranges) internal open class State( val virtualFile: VirtualFile, val ranges: List<RangeState> ) internal class RangeState( val range: com.intellij.diff.util.Range, val changelistId: String ) class LocalRange(line1: Int, line2: Int, vcsLine1: Int, vcsLine2: Int, innerRanges: List<InnerRange>?, val changelistId: String, val isExcludedFromCommit: Boolean) : Range(line1, line2, vcsLine1, vcsLine2, innerRanges) protected data class ChangeListMarker(val changelistId: String) { constructor(changelist: LocalChangeList) : this(changelist.id) } protected data class MyBlockData(var marker: ChangeListMarker? = null, var excludedFromCommit: Boolean = false ) : LineStatusTrackerBase.BlockData() override fun createBlockData(): BlockData = MyBlockData() override val Block.ourData: MyBlockData get() = getBlockData(this) as MyBlockData private var Block.marker: ChangeListMarker get() = this.ourData.marker!! // can be null in MyLineTrackerListener, until `onBlockAdded` is called set(value) { this.ourData.marker = value } private var Block.excludedFromCommit: Boolean get() = this.ourData.excludedFromCommit set(value) { this.ourData.excludedFromCommit = value } companion object { @JvmStatic fun createTracker(project: Project, document: Document, virtualFile: VirtualFile, mode: Mode): PartialLocalLineStatusTracker { return PartialLocalLineStatusTracker(project, document, virtualFile, mode) } } }
apache-2.0
e8c4d6c9e8846e6a736a7f05fab8bfff
31.618286
136
0.701237
4.80893
false
false
false
false
googleapis/gapic-generator-kotlin
generator/src/test/kotlin/com/google/api/kotlin/util/ProtoFieldInfoTest.kt
1
16360
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin.util import com.google.api.kotlin.BaseClientGeneratorTest import com.google.api.kotlin.GeneratorContext import com.google.api.kotlin.config.PropertyPath import com.google.api.kotlin.config.ProtobufTypeMapper import com.google.common.truth.Truth.assertThat import com.google.protobuf.ByteString import com.google.protobuf.DescriptorProtos import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName import kotlin.test.Test internal class ProtoFieldInfoTest : BaseClientGeneratorTest("test", "TestServiceClient") { @Test fun `can find service level comments`() { val service = services.find { it.name == "TestService" }!! val method = service.methodList.find { it.name == "Test" }!! val comments = proto.getMethodComments(service, method) assertThat(comments?.trim()).isEqualTo("This is the test method") } @Test fun `can find parameter comments`() { val message = proto.messageTypeList.find { it.name == "TestRequest" }!! val field = message.fieldList.find { it.name == "query" }!! val kotlinType = ClassName("a", "Foo") val fieldInfo = ProtoFieldInfo(proto, message, field, -1, kotlinType) val comment = fieldInfo.file.getParameterComments(fieldInfo) assertThat(comment?.trim()).isEqualTo("the query") } @Test fun `can identity ints and longs`() { listOf( DescriptorProtos.FieldDescriptorProto.Type.TYPE_INT32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_UINT32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_FIXED32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SFIXED32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SINT32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_INT64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_UINT64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_FIXED64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SFIXED64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SINT64 ).forEach { type -> val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(type) .build() assertThat(proto.isIntOrLong()).isTrue() } listOf( DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE, DescriptorProtos.FieldDescriptorProto.Type.TYPE_FLOAT, DescriptorProtos.FieldDescriptorProto.Type.TYPE_BOOL, DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING, DescriptorProtos.FieldDescriptorProto.Type.TYPE_BYTES, DescriptorProtos.FieldDescriptorProto.Type.TYPE_DOUBLE, DescriptorProtos.FieldDescriptorProto.Type.TYPE_ENUM, DescriptorProtos.FieldDescriptorProto.Type.TYPE_GROUP ).forEach { type -> val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(type) .build() assertThat(proto.isIntOrLong()).isFalse() } } @Test fun `can identify a String`() { val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING) .build() assertThat(proto.asClassName(mock())).isEqualTo(String::class.asTypeName()) } @Test fun `can identify a Boolean`() { val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_BOOL) .build() assertThat(proto.asClassName(mock())).isEqualTo(Boolean::class.asTypeName()) } @Test fun `can identify a Double`() { val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_DOUBLE) .build() assertThat(proto.asClassName(mock())).isEqualTo(Double::class.asTypeName()) } @Test fun `can identify a Float`() { val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_FLOAT) .build() assertThat(proto.asClassName(mock())).isEqualTo(Float::class.asTypeName()) } @Test fun `can identify an Integer`() { listOf( DescriptorProtos.FieldDescriptorProto.Type.TYPE_INT32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_UINT32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_FIXED32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SFIXED32, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SINT32 ).forEach { type -> val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(type) .build() assertThat(proto.asClassName(mock())).isEqualTo(Int::class.asTypeName()) } } @Test fun `can identify a Long`() { listOf( DescriptorProtos.FieldDescriptorProto.Type.TYPE_INT64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_UINT64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_FIXED64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SFIXED64, DescriptorProtos.FieldDescriptorProto.Type.TYPE_SINT64 ).forEach { type -> val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(type) .build() assertThat(proto.asClassName(mock())).isEqualTo(Long::class.asTypeName()) } } @Test fun `can identify a ByteString`() { val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_BYTES) .build() assertThat(proto.asClassName(mock())).isEqualTo(ByteString::class.asTypeName()) } @Test fun `can identify a type`() { val type: ClassName = mock() val typeMap: ProtobufTypeMapper = mock { on { getKotlinType(any()) } doReturn type } val proto = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("my.type") .build() assertThat(proto.asClassName(typeMap)).isEqualTo(type) verify(typeMap).getKotlinType(eq("my.type")) } @Test fun `can describe maps`() { val keyType: DescriptorProtos.FieldDescriptorProto = mock { on { name } doReturn "key" } val valueType: DescriptorProtos.FieldDescriptorProto = mock { on { name } doReturn "value" } val mapType: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(keyType, valueType) } val typeMap: ProtobufTypeMapper = mock { on { getProtoTypeDescriptor(eq("the.type")) } doReturn mapType } val field = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("the.type") .build() val (key, value) = field.describeMap(typeMap) assertThat(key).isEqualTo(keyType) assertThat(value).isEqualTo(valueType) } @Test(expected = IllegalStateException::class) fun `throws on invalid map type`() { val keyType: DescriptorProtos.FieldDescriptorProto = mock { on { name } doReturn "key" } val valueType: DescriptorProtos.FieldDescriptorProto = mock { on { name } doReturn "nope" } val mapType: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(keyType, valueType) } val typeMap: ProtobufTypeMapper = mock { on { getProtoTypeDescriptor(eq("the.type")) } doReturn mapType } val field = DescriptorProtos.FieldDescriptorProto.newBuilder() .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("the.type") .build() field.describeMap(typeMap) } @Test fun `can identify a LRO`() { assertThat( DescriptorProtos.MethodDescriptorProto.newBuilder() .setInputType(".google.longrunning.Operation") .build().isLongRunningOperation() ).isFalse() assertThat( DescriptorProtos.MethodDescriptorProto.newBuilder() .setOutputType(".google.longrunning.Operation") .build().isLongRunningOperation() ).isTrue() listOf( "type", "longrunning.Operation", ".com.longrunning.Operation", "Operation", "long_running_operation" ).forEach { type -> assertThat( DescriptorProtos.MethodDescriptorProto.newBuilder() .setInputType(type) .build().isLongRunningOperation() ).isFalse() assertThat( DescriptorProtos.MethodDescriptorProto.newBuilder() .setOutputType(type) .build().isLongRunningOperation() ).isFalse() } } @Test fun `can get field info for a simple path`() { val proto: DescriptorProtos.FileDescriptorProto = mock() val className: ClassName = mock() val typeMap: ProtobufTypeMapper = mock { on { getKotlinType(any()) } doReturn className } listOf( DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("prop") .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("property") .build(), DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("prop") .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_BOOL) .build() ).forEach { propField -> val context: GeneratorContext = mock { on { this.typeMap } doReturn typeMap on { this.proto } doReturn proto } val type: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(propField) } val path = PropertyPath("prop") val result = getProtoFieldInfoForPath(context, path, type) assertThat(result.field).isEqualTo(propField) assertThat(result.file).isEqualTo(proto) assertThat(result.index).isEqualTo(-1) assertThat(result.message).isEqualTo(type) if (propField.hasTypeName()) { assertThat(result.kotlinType).isEqualTo(className) } else { assertThat(result.kotlinType).isEqualTo(Boolean::class.asClassName()) } } } @Test(expected = IllegalStateException::class) fun `throws on an invalid path`() { val proto: DescriptorProtos.FileDescriptorProto = mock() val typeMap: ProtobufTypeMapper = mock() val context: GeneratorContext = mock { on { this.typeMap } doReturn typeMap on { this.proto } doReturn proto } val type: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf<DescriptorProtos.FieldDescriptorProto>() } val path = PropertyPath("prop") getProtoFieldInfoForPath(context, path, type) } @Test fun `can get field info for a simple 0-indexed path`() = testSimpleIndexedPath("prop[0]") @Test(expected = IllegalArgumentException::class) fun `throws on a non-0-indexed path`() = testSimpleIndexedPath("prop[2]") private fun testSimpleIndexedPath(name: String) { val proto: DescriptorProtos.FileDescriptorProto = mock() val className: ClassName = mock() val typeMap: ProtobufTypeMapper = mock { on { getKotlinType(any()) } doReturn className } val propField = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("prop") .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("property") .build() val context: GeneratorContext = mock { on { this.typeMap } doReturn typeMap on { this.proto } doReturn proto } val type: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(propField) } val result = getProtoFieldInfoForPath(context, PropertyPath(name), type) assertThat(result.field).isEqualTo(propField) assertThat(result.file).isEqualTo(proto) assertThat(result.index).isEqualTo(0) assertThat(result.message).isEqualTo(type) assertThat(result.kotlinType).isEqualTo(className) } @Test fun `can get field info for a compound path`() { val proto: DescriptorProtos.FileDescriptorProto = mock() val className: ClassName = mock() val firstField = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("first") .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("secondType") .build() val firstFieldProto: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(firstField) } val secondField = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("second") .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("thirdType") .build() val secondFiledProto: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(secondField) } val thirdField = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("third") .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("someType") .build() val thirdFiledProto: DescriptorProtos.DescriptorProto = mock { on { fieldList } doReturn listOf(thirdField) } val typeMap: ProtobufTypeMapper = mock { on { getKotlinType(any()) } doReturn className on { hasProtoTypeDescriptor(eq("firstType")) } doReturn true on { hasProtoTypeDescriptor(eq("secondType")) } doReturn true on { hasProtoTypeDescriptor(eq("thirdType")) } doReturn true on { getProtoTypeDescriptor(eq("firstType")) } doReturn firstFieldProto on { getProtoTypeDescriptor(eq("secondType")) } doReturn secondFiledProto on { getProtoTypeDescriptor(eq("thirdType")) } doReturn thirdFiledProto } val context: GeneratorContext = mock { on { this.typeMap } doReturn typeMap on { this.proto } doReturn proto } val path = PropertyPath(listOf("first", "second", "third")) val result = getProtoFieldInfoForPath(context, path, firstFieldProto) assertThat(result.field).isEqualTo(thirdField) assertThat(result.file).isEqualTo(proto) assertThat(result.index).isEqualTo(-1) assertThat(result.message).isEqualTo(thirdFiledProto) assertThat(result.kotlinType).isEqualTo(className) } }
apache-2.0
b25b41f4aeb60b07bf13b6cf5f61a6ac
39.10049
112
0.640709
5.035396
false
true
false
false
GDG-Nantes/devfest-android
app/src/main/kotlin/com/gdgnantes/devfest/android/lifecycle/SessionsLiveData.kt
1
1747
package com.gdgnantes.devfest.android.lifecycle import android.content.Context import com.gdgnantes.devfest.android.model.Room import com.gdgnantes.devfest.android.model.toRoom import com.gdgnantes.devfest.android.model.toSession import com.gdgnantes.devfest.android.provider.ScheduleContract import com.gdgnantes.devfest.android.viewmodel.SessionsViewModel class SessionsLiveData(private val context: Context, private val date: String) : ProviderLiveData<List<SessionsViewModel.Data>>(context) { companion object { // TODO Cyril // Account for the event timezone or express everything in the users timezone ? const val SELECTION = "date(${ScheduleContract.Sessions.SESSION_START_TIMESTAMP}, 'unixepoch') = ?" const val ORDER = "${ScheduleContract.Sessions.SESSION_START_TIMESTAMP} ASC, " + "${ScheduleContract.Sessions.SESSION_END_TIMESTAMP} ASC, " + "${ScheduleContract.Sessions.SESSION_ROOM_ID} ASC" } override fun compute(): List<SessionsViewModel.Data> { val cursor = context.contentResolver.query( ScheduleContract.Sessions.CONTENT_URI, null, SELECTION, arrayOf(date), ORDER) val result = ArrayList<SessionsViewModel.Data>() if (cursor != null) { while (cursor.moveToNext()) { val session = cursor.toSession() var room: Room? = null if (session.roomId != null) { room = cursor.toRoom() } result.add(SessionsViewModel.Data(session, room)) } cursor.close() } return result } }
apache-2.0
1459d026a57933cf0c75aceacdbecf94
36.978261
108
0.622782
4.825967
false
false
false
false
sephiroth74/AndroidUIGestureRecognizer
uigesturerecognizer/src/main/java/it/sephiroth/android/library/uigestures/UITapGestureRecognizer.kt
1
12849
package it.sephiroth.android.library.uigestures import android.content.Context import android.graphics.PointF import android.os.Message import android.util.Log import android.view.MotionEvent import android.view.ViewConfiguration /** * UITapGestureRecognizer looks for single or multiple taps. * For the gesture to be recognized, the specified number of fingers must tap the view a specified number of times. * * @author alessandro crugnola * @see [ * https://developer.apple.com/reference/uikit/uitapgesturerecognizer](https://developer.apple.com/reference/uikit/uitapgesturerecognizer) */ @Suppress("MemberVisibilityCanBePrivate") open class UITapGestureRecognizer(context: Context) : UIGestureRecognizer(context), UIDiscreteGestureRecognizer { override val currentLocationX: Float get() = mDownCurrentLocation.x override val currentLocationY: Float get() = mDownCurrentLocation.y /** * Change the number of required touches for this recognizer to succeed.<br></br> * Default value is 1 * * @since 1.0.0 */ var touchesRequired = 1 override var numberOfTouches: Int = 0 internal set /** * Change the number of required taps for this recognizer to succeed.<br></br> * Default value is 1 * * @since 1.0.0 */ var tapsRequired = 1 /** * the duration in milliseconds we will wait to see if a touch event is a tap or a scroll. * If the user does not move within this interval, it is considered to be a tap. * @since 1.2.5 */ var tapTimeout: Long = TAP_TIMEOUT /** * the duration in milliseconds between the first tap's up event and the second tap's * down event for an interaction to be considered a double-tap. * @since 1.2.5 */ var doubleTapTimeout: Long = DOUBLE_TAP_TIMEOUT /** * Distance in pixels a touch can wander before we think the user is scrolling * @since 1.2.5 */ var scaledTouchSlop: Int /** * Distance in pixels between the first touch and second * touch to still be considered a double tap */ var scaledDoubleTapSlop: Int private var mAlwaysInTapRegion: Boolean = false private var mDownFocus = PointF() private var mStarted: Boolean = false private var mNumTaps = 0 private val mPreviousTapLocation = PointF() private val mDownCurrentLocation = PointF() init { mStarted = false val configuration = ViewConfiguration.get(context) scaledTouchSlop = configuration.scaledTouchSlop scaledDoubleTapSlop = configuration.scaledDoubleTapSlop if (logEnabled) { logMessage(Log.INFO, "tapTimeout: $tapTimeout") logMessage(Log.INFO, "doubleTapTimeout: $doubleTapTimeout") logMessage(Log.INFO, "scaledTouchSlop: $scaledTouchSlop") logMessage(Log.INFO, "scaledDoubleTapSlop: $scaledDoubleTapSlop") } } override fun handleMessage(msg: Message) { when (msg.what) { MESSAGE_RESET -> { logMessage(Log.INFO, "handleMessage(MESSAGE_RESET)") handleReset() } MESSAGE_FAILED -> { logMessage(Log.INFO, "handleMessage(MESSAGE_FAILED)") handleFailed() } MESSAGE_POINTER_UP -> { logMessage(Log.INFO, "handleMessage(MESSAGE_POINTER_UP)") numberOfTouches = msg.arg1 } MESSAGE_LONG_PRESS -> { logMessage(Log.INFO, "handleMessage(MESSAGE_LONG_PRESS)") handleFailed() } else -> { } } } override fun onStateChanged(recognizer: UIGestureRecognizer) { if (UIGestureRecognizer.logEnabled) { logMessage(Log.VERBOSE, "onStateChanged(${recognizer.state?.name})") logMessage(Log.VERBOSE, "mStarted: $mStarted") } if (recognizer.state == State.Failed && state == State.Ended) { stopListenForOtherStateChanges() fireActionEventIfCanRecognizeSimultaneously() postReset() } else if (recognizer.inState(State.Began, State.Ended) && mStarted && inState(State.Possible, State.Ended)) { stopListenForOtherStateChanges() removeMessages() state = State.Failed mStarted = false } } override fun onTouchEvent(event: MotionEvent): Boolean { super.onTouchEvent(event) if (!isEnabled) { return false } val action = event.actionMasked val count = event.pointerCount when (action) { MotionEvent.ACTION_DOWN -> { if (!mStarted && !delegate?.shouldReceiveTouch?.invoke(this)!!) { return cancelsTouchesInView } removeMessages() mAlwaysInTapRegion = true numberOfTouches = count state = State.Possible setBeginFiringEvents(false) if (!mStarted) { stopListenForOtherStateChanges() mNumTaps = 0 mStarted = true } else { // if second tap is too far wawy from the first // and only 1 finger is required if (touchesRequired == 1 && tapsRequired > 1) { val distance = mDownLocation.distance(mPreviousDownLocation) logMessage(Log.VERBOSE, "distance: $distance") if (distance > scaledDoubleTapSlop) { logMessage(Log.WARN, "second touch too far away ($distance > $scaledDoubleTapSlop)") handleFailed() return cancelsTouchesInView } } } mHandler.sendEmptyMessageDelayed(MESSAGE_LONG_PRESS, tapTimeout + TIMEOUT_DELAY_MILLIS) mNumTaps++ mDownFocus.set(mCurrentLocation) mDownCurrentLocation.set(mCurrentLocation) } MotionEvent.ACTION_POINTER_DOWN -> if (state == State.Possible && mStarted) { removeMessages(MESSAGE_POINTER_UP) numberOfTouches = count if (numberOfTouches > 1) { if (numberOfTouches > touchesRequired) { logMessage(Log.WARN, "too many touches: $numberOfTouches > $touchesRequired") state = State.Failed } else if (numberOfTouches == touchesRequired && tapsRequired > 1) { // let's check if the current tap is too far away from the previous if (mNumTaps < tapsRequired) { mPreviousTapLocation.set(mCurrentLocation) } else if (mNumTaps == tapsRequired) { val distance = mCurrentLocation.distance(mPreviousTapLocation) // moved too much from the previous tap if (distance > scaledDoubleTapSlop) { logMessage(Log.WARN, "distance is $distance > $scaledDoubleTapSlop") handleFailed() return cancelsTouchesInView } } } } mDownFocus.set(mCurrentLocation) mDownCurrentLocation.set(mCurrentLocation) } MotionEvent.ACTION_POINTER_UP -> if (state == State.Possible && mStarted) { removeMessages(MESSAGE_FAILED, MESSAGE_RESET, MESSAGE_POINTER_UP) mDownFocus.set(mCurrentLocation) val message = mHandler.obtainMessage(MESSAGE_POINTER_UP) message.arg1 = numberOfTouches - 1 mHandler.sendMessageDelayed(message, UIGestureRecognizer.TAP_TIMEOUT) } MotionEvent.ACTION_MOVE -> if (state == State.Possible && mStarted) { if (mAlwaysInTapRegion) { val distance = mDownFocus.distance(mCurrentLocation) // if taps and touches > 1 then we need to be less strict val slop = if (touchesRequired > 1 && tapsRequired > 1) scaledDoubleTapSlop else scaledTouchSlop if (distance > slop) { mDownCurrentLocation.set(mCurrentLocation) logMessage(Log.WARN, "distance: $distance, slop: $slop") mAlwaysInTapRegion = false removeMessages() state = State.Failed } } } MotionEvent.ACTION_UP -> { removeMessages(MESSAGE_RESET, MESSAGE_POINTER_UP, MESSAGE_LONG_PRESS) if (state == State.Possible && mStarted) { if (numberOfTouches != touchesRequired) { logMessage(Log.WARN, "number touches not correct: $numberOfTouches != $touchesRequired") handleFailed() } else { if (mNumTaps < tapsRequired) { delayedFail() } else { // nailed! if (delegate?.shouldBegin?.invoke(this)!!) { state = State.Ended if (null == requireFailureOf) { fireActionEventIfCanRecognizeSimultaneously() postReset() } else { when { requireFailureOf!!.state === State.Failed -> { fireActionEventIfCanRecognizeSimultaneously() postReset() } requireFailureOf!!.inState(State.Began, State.Ended, State.Changed) -> state = State.Failed else -> { listenForOtherStateChanges() } } } } else { state = State.Failed } mStarted = false } } } else { handleReset() } } MotionEvent.ACTION_CANCEL -> { removeMessages() mStarted = false state = State.Cancelled setBeginFiringEvents(false) postReset() } else -> { } } return cancelsTouchesInView } private fun fireActionEventIfCanRecognizeSimultaneously() { if (delegate?.shouldRecognizeSimultaneouslyWithGestureRecognizer(this)!!) { setBeginFiringEvents(true) fireActionEvent() } } override fun hasBeganFiringEvents(): Boolean { return super.hasBeganFiringEvents() && inState(State.Ended) } override fun removeMessages() { removeMessages(MESSAGE_FAILED, MESSAGE_RESET, MESSAGE_POINTER_UP, MESSAGE_LONG_PRESS) } private fun postReset() { mHandler.sendEmptyMessage(MESSAGE_RESET) } private fun delayedFail() { mHandler.sendEmptyMessageDelayed(MESSAGE_FAILED, doubleTapTimeout) } private fun handleFailed() { state = State.Failed setBeginFiringEvents(false) removeMessages() mStarted = false } private fun handleReset() { state = State.Possible setBeginFiringEvents(false) mStarted = false } override fun reset() { super.reset() handleReset() } companion object { // request to change the current state to Failed private const val MESSAGE_FAILED = 1 // request to change the current state to Possible private const val MESSAGE_RESET = 2 // we handle the action_pointer_up received in the onTouchEvent with a delay // in order to check how many fingers were actually down when we're checking them // in the action_up. private const val MESSAGE_POINTER_UP = 3 // a long press will make this gesture to fail private const val MESSAGE_LONG_PRESS = 4 } }
mit
5a08b1efd185e1d0bb3613f5e5c77464
35.502841
138
0.534594
5.652882
false
false
false
false
xamoom/xamoom-android-sdk
xamoomsdk/src/main/java/com/xamoom/android/xamoomcontentblocks/Views/CustomMapViewWithChart.kt
1
2754
package com.xamoom.android.xamoomcontentblocks.Views import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.* import com.github.mikephil.charting.charts.LineChart import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.floatingactionbutton.FloatingActionButton import com.mapbox.mapboxsdk.maps.MapView import com.xamoom.android.xamoomsdk.R class CustomMapViewWithChart : RelativeLayout { @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) var mapView: MapView var textView: TextView var bottomSheetBehavior: BottomSheetBehavior<View> var centerSpotsButton: FloatingActionButton var centerUserButton: FloatingActionButton var spotTitleTextView: TextView var spotExcerptTextView: TextView var spotNavigationButton: Button var spotContentButton: Button var spotImageView: ImageView var chart: LineChart var imperialRadioButton: RadioButton var metricRadioButton: RadioButton var elevationRadioGroup: RadioGroup var infoButton: FloatingActionButton var zoomInButton: ImageButton var zoomOutButton: ImageButton init { val v = LayoutInflater.from(context) .inflate(R.layout.item_map_and_chart, this, true) mapView = v.findViewById(R.id.mapImageView) textView = v.findViewById(R.id.titleTextView) val view: View = v.findViewById(R.id.bottom_sheet) view.setOnTouchListener { _, event -> view.onTouchEvent(event) true } bottomSheetBehavior = BottomSheetBehavior.from<View>(view) centerSpotsButton = v.findViewById(R.id.center_spot_fab) centerUserButton = v.findViewById(R.id.user_location_fab) spotTitleTextView = v.findViewById(R.id.spot_title_text_view) spotExcerptTextView = v.findViewById(R.id.spot_excerpt_text_view) spotImageView = v.findViewById(R.id.spot_image_view) spotContentButton = v.findViewById(R.id.spot_content_button) spotNavigationButton = v.findViewById(R.id.spot_navigation_button) chart = v.findViewById(R.id.elevationChart) imperialRadioButton = v.findViewById(R.id.elevation_radio_imperial) metricRadioButton = v.findViewById(R.id.elevation_radio_metric) elevationRadioGroup = v.findViewById(R.id.elevation_radio_group) infoButton = v.findViewById(R.id.info_button) zoomInButton = v.findViewById(R.id.zoom_in_button) zoomOutButton = v.findViewById(R.id.zoom_out_button) } }
mit
fe4df4e9db3a52c0fb8b0fb8792f484c
40.119403
76
0.726943
4.323391
false
false
false
false
FHannes/intellij-community
python/src/com/jetbrains/python/codeInsight/typing/PyTypingInspectionExtension.kt
9
1854
/* * 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.jetbrains.python.codeInsight.typing import com.jetbrains.python.PyNames import com.jetbrains.python.inspections.PyInspectionExtension import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.types.PyClassLikeType import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext class PyTypingInspectionExtension : PyInspectionExtension() { override fun ignoreUnresolvedMember(type: PyType, name: String, context: TypeEvalContext): Boolean { return name == PyNames.GETITEM && type is PyClassLikeType && type.isDefinition && !isBuiltin(type) && isGenericItselfOrDescendant(type, context) } private fun isGenericItselfOrDescendant(type: PyClassLikeType, context: TypeEvalContext): Boolean { return type.classQName == PyTypingTypeProvider.GENERIC || type.getSuperClassTypes(context).any { it.classQName == PyTypingTypeProvider.GENERIC } } private fun isBuiltin(type: PyClassLikeType): Boolean { return if (type is PyClassType) PyBuiltinCache.getInstance(type.pyClass).isBuiltin(type.pyClass) else false } }
apache-2.0
bc4a49cc73e7d64999c762ded7b0fe72
39.304348
111
0.743797
4.589109
false
false
false
false
Esri/arcgis-runtime-demos-android
android-demos/GeotriggerMonitoring/GeotriggerMonitoringDemo-WithGeotriggers/app/src/main/java/com/arcgisruntime/sample/geotriggermonitoringdemo/view/MapViewModel.kt
1
3148
package com.arcgisruntime.sample.geotriggermonitoringdemo.view import android.graphics.Color import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.arcgisruntime.sample.geotriggermonitoringdemo.domain.GeotriggerInteractor import com.arcgisruntime.sample.geotriggermonitoringdemo.domain.PointOfInterestInteractor import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.geometry.SpatialReferences import com.esri.arcgisruntime.location.LocationDataSource import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.Basemap import com.esri.arcgisruntime.mapping.Viewpoint import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol import com.esri.arcgisruntime.symbology.SimpleRenderer import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MapViewModel @Inject constructor( private val pointOfInterestInteractor: PointOfInterestInteractor, private val geotriggerInteractor: GeotriggerInteractor ) : ViewModel() { val map: ArcGISMap = ArcGISMap(Basemap.createLightGrayCanvasVector()) private val _viewpoint = MutableLiveData<Viewpoint>() val viewpoint: LiveData<Viewpoint> = _viewpoint val shouldMonitor = geotriggerInteractor.shouldMonitor val locationDataSource: LocationDataSource = geotriggerInteractor.lds private val symbol = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.X, Color.RED, 10.0F) val graphicsOverlay = GraphicsOverlay().apply { renderer = SimpleRenderer(symbol) } init { // ensures the graphics overlay is always updated with new points of interest viewModelScope.launch { pointOfInterestInteractor.getGraphicsForPointsOfInterest().collect { graphicsOverlay.graphics.clear() graphicsOverlay.graphics.addAll(it) } } // set the viewpoint to Edinburgh setEdinburgh() } private fun setViewpoint(x: Double, y: Double, scale: Double) { val point = Point(x, y, SpatialReferences.getWgs84()) _viewpoint.value = Viewpoint(point, scale) } fun createPointOfInterest(point: Point) { viewModelScope.launch { pointOfInterestInteractor.createPointOfInterest(point) } } fun clearPointsOfInterest() { viewModelScope.launch { pointOfInterestInteractor.clearPointsOfInterest() } } fun setEdinburgh() { setViewpoint(-3.1824314444161477, 55.95994422289002, 50000.0) } fun startMonitoring() { geotriggerInteractor.createMonitors(graphicsOverlay, 50.0) viewModelScope.launch(Dispatchers.Main) { geotriggerInteractor.setMonitoring(true) } } fun stopMonitoring() { viewModelScope.launch(Dispatchers.Main) { geotriggerInteractor.setMonitoring(false) } } }
apache-2.0
a1e0c52bb3e482f8a5f9d4e980040605
35.195402
89
0.7554
4.622614
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/text/NovelTextBaseFullScreenActivity.kt
1
4709
package cc.aoeiuv020.panovel.text import android.annotation.SuppressLint import android.os.Build import android.os.Bundle import android.os.Handler import android.view.MenuItem import android.view.View import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import cc.aoeiuv020.panovel.R import cc.aoeiuv020.panovel.settings.ReaderSettings import cc.aoeiuv020.panovel.util.hide import cc.aoeiuv020.panovel.util.show import kotlinx.android.synthetic.main.activity_novel_text.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug /** * 全屏Activity,绝大部分代码是自动生成的, * 分离出来仅供activity_novel_text使用, * Created by AoEiuV020 on 2017.09.15-17:38. */ @Suppress("MemberVisibilityCanPrivate", "unused") abstract class NovelTextBaseFullScreenActivity : AppCompatActivity(), AnkoLogger { private val mHideHandler = Handler() @SuppressLint("InlinedApi") private val mHidePart2Runnable = Runnable { if (ReaderSettings.fullScreen) { flContent.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION } } private val mShowPart2Runnable = Runnable { app_bar.show() fullscreen_content_controls.visibility = View.VISIBLE } protected var mVisible: Boolean = false private val mHideRunnable = Runnable { hide() } private val mDelayHideTouchListener = View.OnTouchListener { _, _ -> @Suppress("ConstantConditionIf") if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS) } false } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> onBackPressed() else -> super.onOptionsItemSelected(item) } return true } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_novel_text) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (ReaderSettings.fullScreen) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = 0xff000000.toInt() } } mVisible = true } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) hide() } override fun onRestart() { super.onRestart() if (!mVisible) { hide() } } fun toggle() { if (mVisible) { hide() } else { if (fullscreen_content_controls.visibility != View.GONE) { hide() } else { show() } } } // 进入全屏但不隐藏菜单栏, fun fullScreen() { app_bar.hide() mVisible = false mHideHandler.removeCallbacks(mShowPart2Runnable) mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong()) } fun hide() { debug { "hide" } fullscreen_content_controls.visibility = View.GONE fullScreen() } protected open fun show() { debug { "show" } if (ReaderSettings.fullScreen) { flContent.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION } mVisible = true mHideHandler.removeCallbacks(mHidePart2Runnable) mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY.toLong()) } private fun delayedHide(delayMillis: Int) { mHideHandler.removeCallbacks(mHideRunnable) mHideHandler.postDelayed(mHideRunnable, delayMillis.toLong()) } companion object { private val AUTO_HIDE = true private val AUTO_HIDE_DELAY_MILLIS = 3000 private val UI_ANIMATION_DELAY get() = ReaderSettings.fullScreenDelay } }
gpl-3.0
d10c001bf16009b280da3e340eeac142
31.412587
130
0.635814
4.431166
false
false
false
false
Light-Team/ModPE-IDE-Source
editorkit/src/main/kotlin/com/brackeys/ui/editorkit/theme/EditorTheme.kt
1
10220
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.editorkit.theme import android.graphics.Color import com.brackeys.ui.editorkit.model.ColorScheme import com.brackeys.ui.language.base.model.SyntaxScheme object EditorTheme { val DARCULA = ColorScheme( textColor = Color.parseColor("#ABB7C5"), backgroundColor = Color.parseColor("#303030"), gutterColor = Color.parseColor("#313335"), gutterDividerColor = Color.parseColor("#555555"), gutterCurrentLineNumberColor = Color.parseColor("#A4A3A3"), gutterTextColor = Color.parseColor("#616366"), selectedLineColor = Color.parseColor("#3A3A3A"), selectionColor = Color.parseColor("#28427F"), suggestionQueryColor = Color.parseColor("#987DAC"), findResultBackgroundColor = Color.parseColor("#33654B"), delimiterBackgroundColor = Color.parseColor("#33654B"), syntaxScheme = SyntaxScheme( numberColor = Color.parseColor("#6897BB"), operatorColor = Color.parseColor("#E8E2B7"), keywordColor = Color.parseColor("#EC7600"), typeColor = Color.parseColor("#EC7600"), langConstColor = Color.parseColor("#EC7600"), preprocessorColor = Color.parseColor("#C9C54E"), variableColor = Color.parseColor("#9378A7"), methodColor = Color.parseColor("#FEC76C"), stringColor = Color.parseColor("#6E875A"), commentColor = Color.parseColor("#66747B"), tagColor = Color.parseColor("#E2C077"), tagNameColor = Color.parseColor("#E2C077"), attrNameColor = Color.parseColor("#BABABA"), attrValueColor = Color.parseColor("#ABC16D"), entityRefColor = Color.parseColor("#6897BB") ) ) val MONOKAI = ColorScheme( textColor = Color.parseColor("#F8F8F8"), backgroundColor = Color.parseColor("#272823"), gutterColor = Color.parseColor("#272823"), gutterDividerColor = Color.parseColor("#5B5A4F"), gutterCurrentLineNumberColor = Color.parseColor("#C8BBAC"), gutterTextColor = Color.parseColor("#5B5A4F"), selectedLineColor = Color.parseColor("#34352D"), selectionColor = Color.parseColor("#666666"), suggestionQueryColor = Color.parseColor("#7CE0F3"), findResultBackgroundColor = Color.parseColor("#5F5E5A"), delimiterBackgroundColor = Color.parseColor("#5F5E5A"), syntaxScheme = SyntaxScheme( numberColor = Color.parseColor("#BB8FF8"), operatorColor = Color.parseColor("#F8F8F2"), keywordColor = Color.parseColor("#EB347E"), typeColor = Color.parseColor("#7FD0E4"), langConstColor = Color.parseColor("#EB347E"), preprocessorColor = Color.parseColor("#EB347E"), variableColor = Color.parseColor("#7FD0E4"), methodColor = Color.parseColor("#B6E951"), stringColor = Color.parseColor("#EBE48C"), commentColor = Color.parseColor("#89826D"), tagColor = Color.parseColor("#F8F8F8"), tagNameColor = Color.parseColor("#EB347E"), attrNameColor = Color.parseColor("#B6E951"), attrValueColor = Color.parseColor("#EBE48C"), entityRefColor = Color.parseColor("#BB8FF8") ) ) val OBSIDIAN = ColorScheme( textColor = Color.parseColor("#E0E2E4"), backgroundColor = Color.parseColor("#2A3134"), gutterColor = Color.parseColor("#2A3134"), gutterDividerColor = Color.parseColor("#67777B"), gutterCurrentLineNumberColor = Color.parseColor("#E0E0E0"), gutterTextColor = Color.parseColor("#859599"), selectedLineColor = Color.parseColor("#31393C"), selectionColor = Color.parseColor("#616161"), suggestionQueryColor = Color.parseColor("#9EC56F"), findResultBackgroundColor = Color.parseColor("#838177"), delimiterBackgroundColor = Color.parseColor("#616161"), syntaxScheme = SyntaxScheme( numberColor = Color.parseColor("#F8CE4E"), operatorColor = Color.parseColor("#E7E2BC"), keywordColor = Color.parseColor("#9EC56F"), typeColor = Color.parseColor("#9EC56F"), langConstColor = Color.parseColor("#9EC56F"), preprocessorColor = Color.parseColor("#9B84B9"), variableColor = Color.parseColor("#6E8BAE"), methodColor = Color.parseColor("#E7E2BC"), stringColor = Color.parseColor("#DE7C2E"), commentColor = Color.parseColor("#808C92"), tagColor = Color.parseColor("#E7E2BC"), tagNameColor = Color.parseColor("#9EC56F"), attrNameColor = Color.parseColor("#E0E2E4"), attrValueColor = Color.parseColor("#DE7C2E"), entityRefColor = Color.parseColor("#F8CE4E") ) ) val LADIES_NIGHT = ColorScheme( textColor = Color.parseColor("#E0E2E4"), backgroundColor = Color.parseColor("#22282C"), gutterColor = Color.parseColor("#2A3134"), gutterDividerColor = Color.parseColor("#4F575A"), gutterCurrentLineNumberColor = Color.parseColor("#E0E2E4"), gutterTextColor = Color.parseColor("#859599"), selectedLineColor = Color.parseColor("#373340"), selectionColor = Color.parseColor("#5B2B41"), suggestionQueryColor = Color.parseColor("#6E8BAE"), findResultBackgroundColor = Color.parseColor("#8A4364"), delimiterBackgroundColor = Color.parseColor("#616161"), syntaxScheme = SyntaxScheme( numberColor = Color.parseColor("#7EFBFD"), operatorColor = Color.parseColor("#E7E2BC"), keywordColor = Color.parseColor("#DA89A2"), typeColor = Color.parseColor("#DA89A2"), langConstColor = Color.parseColor("#DA89A2"), preprocessorColor = Color.parseColor("#9B84B9"), variableColor = Color.parseColor("#6EA4C7"), methodColor = Color.parseColor("#8FB4C5"), stringColor = Color.parseColor("#75D367"), commentColor = Color.parseColor("#808C92"), tagColor = Color.parseColor("#E7E2BC"), tagNameColor = Color.parseColor("#DA89A2"), attrNameColor = Color.parseColor("#E0E2E4"), attrValueColor = Color.parseColor("#75D367"), entityRefColor = Color.parseColor("#7EFBFD") ) ) val TOMORROW_NIGHT = ColorScheme( textColor = Color.parseColor("#C6C8C6"), backgroundColor = Color.parseColor("#222426"), gutterColor = Color.parseColor("#222426"), gutterDividerColor = Color.parseColor("#4B4D51"), gutterCurrentLineNumberColor = Color.parseColor("#FFFFFF"), gutterTextColor = Color.parseColor("#C6C8C6"), selectedLineColor = Color.parseColor("#2D2F33"), selectionColor = Color.parseColor("#383B40"), suggestionQueryColor = Color.parseColor("#EAC780"), findResultBackgroundColor = Color.parseColor("#4B4E54"), delimiterBackgroundColor = Color.parseColor("#616161"), syntaxScheme = SyntaxScheme( numberColor = Color.parseColor("#D49668"), operatorColor = Color.parseColor("#CFD1CF"), keywordColor = Color.parseColor("#AD95B8"), typeColor = Color.parseColor("#AD95B8"), langConstColor = Color.parseColor("#AD95B8"), preprocessorColor = Color.parseColor("#CFD1CF"), variableColor = Color.parseColor("#EAC780"), methodColor = Color.parseColor("#87A1BB"), stringColor = Color.parseColor("#B7BC73"), commentColor = Color.parseColor("#969896"), tagColor = Color.parseColor("#CFD1CF"), tagNameColor = Color.parseColor("#AD95B8"), attrNameColor = Color.parseColor("#C6C8C6"), attrValueColor = Color.parseColor("#B7BC73"), entityRefColor = Color.parseColor("#D49668") ) ) val VISUAL_STUDIO_2013 = ColorScheme( textColor = Color.parseColor("#C8C8C8"), backgroundColor = Color.parseColor("#232323"), gutterColor = Color.parseColor("#2C2C2C"), gutterDividerColor = Color.parseColor("#555555"), gutterCurrentLineNumberColor = Color.parseColor("#FFFFFF"), gutterTextColor = Color.parseColor("#C6C8C6"), selectedLineColor = Color.parseColor("#141414"), selectionColor = Color.parseColor("#454464"), suggestionQueryColor = Color.parseColor("#4F98F7"), findResultBackgroundColor = Color.parseColor("#1C3D6B"), delimiterBackgroundColor = Color.parseColor("#616161"), syntaxScheme = SyntaxScheme( numberColor = Color.parseColor("#BACDAB"), operatorColor = Color.parseColor("#DCDCDC"), keywordColor = Color.parseColor("#669BD1"), typeColor = Color.parseColor("#669BD1"), langConstColor = Color.parseColor("#669BD1"), preprocessorColor = Color.parseColor("#C49594"), variableColor = Color.parseColor("#9DDDFF"), methodColor = Color.parseColor("#71C6B1"), stringColor = Color.parseColor("#CE9F89"), commentColor = Color.parseColor("#6BA455"), tagColor = Color.parseColor("#DCDCDC"), tagNameColor = Color.parseColor("#669BD1"), attrNameColor = Color.parseColor("#C8C8C8"), attrValueColor = Color.parseColor("#CE9F89"), entityRefColor = Color.parseColor("#BACDAB") ) ) }
apache-2.0
90062c81d8c26cf11db887127195b305
47.671429
75
0.632779
4.412781
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/MythRecordedTool.kt
1
6196
/* 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 import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.TaskParser import uk.co.nickthecoder.paratask.parameters.FileParameter import uk.co.nickthecoder.paratask.parameters.StringParameter import uk.co.nickthecoder.paratask.table.BaseFileColumn import uk.co.nickthecoder.paratask.table.Column import uk.co.nickthecoder.paratask.table.ListTableTool import uk.co.nickthecoder.paratask.table.LocalDateTimeColumn import uk.co.nickthecoder.paratask.table.filter.RowFilter import java.io.BufferedReader import java.io.DataOutputStream import java.io.File import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import java.net.URLEncoder import java.sql.DriverManager import java.sql.Timestamp import java.text.SimpleDateFormat /** * */ class MythRecordedTool : ListTableTool<MythRecordedTool.RecordedLine>() { override val taskD = TaskDescription("mythRecorded") val serverP = StringParameter("server") val databaseP = StringParameter("database", value = "mythconverg") val userP = StringParameter("user", value = "mythtv") val passwordP = StringParameter("password") val directoryP = FileParameter("directory", expectFile = false) override val rowFilter = RowFilter(this, columns, RecordedLine("", "", Timestamp(0), "", "", "", File(""))) init { Class.forName("com.mysql.jdbc.Driver") taskD.addParameters(serverP, databaseP, userP, passwordP, directoryP) directoryP.aliases.add("direcotry") columns.add(Column<RecordedLine, String>("channel", getter = { it.channel })) columns.add(LocalDateTimeColumn<RecordedLine>("start", getter = { it.start.toLocalDateTime() })) columns.add(Column<RecordedLine, String>("title", getter = { it.title })) columns.add(Column<RecordedLine, String>("subtitle", getter = { it.subtitle })) columns.add(Column<RecordedLine, String>("description", getter = { it.description })) columns.add(BaseFileColumn<RecordedLine>("file", base = directoryP.value!!, getter = { it.file })) } override fun run() { longTitle = "Myth Recorded. Server: ${serverP.value}" list.clear() val server = encode(serverP.value) val database = encode(databaseP.value) val user = encode(userP.value) val password = encode(passwordP.value) val connect = DriverManager.getConnection("jdbc:mysql://$server/$database?user=$user&password=$password") val statement = connect.createStatement() val resultSet = statement.executeQuery("SELECT channel.name, channel.chanid, progstart, title, subtitle, description, basename FROM recorded, channel WHERE recorded.chanid = channel.chanid ORDER BY progstart DESC;") while (resultSet.next()) { val channel = resultSet.getString("name") val channelID = resultSet.getString("chanid") val start = resultSet.getTimestamp("progstart") val title = resultSet.getString("title") val subtitle = resultSet.getString("subtitle") val description = resultSet.getString("description") val basename = resultSet.getString("basename") val file = File(directoryP.value!!, basename) val line = RecordedLine(channel, channelID, start, title, subtitle, description, file) list.add(line) } } private fun encode(str: String) = URLEncoder.encode(str, "UTF-8") inner class RecordedLine( val channel: String, val channelID: String, val start: Timestamp, val title: String, val subtitle: String, val description: String, val file: File) { fun isFile() = true // For "file.json" /** * Use the myth "services API" to delete a recorded program. * See .https://www.mythtv.org/wiki/DVR_Service#DeleteRecording * * Example POST request : * http://BackendServerIP:6544/Dvr/DeleteRecording?StartTime=2011-10-03T19:00:00&ChanId=2066 */ fun delete() { val url = URL("http://${serverP.value}:6544.") println("URL = $url") val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val formattedStartTime = dateFormat.format(start).replace(' ', 'T') val urlParameters = "StartTime=$formattedStartTime&ChanId=$channelID" println("Opening connection") val connection = url.openConnection() as HttpURLConnection println("Opened connection") connection.requestMethod = "POST" println("Set to post") connection.doOutput = true println("Setting output stream") val wr = DataOutputStream(connection.outputStream) wr.writeBytes(urlParameters) wr.flush() wr.close() println("Created the connection") val responseCode = connection.responseCode println("Response code $responseCode") // We don't care about the results! val input = BufferedReader(InputStreamReader(connection.inputStream)) var line = input.readLine() while (line != null) { println(line) line = input.readLine() } input.close() } } } fun main(args: Array<String>) { TaskParser(MythRecordedTool()).go(args) }
gpl-3.0
fc9d71c3a8108928554b044f74a95890
36.780488
223
0.666559
4.438395
false
false
false
false
lambdasoup/watchlater
tea/src/test/java/com/lambdasoup/tea/TeaTest.kt
1
4087
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.tea import com.lambdasoup.tea.TeaTest.Msg.OnSubMsg import com.lambdasoup.tea.TeaTest.Msg.TaskResult import com.lambdasoup.tea.testing.TeaTestEngineRule import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.inOrder import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.junit.Rule import org.junit.Test class TeaTest { @get:Rule var rule = TeaTestEngineRule(autoExecute = false) data class Model( val string: String = "test-string", val int: Int = 0, ) sealed class Msg { data class OnSubMsg(val i: Int) : Msg() data class TaskResult(val s: String) : Msg() } @Test fun `should do initial render with init model`() { val view: (Model) -> Unit = mock() val update: (Model, Msg) -> Pair<Model, Cmd<Msg>> = mock() val subscriptions: (Model) -> Sub<Msg> = mock() whenever(subscriptions.invoke(any())).thenReturn(Sub.none()) val tea = Tea( init = Model(string = "test-name") * Cmd.none(), view = view, update = update, subscriptions = subscriptions, ) tea.clear() verify(view).invoke(Model(string = "test-name")) verify(subscriptions).invoke(Model(string = "test-name")) } @Test fun `should bind and unbind subscriptions`() { val view: (Model) -> Unit = mock() val update: (Model, Msg) -> Pair<Model, Cmd<Msg>> = mock() val sub: Sub<Msg> = mock() val tea = Tea( init = Model(string = "test-name") * Cmd.none(), view = view, update = update, subscriptions = { sub }, ) verify(sub).bind() tea.clear() verify(sub).unbind() } @Test fun `should execute task`() { val view: (Model) -> Unit = mock() val task = Cmd.task<Msg, String> { "test-result" } val tea = Tea( init = Model() * task { TaskResult("test-result") }, view = view, update = { model, msg -> when (msg) { is TaskResult -> model.copy(string = msg.s) * Cmd.none() else -> model * Cmd.none() } }, subscriptions = { Sub.none() }, ) rule.proceed() tea.clear() inOrder(view) { verify(view).invoke(Model()) verify(view).invoke(Model(string = "test-result")) } } @Test fun `should process sub`() { val view: (Model) -> Unit = mock() val sub = Sub.create<Int, Msg>() val tea = Tea( init = Model() * Cmd.none(), view = view, update = { model, msg -> when (msg) { is OnSubMsg -> model.copy(int = msg.i) * Cmd.none() else -> model * Cmd.none() } }, subscriptions = { sub { OnSubMsg(it) } }, ) sub.submit(1337) tea.clear() inOrder(view) { verify(view).invoke(Model()) verify(view).invoke(Model().copy(int = 1337)) } } }
gpl-3.0
fb7864fb6b778276217cd724cbb99714
27.58042
76
0.561292
3.941176
false
true
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/adapter/ProjectsListAdapter.kt
2
12701
/* * This file is part of BOINC. * https://boinc.berkeley.edu * Copyright (C) 2022 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.adapter import android.R.color import android.app.Activity import android.graphics.Bitmap import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.ListView import android.widget.RelativeLayout import android.widget.TextView import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import edu.berkeley.boinc.BOINCActivity import edu.berkeley.boinc.ProjectsFragment.ProjectsListData import edu.berkeley.boinc.R import edu.berkeley.boinc.rpc.TransferStatus.ERR_GIVEUP_DOWNLOAD import edu.berkeley.boinc.rpc.TransferStatus.ERR_GIVEUP_UPLOAD import edu.berkeley.boinc.utils.Logging.Category.GUI_VIEW import edu.berkeley.boinc.utils.Logging.Category.MONITOR import edu.berkeley.boinc.utils.Logging.logException import java.text.DecimalFormat import java.text.NumberFormat import java.time.Duration import java.time.Instant import kotlin.math.roundToInt import org.apache.commons.lang3.StringUtils class ProjectsListAdapter( private val activity: Activity, listView: ListView, textViewResourceId: Int, private val entries: List<ProjectsListData> ) : ArrayAdapter<ProjectsListData>(activity, textViewResourceId, entries) { init { listView.adapter = this } override fun getCount(): Int { return entries.size } override fun getItem(position: Int): ProjectsListData { return entries[position] } override fun getItemId(position: Int): Long { return position.toLong() } fun getDiskUsage(position: Int): String { val diskUsage = entries[position].project!!.diskUsage val df = DecimalFormat("#.##") return df.format(diskUsage / (1024 * 1024)) } fun getName(position: Int): String { return entries[position].project!!.projectName } private fun getUser(position: Int): String { val user = entries[position].project!!.userName val team = entries[position].project!!.teamName return if (team.isNotEmpty()) { "$user ($team)" } else user } private fun getIcon(position: Int): Bitmap? { // try to get current client status from monitor return try { BOINCActivity.monitor!!.getProjectIcon(entries[position].id) } catch (e: Exception) { logException( MONITOR, "ProjectsListAdapter: Could not load data, clientStatus not initialized.", e ) null } } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val data = entries[position] val isAcctMgr = data.isMgr var vi = convertView // setup new view, if: // - view is null, has not been here before // - view has different id var setup = false if (vi == null) { setup = true } else { val viewId = vi.tag?.toString().orEmpty() if (!StringUtils.equals(data.id, viewId)) { setup = true } } if (setup) { val layoutInflater = ContextCompat.getSystemService( activity, LayoutInflater::class.java )!! vi = if (isAcctMgr) { layoutInflater.inflate(R.layout.projects_layout_listitem_acctmgr, null) } else { layoutInflater.inflate(R.layout.projects_layout_listitem, null) } vi!!.setOnClickListener(entries[position].projectsListClickListener) vi.tag = data.id } if (isAcctMgr) { // element is account manager // populate name val tvName = vi!!.findViewById<TextView>(R.id.name) tvName.text = data.acctMgrInfo!!.acctMgrName // populate url val tvUrl = vi.findViewById<TextView>(R.id.url) tvUrl.text = data.acctMgrInfo!!.acctMgrUrl } else { // element is project // set data of standard elements val tvName = vi!!.findViewById<TextView>(R.id.project_name) tvName.text = getName(position) val tvUser = vi.findViewById<TextView>(R.id.project_user) val userText = getUser(position) if (userText.isEmpty()) { tvUser.visibility = View.GONE } else { tvUser.visibility = View.VISIBLE tvUser.text = userText } var statusText = "" try { statusText = BOINCActivity.monitor!!.getProjectStatus(data.project!!.masterURL) } catch (e: Exception) { logException(GUI_VIEW, "ProjectsListAdapter.getView error: ", e) } val tvStatus = vi.findViewById<TextView>(R.id.project_status) if (statusText.isEmpty()) { tvStatus.visibility = View.GONE } else { tvStatus.visibility = View.VISIBLE tvStatus.text = statusText } val ivIcon = vi.findViewById<ImageView>(R.id.project_icon) val finalIconId = ivIcon.tag?.toString().orEmpty() if (!StringUtils.equals(finalIconId, data.id)) { val icon = getIcon(position) // if available set icon, if not boinc logo if (icon == null) { // BOINC logo ivIcon.setImageResource(R.drawable.ic_boinc) } else { // project icon ivIcon.setImageBitmap(icon) // mark as final ivIcon.tag = data.id } } // transfers val numberTransfers = data.projectTransfers!!.size val tvTransfers = vi.findViewById<TextView>(R.id.project_transfers) var transfersString = "" if (numberTransfers > 0) { // ongoing transfers // summarize information for compact representation var numberTransfersUpload = 0 var uploadsPresent = false var numberTransfersDownload = 0 var downloadsPresent = false var transfersActive = false // true if at least one transfer is active var nextRetryS: Long = 0 var transferStatus = 0 for (trans in data.projectTransfers!!) { if (trans.isUpload) { numberTransfersUpload++ uploadsPresent = true } else { numberTransfersDownload++ downloadsPresent = true } if (trans.isTransferActive) { transfersActive = true } else if (trans.nextRequestTime < nextRetryS || nextRetryS == 0L) { nextRetryS = trans.nextRequestTime transferStatus = trans.status } } var numberTransfersString = "(" // will never be empty if (downloadsPresent) { numberTransfersString += "$numberTransfersDownload " + activity.resources.getString( R.string.trans_download ) } if (downloadsPresent && uploadsPresent) { numberTransfersString += " / " } if (uploadsPresent) { numberTransfersString += "$numberTransfersUpload " + activity.resources.getString( R.string.trans_upload ) } numberTransfersString += ")" var activityStatus = "" // will never be empty var activityExplanation = "" if (nextRetryS > Instant.now().epochSecond) { activityStatus += activity.resources.getString(R.string.trans_pending) val retryInSeconds = Duration.between( Instant.now(), Instant.ofEpochSecond(nextRetryS) ).seconds // if timestamp is in the past, do not write anything if (retryInSeconds >= 0) { val formattedTime = DateUtils.formatElapsedTime(retryInSeconds) activityExplanation += activity.resources.getString( R.string.trans_retry_in, formattedTime ) } } else if (ERR_GIVEUP_DOWNLOAD.status == transferStatus || ERR_GIVEUP_UPLOAD.status == transferStatus) { activityStatus += activity.resources.getString(R.string.trans_failed) } else { activityStatus += if (BOINCActivity.monitor!!.networkSuspendReason != 0) { activity.resources.getString(R.string.trans_suspended) } else { if (transfersActive) { activity.resources.getString(R.string.trans_active) } else { activity.resources.getString(R.string.trans_pending) } } } transfersString += activity.resources.getString(R.string.tab_transfers) + " " + activityStatus + " " + numberTransfersString + " " + activityExplanation tvTransfers.visibility = View.VISIBLE tvTransfers.text = transfersString } else { // no ongoing transfers tvTransfers.visibility = View.GONE } // credits val userCredit = data.project!!.userTotalCredit.roundToInt() val hostCredit = data.project!!.hostTotalCredit.roundToInt() (vi.findViewById<View>(R.id.project_credits) as TextView).text = if (hostCredit == userCredit) NumberFormat.getIntegerInstance() .format(hostCredit) else activity.getString( R.string.projects_credits_host_and_user, hostCredit, userCredit ) val tvDiskUsage = vi.findViewById<TextView>(R.id.project_disk_usage) val diskUsage = getDiskUsage(position) tvDiskUsage.text = activity.getString(R.string.projects_disk_usage_with_unit, diskUsage) // server notice val notice = data.lastServerNotice val tvNotice = vi.findViewById<TextView>(R.id.project_notice) if (notice == null) { tvNotice.visibility = View.GONE } else { tvNotice.visibility = View.VISIBLE val noticeText = notice.description.trim { it <= ' ' } tvNotice.text = noticeText } // icon background val iconBackground = vi.findViewById<RelativeLayout>(R.id.icon_background) if (data.project!!.attachedViaAcctMgr) { val background = AppCompatResources.getDrawable( activity.applicationContext, R.drawable.shape_boinc_icon_light_blue_background ) iconBackground.background = background } else { iconBackground.setBackgroundColor( ContextCompat.getColor( activity.applicationContext, color.transparent ) ) } } return vi } }
lgpl-3.0
bce0721ca154c6fe69c7a72be58c6ab9
39.578275
120
0.56216
5.115183
false
false
false
false
dsmiley/hhypermap-bop
bop-core/ingest/src/test/kotlin/edu/harvard/gis/hhypermap/bop/ingest/TestIngest.kt
2
6523
/* * Copyright 2016 President and Fellows of Harvard College * * 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 edu.harvard.gis.hhypermap.bop.ingest import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import org.junit.Test import java.util.* import kotlin.test.assertEquals class TestIngest { @Test fun testTransform() { val input = """{ "contributors": null, "truncated": false, "text": "Can you recommend anyone for this #job in ? https://t.co/LYiQrBd7i4 #Healthcare #Hiring #CareerArc", "is_quote_status": false, "in_reply_to_status_id": null, "id": 786254188132962300, "favorite_count": 0, "source": "<a href=\"http://www.tweetmyjobs.com\" rel=\"nofollow\">TweetMyJOBS</a>", "retweeted": false, "coordinates": { "type": "Point", "coordinates": [ -121.7680088, 37.6818745 ] }, "timestamp_ms": "1476292581004", "entities": { "user_mentions": [], "symbols": [], "hashtags": [ { "indices": [ 34, 38 ], "text": "job" }, { "indices": [ 68, 79 ], "text": "Healthcare" }, { "indices": [ 80, 87 ], "text": "Hiring" }, { "indices": [ 88, 98 ], "text": "CareerArc" } ], "urls": [ { "url": "https://t.co/LYiQrBd7i4", "indices": [ 44, 67 ], "expanded_url": "http://bit.ly/2c2LZg4", "display_url": "bit.ly/2c2LZg4" } ] }, "in_reply_to_screen_name": null, "id_str": "786254188132962304", "retweet_count": 0, "in_reply_to_user_id": null, "favorited": false, "user": { "follow_request_sent": null, "profile_use_background_image": true, "default_profile_image": false, "id": 21712764, "verified": false, "profile_image_url_https": "https://pbs.twimg.com/profile_images/668671014188945408/YCpTfOfI_normal.jpg", "profile_sidebar_fill_color": "407DB0", "profile_text_color": "000000", "followers_count": 464, "profile_sidebar_border_color": "000000", "id_str": "21712764", "profile_background_color": "253956", "listed_count": 117, "profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/315559631/Twitter-BG_2_bg-image.jpg", "utc_offset": -14400, "statuses_count": 505, "description": "Follow this account for geo-targeted Healthcare job tweets in San Jose, CA. Need help? Tweet us at @CareerArc!", "friends_count": 306, "location": "San Jose, CA", "profile_link_color": "4A913C", "profile_image_url": "http://pbs.twimg.com/profile_images/668671014188945408/YCpTfOfI_normal.jpg", "following": null, "geo_enabled": true, "profile_banner_url": "https://pbs.twimg.com/profile_banners/21712764/1448258569", "profile_background_image_url": "http://pbs.twimg.com/profile_background_images/315559631/Twitter-BG_2_bg-image.jpg", "name": "TMJ- SJC Health Jobs", "lang": "en", "profile_background_tile": false, "favourites_count": 0, "screen_name": "tmj_sjc_health", "notifications": null, "url": "http://www.careerarc.com/job-seeker", "created_at": "Tue Feb 24 00:35:43 +0000 2009", "contributors_enabled": false, "time_zone": "Eastern Time (US & Canada)", "protected": false, "default_profile": false, "is_translator": false }, "geo": { "type": "Point", "coordinates": [ 37.6818745, -121.7680088 ] }, "in_reply_to_user_id_str": null, "possibly_sensitive": false, "lang": "en", "created_at": "Wed Oct 12 17:16:21 +0000 2016", "filter_level": "low", "in_reply_to_status_id_str": null, "place": { "full_name": "Livermore, CA", "url": "https://api.twitter.com/1.1/geo/id/159279f05be2ade4.json", "country": "United States", "place_type": "city", "bounding_box": { "type": "Polygon", "coordinates": [ [ [ -121.823726, 37.63653 ], [ -121.823726, 37.730654 ], [ -121.696432, 37.730654 ], [ -121.696432, 37.63653 ] ] ] }, "country_code": "US", "attributes": {}, "id": "159279f05be2ade4", "name": "Livermore" }, "hcga_sentiment": "pos", "hcga_geoadmin_admin2": [ { "id": "244-5-184", "txt": "United States_California_Alameda" } ], "hcga_geoadmin_us_census_tract": [ { "tract": "06001451601" } ], "hcga_geoadmin_us_ma_census_block": [] }""" val jsonObj = ObjectMapper().readValue(input, ObjectNode::class.java) val solrDoc = edu.harvard.gis.hhypermap.bop.ingest.jsonToSolrInputDoc(jsonObj) // Replace Date with millis because the toString test we do next shouldn't be dependent on the // current timezone. solrDoc.get("created_at")?.let { field -> field.setValue( (field.value as Date).time, 1f) } assertEquals("""SolrInputDocument(fields: [id=786254188132962304, created_at=1476292581004, minuteOfDayByUserTimeZone=796, coord=37.6818745,-121.7680088, text=Can you recommend anyone for this #job in ? https://t.co/LYiQrBd7i4 #Healthcare #Hiring #CareerArc, user_name=tmj_sjc_health, lang=en, sentiment_pos=true, geoadmin_admin2_count=1, geoadmin_admin2=/244/5/184, geoadmin_admin2_0_pathdv=/244, geoadmin_admin2_1_pathdv=/244/5, geoadmin_admin2_2_pathdv=/244/5/184, geoadmin_admin2_txt=/United States/California/Alameda, geoadmin_admin2_txt_0_pathdv=/United States, geoadmin_admin2_txt_1_pathdv=/United States/California, geoadmin_admin2_txt_2_pathdv=/United States/California/Alameda, geoadmin_us_census_tract_count=1, geoadmin_us_census_tract=06001451601, geoadmin_us_ma_census_block_count=0])""", solrDoc.toString()) } }
apache-2.0
3c336f12b291a3ec09b853cd3bd1c44d
30.669903
805
0.607083
3.112118
false
false
false
false
Jire/Abendigo
src/main/kotlin/org/abendigo/plugin/csgo/InGamePlugin.kt
2
711
package org.abendigo.plugin.csgo import org.abendigo.DEBUG import org.abendigo.csgo.Engine.clientState import org.abendigo.csgo.GameState import org.abendigo.plugin.CyclePlugin import org.abendigo.plugin.every import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS abstract class InGamePlugin(name: String, duration: Int, durationUnit: TimeUnit = MILLISECONDS) : CyclePlugin(name, duration, durationUnit) { override fun enable() = every(duration, durationUnit) { val gameState = clientState(1024).gameState() if (enabled && GameState.PLAYING == gameState) try { cycle() } catch (t: Throwable) { if (DEBUG) t.printStackTrace() } } }
gpl-3.0
0f331fbc45148357e64e8331d76d190d
29.956522
112
0.74121
3.843243
false
false
false
false
android/health-samples
health-services/PassiveGoals/app/src/main/java/com/example/passivegoals/PassiveGoalsRepository.kt
1
2959
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.passivegoals import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.longPreferencesKey import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.util.TimeZone import javax.inject.Inject /** * Stores the latest information and whether or not passive goals are enabled. */ class PassiveGoalsRepository @Inject constructor( private val dataStore: DataStore<Preferences> ) { companion object { const val PREFERENCES_FILENAME = "passive_goals_prefs" private val LATEST_DAILY_GOAL_ACHIEVED_TIME = longPreferencesKey("latest_daily_goal_time") private val PASSIVE_GOALS_ENABLED = booleanPreferencesKey("passive_goals_enabled") private val LATEST_FLOOR_GOAL_TIME = longPreferencesKey("latest_floor_goal_time") } val passiveGoalsEnabled: Flow<Boolean> = dataStore.data.map { prefs -> prefs[PASSIVE_GOALS_ENABLED] ?: false } suspend fun setPassiveGoalsEnabled(enabled: Boolean) { dataStore.edit { prefs -> prefs[PASSIVE_GOALS_ENABLED] = enabled } } suspend fun setLatestDailyGoalAchieved(timestamp: Instant) { dataStore.edit { prefs -> prefs[LATEST_DAILY_GOAL_ACHIEVED_TIME] = timestamp.toEpochMilli() } } val dailyStepsGoalAchieved: Flow<Boolean> = dataStore.data.map { prefs -> prefs[LATEST_DAILY_GOAL_ACHIEVED_TIME]?.let { val zoneId = TimeZone.getDefault().toZoneId() val achievedDate = LocalDateTime.ofInstant( Instant.ofEpochMilli(it), zoneId ).toLocalDate() achievedDate == LocalDate.now(zoneId) } ?: false } suspend fun updateLatestFloorsGoalTime(timestamp: Instant) { dataStore.edit { prefs -> prefs[LATEST_FLOOR_GOAL_TIME] = timestamp.toEpochMilli() } } val latestFloorsGoalTime: Flow<Instant> = dataStore.data.map { prefs -> val time = prefs[LATEST_FLOOR_GOAL_TIME] ?: 0L Instant.ofEpochMilli(time) } }
apache-2.0
dcc9b529f1be6fd1e087bacc2c0abcbb
34.662651
98
0.703954
4.33871
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/LinkHighlightPreference.kt
1
2511
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.preference import android.content.Context import android.text.SpannableString import android.util.AttributeSet import de.vanita5.twittnuker.R import de.vanita5.twittnuker.constant.SharedPreferenceConstants.* import de.vanita5.twittnuker.text.TwidereHighLightStyle class LinkHighlightPreference( context: Context, attrs: AttributeSet? ) : EntrySummaryListPreference(context, attrs) { init { entries = Array<CharSequence>(VALUES.size) { i -> getStyledEntry(OPTIONS[i], context.getString(ENTRIES_RES[i])) } entryValues = VALUES } companion object { private val ENTRIES_RES = intArrayOf( R.string.none, R.string.highlight, R.string.underline, R.string.highlight_and_underline ) private val VALUES = arrayOf( VALUE_LINK_HIGHLIGHT_OPTION_NONE, VALUE_LINK_HIGHLIGHT_OPTION_HIGHLIGHT, VALUE_LINK_HIGHLIGHT_OPTION_UNDERLINE, VALUE_LINK_HIGHLIGHT_OPTION_BOTH ) private val OPTIONS = intArrayOf( VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE, VALUE_LINK_HIGHLIGHT_OPTION_CODE_HIGHLIGHT, VALUE_LINK_HIGHLIGHT_OPTION_CODE_UNDERLINE, VALUE_LINK_HIGHLIGHT_OPTION_CODE_BOTH ) private fun getStyledEntry(option: Int, entry: CharSequence): CharSequence { val str = SpannableString(entry) str.setSpan(TwidereHighLightStyle(option), 0, str.length, 0) return str } } }
gpl-3.0
bcb9c3bc3383d8a33d95809e4884f280
34.885714
84
0.670649
4.413005
false
false
false
false
AlexLandau/semlang
kotlin/sem2-lang/src/main/kotlin/sem2.kt
1
15253
package net.semlang.sem2.api import net.semlang.api.parser.Location data class S2ModuleRef(val group: String?, val module: String, val version: String?) { init { if (group == null && version != null) { error("Version may not be set unless group is also set") } } override fun toString(): String { if (version != null) { return "$group:$module:$version" } else if (group != null) { return "$group:$module" } else { return module } } } // An EntityId uniquely identifies an entity within a module. An EntityRef refers to an entity that may be in this // module or another, and may or may not have hints pointing to a particular module. // TODO: Use a common type across dialects data class EntityId(val namespacedName: List<String>) { init { if (namespacedName.isEmpty()) { error("Entity IDs must have at least one name component") } for (namePart in namespacedName) { if (namePart.isEmpty()) { error("Entity IDs may not have empty name components") } var foundNonUnderscore = false for (character in namePart) { if (character in 'a'..'z' || character in 'A'..'Z' || character in '0'..'9') { foundNonUnderscore = true } else if (character == '_') { // Do nothing } else { error("Invalid character '$character' (code: ${character.toInt()}) in entity ID with components $namespacedName") } } if (!foundNonUnderscore) { error("Name components must contain non-underscore characters; bad entity ID components: $namespacedName") } } } companion object { fun of(vararg names: String): EntityId { return EntityId(names.toList()) } /** * Parses the components of an entity ID expressed as a period-delimited string. In particular, this reverses * the [EntityId.toString] operation. */ fun parse(periodDelimitedNames: String): EntityId { return EntityId(periodDelimitedNames.split(".")) } } override fun toString(): String { return namespacedName.joinToString(".") } /** * Returns an EntityRef with this identity and no module hints. */ fun asRef(): EntityRef { return EntityRef(null, this) } } /** * Note: These should usually not be used as keys in a map; use ResolvedEntityRefs from an EntityResolver instead. */ data class EntityRef(val moduleRef: S2ModuleRef?, val id: EntityId) { companion object { fun of(vararg names: String): EntityRef { return EntityRef(null, EntityId.of(*names)) } } override fun toString(): String { if (moduleRef != null) { return moduleRef.toString() + ":" + id.toString() } else { return id.toString() } } } sealed class S2Type { abstract val location: Location? abstract protected fun getTypeString(): String abstract fun replacingNamedParameterTypes(parameterReplacementMap: Map<String, S2Type>): S2Type override fun toString(): String { return getTypeString() } data class FunctionType(val isReference: kotlin.Boolean, val typeParameters: kotlin.collections.List<TypeParameter>, val argTypes: kotlin.collections.List<S2Type>, val outputType: S2Type, override val location: Location? = null): S2Type() { override fun replacingNamedParameterTypes(parameterReplacementMap: Map<String, S2Type>): S2Type { return FunctionType( isReference, typeParameters, this.argTypes.map { it.replacingNamedParameterTypes(parameterReplacementMap) }, this.outputType.replacingNamedParameterTypes(parameterReplacementMap), location) } override fun getTypeString(): String { val referenceString = if (isReference) "&" else "" val typeParametersString = if (typeParameters.isEmpty()) { "" } else { "<" + typeParameters.joinToString(", ") + ">" } return referenceString + typeParametersString + "(" + argTypes.joinToString(", ") + ") -> " + outputType.toString() } override fun toString(): String { return getTypeString() } } data class NamedType(val ref: EntityRef, val isReference: kotlin.Boolean, val parameters: kotlin.collections.List<S2Type> = listOf(), override val location: Location? = null): S2Type() { override fun replacingNamedParameterTypes(parameterReplacementMap: Map<String, S2Type>): S2Type { if (ref.moduleRef == null && ref.id.namespacedName.size == 1) { val replacement = parameterReplacementMap[ref.id.namespacedName[0]] if (replacement != null) { return replacement } } return NamedType( ref, isReference, parameters.map { it.replacingNamedParameterTypes(parameterReplacementMap) }, location) } companion object { fun forParameter(parameter: TypeParameter, location: Location? = null): NamedType { return NamedType(EntityRef(null, EntityId(listOf(parameter.name))), false, listOf(), location) } } override fun getTypeString(): String { // TODO: This might be wrong if the ref includes a module... return (if (isReference) "&" else "") + ref.toString() + if (parameters.isEmpty()) { "" } else { "<" + parameters.joinToString(", ") + ">" } } override fun toString(): String { return getTypeString() } } } enum class TypeClass { Data, } data class TypeParameter(val name: String, val typeClass: TypeClass?) { override fun toString(): String { if (typeClass == null) { return name } else { return "$name: $typeClass" } } } data class S2FunctionSignature(override val id: EntityId, val argumentTypes: List<S2Type>, val outputType: S2Type, val typeParameters: List<TypeParameter> = listOf()): HasId { fun getFunctionType(): S2Type.FunctionType { return S2Type.FunctionType(false, typeParameters, argumentTypes, outputType) } } data class S2Annotation(val name: EntityId, val values: List<S2AnnotationArgument>) sealed class S2AnnotationArgument { data class Literal(val value: String): S2AnnotationArgument() data class List(val values: kotlin.collections.List<S2AnnotationArgument>): S2AnnotationArgument() } sealed class S2Expression { abstract val location: Location? data class RawId(val name: String, override val location: Location? = null): S2Expression() data class DotAccess(val subexpression: S2Expression, val name: String, override val location: Location? = null, val nameLocation: Location? = null): S2Expression() data class IfThen(val condition: S2Expression, val thenBlock: S2Block, val elseBlock: S2Block, override val location: Location? = null): S2Expression() data class FunctionCall(val expression: S2Expression, val arguments: List<S2Expression>, val chosenParameters: List<S2Type>, override val location: Location? = null): S2Expression() data class Literal(val type: S2Type, val literal: String, override val location: Location? = null): S2Expression() data class IntegerLiteral(val literal: String, override val location: Location? = null): S2Expression() data class ListLiteral(val contents: List<S2Expression>, val chosenParameter: S2Type, override val location: Location? = null): S2Expression() data class FunctionBinding(val expression: S2Expression, val bindings: List<S2Expression?>, val chosenParameters: List<S2Type?>, override val location: Location? = null): S2Expression() data class Follow(val structureExpression: S2Expression, val name: String, override val location: Location? = null): S2Expression() data class InlineFunction(val arguments: List<S2Argument>, val returnType: S2Type?, val block: S2Block, override val location: Location? = null): S2Expression() data class PlusOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class MinusOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class TimesOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class EqualsOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class NotEqualsOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class LessThanOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class GreaterThanOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class DotAssignOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class GetOp(val subject: S2Expression, val arguments: List<S2Expression>, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class AndOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() data class OrOp(val left: S2Expression, val right: S2Expression, override val location: Location? = null, val operatorLocation: Location? = null): S2Expression() } sealed class S2Statement { data class Assignment(val name: String, val type: S2Type?, val expression: S2Expression, val location: Location? = null, val nameLocation: Location? = null): S2Statement() data class Bare(val expression: S2Expression, val location: Location? = null): S2Statement() data class WhileLoop(val conditionExpression: S2Expression, val actionBlock: S2Block, val location: Location? = null): S2Statement() } data class S2Argument(val name: String, val type: S2Type, val location: Location? = null) data class S2Block(val statements: List<S2Statement>, val location: Location? = null) data class S2Function(override val id: EntityId, val typeParameters: List<TypeParameter>, val arguments: List<S2Argument>, val returnType: S2Type, val block: S2Block, override val annotations: List<S2Annotation>, val idLocation: Location? = null, val returnTypeLocation: Location? = null) : TopLevelEntity { fun getType(): S2Type.FunctionType { return S2Type.FunctionType( false, typeParameters, arguments.map(S2Argument::type), returnType ) } fun getSignature(): S2FunctionSignature { return S2FunctionSignature(id, arguments.map { it.type }, returnType, typeParameters) } } data class S2Struct(override val id: EntityId, val typeParameters: List<TypeParameter>, val members: List<S2Member>, val requires: S2Block?, override val annotations: List<S2Annotation>, val idLocation: Location? = null) : TopLevelEntity { fun getConstructorSignature(): S2FunctionSignature { val argumentTypes = members.map(S2Member::type) val typeParameters = typeParameters.map { S2Type.NamedType.forParameter(it, idLocation) } val outputType = if (requires == null) { S2Type.NamedType(id.asRef(), false, typeParameters, idLocation) } else { S2Type.NamedType(id.asRef(), false, listOf( S2Type.NamedType(id.asRef(), false, typeParameters, idLocation) ), idLocation) } return S2FunctionSignature(id, argumentTypes, outputType, this.typeParameters) } } interface HasId { val id: EntityId } interface TopLevelEntity: HasId { val annotations: List<S2Annotation> } data class S2Member(val name: String, val type: S2Type) data class S2Union(override val id: EntityId, val typeParameters: List<TypeParameter>, val options: List<S2Option>, override val annotations: List<S2Annotation>, val idLocation: Location? = null): TopLevelEntity { private fun getType(): S2Type { val functionParameters = typeParameters.map { S2Type.NamedType.forParameter(it) } return S2Type.NamedType(id.asRef(), false, functionParameters) } fun getConstructorSignature(option: S2Option): S2FunctionSignature { if (!options.contains(option)) { error("Invalid option $option") } val optionId = EntityId(id.namespacedName + option.name) val argumentTypes = if (option.type == null) { listOf() } else { listOf(option.type) } return S2FunctionSignature(optionId, argumentTypes, getType(), typeParameters) } fun getWhenSignature(): S2FunctionSignature { val whenId = EntityId(id.namespacedName + "when") val outputParameterName = getUnusedTypeParameterName(typeParameters) val outputParameterType = S2Type.NamedType(EntityId.of(outputParameterName).asRef(), false) val outputTypeParameter = TypeParameter(outputParameterName, null) val whenTypeParameters = typeParameters + outputTypeParameter val argumentTypes = listOf(getType()) + options.map { option -> val optionArgTypes = if (option.type == null) { listOf() } else { listOf(option.type) } S2Type.FunctionType(false, listOf(), optionArgTypes, outputParameterType) } return S2FunctionSignature(whenId, argumentTypes, outputParameterType, whenTypeParameters) } } data class S2Option(val name: String, val type: S2Type?, val idLocation: Location? = null) private fun getUnusedTypeParameterName(explicitTypeParameters: List<TypeParameter>): String { val typeParameterNames = explicitTypeParameters.map(TypeParameter::name) if (!typeParameterNames.contains("A")) { return "A" } var index = 2 while (true) { val name = "A" + index if (!typeParameterNames.contains(name)) { return name } index++ } } data class S2Context(val functions: List<S2Function>, val structs: List<S2Struct>, val unions: List<S2Union>)
apache-2.0
3c4d7876c4e59e56dac35f5150d65fde
46.517134
307
0.652724
4.52477
false
false
false
false
stripe/stripe-android
link/src/main/java/com/stripe/android/link/ui/paymentmethod/SupportedPaymentMethod.kt
1
2772
package com.stripe.android.link.ui.paymentmethod import android.content.res.Resources import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.stripe.android.link.R import com.stripe.android.link.ui.completePaymentButtonLabel import com.stripe.android.model.ConsumerPaymentDetails import com.stripe.android.model.StripeIntent import com.stripe.android.ui.core.elements.FormItemSpec import com.stripe.android.ui.core.forms.LinkCardForm /** * Represents the Payment Methods that are supported by Link. * * @param type The Payment Method type. Matches the [ConsumerPaymentDetails] types. * @param formSpec Specification of how the payment method data collection UI should look. * @param nameResourceId String resource id for the name of this payment method. * @param iconResourceId Drawable resource id for the icon representing this payment method. * @param primaryButtonStartIconResourceId Drawable resource id for the icon to be displayed at the * start of the primary button when this payment method is being created. * @param primaryButtonEndIconResourceId Drawable resource id for the icon to be displayed at the * end of the primary button when this payment method is being created. */ internal enum class SupportedPaymentMethod( val type: String, val formSpec: List<FormItemSpec>, @StringRes val nameResourceId: Int, @DrawableRes val iconResourceId: Int, @DrawableRes val primaryButtonStartIconResourceId: Int? = null, @DrawableRes val primaryButtonEndIconResourceId: Int? = null ) { Card( ConsumerPaymentDetails.Card.type, LinkCardForm.items, R.string.stripe_paymentsheet_payment_method_card, R.drawable.ic_link_card, primaryButtonEndIconResourceId = R.drawable.stripe_ic_lock ) { override fun primaryButtonLabel( stripeIntent: StripeIntent, resources: Resources ) = completePaymentButtonLabel(stripeIntent, resources) }, BankAccount( ConsumerPaymentDetails.BankAccount.type, emptyList(), R.string.stripe_payment_method_bank, R.drawable.ic_link_bank, primaryButtonStartIconResourceId = R.drawable.ic_link_add ) { override fun primaryButtonLabel( stripeIntent: StripeIntent, resources: Resources ) = resources.getString(R.string.add_bank_account) }; val showsForm = formSpec.isNotEmpty() /** * The label for the primary button when this payment method is being created. */ abstract fun primaryButtonLabel( stripeIntent: StripeIntent, resources: Resources ): String internal companion object { val allTypes = values().map { it.type }.toSet() } }
mit
48e94b3d2bc3f4a97e3b60ddcd89051b
38.042254
99
0.729798
4.544262
false
false
false
false
slartus/4pdaClient-plus
core/src/main/java/org/softeg/slartus/forpdaplus/core/entities/SearchSettings.kt
1
732
package org.softeg.slartus.forpdaplus.core.entities data class SearchSettings( val query: String? = null, val userName: String? = null, val searchType: SearchType = SearchType.Forum, val searchInSubForums: Boolean = true, val resultView: ResultView = ResultView.Posts, val sortType: SortType = SortType.DateDesc, val sourceType: SourceType = SourceType.All, val topicIds: Set<String> = emptySet(), val forumIds: Set<String> ) { enum class SearchType { Forum, Topic, UserTopics, UserPosts } enum class ResultView { Topics, Posts } enum class SortType { Relevant, DateAsc, DateDesc } enum class SourceType { All, Topics, Posts } }
apache-2.0
752ba2e5caf7fbf915a03050a506f1ee
24.275862
51
0.661202
4.159091
false
false
false
false
AndroidX/androidx
wear/watchface/watchface-complications-rendering/src/test/java/androidx/wear/watchface/complications/rendering/CanvasComplicationDrawableTest.kt
3
5529
/* * 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.watchface.complications.rendering import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Rect import androidx.test.core.app.ApplicationProvider import androidx.wear.watchface.CanvasComplication import androidx.wear.watchface.DrawMode import androidx.wear.watchface.MutableWatchState import androidx.wear.watchface.RenderParameters import androidx.wear.watchface.TapEvent import androidx.wear.watchface.style.WatchFaceLayer import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import java.time.Instant import java.time.ZoneId import java.time.ZonedDateTime @RunWith(ComplicationsTestRunner::class) public class CanvasComplicationDrawableTest { private val complicationDrawable = ComplicationDrawable(ApplicationProvider.getApplicationContext()) private val watchState = MutableWatchState() private val invalidateCallback = Mockito.mock(CanvasComplication.InvalidateCallback::class.java) private val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888) private val bounds = Rect(0, 0, 100, 100) private val canvas = Canvas(bitmap) private val zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(1234), ZoneId.of("UTC")) private val canvasComplicationDrawable = CanvasComplicationDrawable( complicationDrawable, watchState.asWatchState(), invalidateCallback ) private val slotId = 100 @Test public fun render_ambientMode() { canvasComplicationDrawable.render( canvas, bounds, zonedDateTime, RenderParameters( DrawMode.AMBIENT, setOf(WatchFaceLayer.BASE, WatchFaceLayer.COMPLICATIONS), null, emptyMap() ), slotId ) assertThat(complicationDrawable.isInAmbientMode).isTrue() canvasComplicationDrawable.render( canvas, bounds, zonedDateTime, RenderParameters( DrawMode.INTERACTIVE, setOf(WatchFaceLayer.BASE, WatchFaceLayer.COMPLICATIONS), null, emptyMap() ), slotId ) assertThat(complicationDrawable.isInAmbientMode).isFalse() } @Test public fun render_bounds() { canvasComplicationDrawable.render( canvas, bounds, zonedDateTime, RenderParameters( DrawMode.INTERACTIVE, setOf(WatchFaceLayer.BASE, WatchFaceLayer.COMPLICATIONS), null, emptyMap() ), slotId ) assertThat(complicationDrawable.bounds).isEqualTo(bounds) } @Test public fun render_currentTimeMillis() { canvasComplicationDrawable.render( canvas, bounds, zonedDateTime, RenderParameters( DrawMode.INTERACTIVE, setOf(WatchFaceLayer.BASE, WatchFaceLayer.COMPLICATIONS), null, emptyMap() ), slotId ) assertThat(complicationDrawable.currentTime.toEpochMilli()).isEqualTo(1234) } @Test public fun render_highlight() { val renderParameters = RenderParameters( DrawMode.INTERACTIVE, setOf(WatchFaceLayer.BASE, WatchFaceLayer.COMPLICATIONS), null, mapOf(slotId to TapEvent(50, 50, Instant.ofEpochMilli(1100))) ) val t1099 = ZonedDateTime.ofInstant(Instant.ofEpochMilli(1099), ZoneId.of("UTC")) canvasComplicationDrawable.render(canvas, bounds, t1099, renderParameters, slotId) assertThat(complicationDrawable.isHighlighted).isFalse() val t1100 = ZonedDateTime.ofInstant(Instant.ofEpochMilli(1100), ZoneId.of("UTC")) canvasComplicationDrawable.render(canvas, bounds, t1100, renderParameters, slotId) assertThat(complicationDrawable.isHighlighted).isTrue() val t1099_plus = ZonedDateTime.ofInstant( Instant.ofEpochMilli( 1099 + CanvasComplicationDrawable.COMPLICATION_HIGHLIGHT_DURATION_MS ), ZoneId.of("UTC") ) canvasComplicationDrawable.render(canvas, bounds, t1099_plus, renderParameters, slotId) assertThat(complicationDrawable.isHighlighted).isTrue() val t1100_plus = ZonedDateTime.ofInstant( Instant.ofEpochMilli( 1100 + CanvasComplicationDrawable.COMPLICATION_HIGHLIGHT_DURATION_MS ), ZoneId.of("UTC") ) canvasComplicationDrawable.render(canvas, bounds, t1100_plus, renderParameters, slotId) assertThat(complicationDrawable.isHighlighted).isFalse() } }
apache-2.0
6f1add037cf16ede90682378b9176c01
34.442308
100
0.664858
5.067828
false
true
false
false
AndroidX/androidx
compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/inspector/ParameterFactory.kt
3
43122
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.inspection.inspector import java.lang.reflect.Modifier as JavaModifier import android.util.Log import android.view.View import androidx.compose.runtime.internal.ComposableLambda import androidx.compose.ui.AbsoluteAlignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.inspection.inspector.ParameterType.DimensionDp import androidx.compose.ui.platform.InspectableModifier import androidx.compose.ui.platform.InspectableValue import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontListFontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.ResourceFont import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import java.lang.reflect.Field import java.util.IdentityHashMap import kotlin.jvm.internal.FunctionReference import kotlin.jvm.internal.Lambda import kotlin.math.abs import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 import kotlin.reflect.full.allSuperclasses import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.javaField import kotlin.reflect.jvm.javaGetter private val reflectionScope: ReflectionScope = ReflectionScope() /** * Factory of [NodeParameter]s. * * Each parameter value is converted to a user readable value. */ internal class ParameterFactory(private val inlineClassConverter: InlineClassConverter) { /** * A map from known values to a user readable string representation. */ private val valueLookup = mutableMapOf<Any, String>() /** * The classes we have loaded constants from. */ private val valuesLoaded = mutableSetOf<Class<*>>() /** * Do not load constant names from instances of these classes. * We prefer showing the raw values of Color and Dimensions. */ private val ignoredClasses = listOf(Color::class.java, Dp::class.java) private var creatorCache: ParameterCreator? = null /** * Do not decompose instances or lookup constants from these package prefixes * * The following instances are known to contain self recursion: * - kotlinx.coroutines.flow.StateFlowImpl * - androidx.compose.ui.node.LayoutNode */ private val ignoredPackagePrefixes = listOf( "android.", "java.", "javax.", "kotlinx.", "androidx.compose.ui.node." ) var density = Density(1.0f) init { val textDecorationCombination = TextDecoration.combine( listOf(TextDecoration.LineThrough, TextDecoration.Underline) ) valueLookup[textDecorationCombination] = "LineThrough+Underline" valueLookup[Color.Unspecified] = "Unspecified" valueLookup[RectangleShape] = "RectangleShape" valuesLoaded.add(Enum::class.java) valuesLoaded.add(Any::class.java) // AbsoluteAlignment is not found from an instance of BiasAbsoluteAlignment, // because Alignment has no file level class. reflectionScope.withReflectiveAccess { loadConstantsFromEnclosedClasses(AbsoluteAlignment::class.java) } } /** * Create a [NodeParameter] from the specified parameter [name] and [value]. * * Attempt to convert the value to a user readable value. * For now: return null when a conversion is not possible/found. */ fun create( rootId: Long, nodeId: Long, anchorId: Int, name: String, value: Any?, kind: ParameterKind, parameterIndex: Int, maxRecursions: Int, maxInitialIterableSize: Int ): NodeParameter { val creator = creatorCache ?: ParameterCreator() try { return reflectionScope.withReflectiveAccess { creator.create( rootId, nodeId, anchorId, name, value, kind, parameterIndex, maxRecursions, maxInitialIterableSize ) } } finally { creatorCache = creator } } /** * Create/expand the [NodeParameter] specified by [reference]. * * @param rootId is the root id of the specified [nodeId]. * @param nodeId is the [InspectorNode.id] of the node the parameter belongs to. * @param anchorId is the [InspectorNode.anchorId] of the node the parameter belongs to. * @param name is the name of the [reference].parameterIndex'th parameter of the node. * @param value is the value of the [reference].parameterIndex'th parameter of the node. * @param startIndex is the index of the 1st wanted element of a List/Array. * @param maxElements is the max number of elements wanted from a List/Array. * @param maxRecursions is the max recursion into composite types starting from reference. * @param maxInitialIterableSize is the max number of elements wanted in new List/Array values. */ fun expand( rootId: Long, nodeId: Long, anchorId: Int, name: String, value: Any?, reference: NodeParameterReference, startIndex: Int, maxElements: Int, maxRecursions: Int, maxInitialIterableSize: Int ): NodeParameter? { val creator = creatorCache ?: ParameterCreator() try { return reflectionScope.withReflectiveAccess { creator.expand( rootId, nodeId, anchorId, name, value, reference, startIndex, maxElements, maxRecursions, maxInitialIterableSize ) } } finally { creatorCache = creator } } fun clearReferenceCache() { val creator = creatorCache ?: return creator.clearReferenceCache() } private fun loadConstantsFrom(javaClass: Class<*>) { if (valuesLoaded.contains(javaClass) || ignoredPackagePrefixes.any { javaClass.name.startsWith(it) } ) { return } val related = generateSequence(javaClass) { it.superclass }.plus(javaClass.interfaces) related.forEach { aClass -> val topClass = generateSequence(aClass) { safeEnclosingClass(it) }.last() loadConstantsFromEnclosedClasses(topClass) findPackageLevelClass(topClass)?.let { loadConstantsFromStaticFinal(it) } } } private fun safeEnclosingClass(klass: Class<*>): Class<*>? = try { klass.enclosingClass } catch (_: Error) { // Exceptions seen on API 23... null } private fun findPackageLevelClass(javaClass: Class<*>): Class<*>? = try { // Note: This doesn't work when @file.JvmName is specified Class.forName("${javaClass.name}Kt") } catch (ex: Throwable) { null } private fun loadConstantsFromEnclosedClasses(javaClass: Class<*>) { if (valuesLoaded.contains(javaClass)) { return } loadConstantsFromObjectInstance(javaClass.kotlin) loadConstantsFromStaticFinal(javaClass) valuesLoaded.add(javaClass) javaClass.declaredClasses.forEach { loadConstantsFromEnclosedClasses(it) } } /** * Load all constants from companion objects and singletons * * Exclude: primary types and types of ignoredClasses, open and lateinit vals. */ private fun loadConstantsFromObjectInstance(kClass: KClass<*>) { try { val instance = kClass.objectInstance ?: return kClass.declaredMemberProperties.asSequence() .filter { it.isFinal && !it.isLateinit } .mapNotNull { constantValueOf(it, instance)?.let { key -> Pair(key, it.name) } } .filter { !ignoredValue(it.first) } .toMap(valueLookup) } catch (_: Throwable) { // KT-16479 : kotlin reflection does currently not support packages and files. // We load top level values using Java reflection instead. // Ignore other reflection errors as well } } /** * Load all constants from top level values from Java. * * Exclude: primary types and types of ignoredClasses. * Since this is Java, inline types will also (unfortunately) be excluded. */ private fun loadConstantsFromStaticFinal(javaClass: Class<*>) { try { javaClass.declaredMethods.asSequence() .filter { it.returnType != Void.TYPE && JavaModifier.isStatic(it.modifiers) && JavaModifier.isFinal(it.modifiers) && !it.returnType.isPrimitive && it.parameterTypes.isEmpty() && it.name.startsWith("get") } .mapNotNull { javaClass.getDeclaredField(it.name.substring(3)) } .mapNotNull { constantValueOf(it)?.let { key -> Pair(key, it.name) } } .filter { !ignoredValue(it.first) } .toMap(valueLookup) } catch (_: ReflectiveOperationException) { // ignore reflection errors } catch (_: NoClassDefFoundError) { // ignore missing classes on lower level SDKs } } private fun constantValueOf(field: Field?): Any? = try { field?.isAccessible = true field?.get(null) } catch (_: ReflectiveOperationException) { // ignore reflection errors null } private fun constantValueOf(property: KProperty1<out Any, *>, instance: Any): Any? = try { val field = property.javaField field?.isAccessible = true inlineClassConverter.castParameterValue(inlineResultClass(property), field?.get(instance)) } catch (_: ReflectiveOperationException) { // ignore reflection errors null } private fun inlineResultClass(property: KProperty1<out Any, *>): String? { // The Java getter name will be mangled if it contains parameters of an inline class. // The mangled part starts with a '-'. if (property.javaGetter?.name?.contains('-') == true) { return property.returnType.toString() } return null } private fun ignoredValue(value: Any?): Boolean = value == null || ignoredClasses.any { ignored -> ignored.isInstance(value) } || value::class.java.isPrimitive /** * Convenience class for building [NodeParameter]s. */ private inner class ParameterCreator { private var rootId = 0L private var nodeId = 0L private var anchorId = 0 private var kind: ParameterKind = ParameterKind.Normal private var parameterIndex = 0 private var maxRecursions = 0 private var maxInitialIterableSize = 0 private var recursions = 0 private val valueIndex = mutableListOf<Int>() private val valueLazyReferenceMap = IdentityHashMap<Any, MutableList<NodeParameter>>() private val rootValueIndexCache = mutableMapOf<Long, IdentityHashMap<Any, NodeParameterReference>>() private var valueIndexMap = IdentityHashMap<Any, NodeParameterReference>() fun create( rootId: Long, nodeId: Long, anchorId: Int, name: String, value: Any?, kind: ParameterKind, parameterIndex: Int, maxRecursions: Int, maxInitialIterableSize: Int ): NodeParameter = try { setup( rootId, nodeId, anchorId, kind, parameterIndex, maxRecursions, maxInitialIterableSize ) create(name, value, null) ?: createEmptyParameter(name) } finally { setup() } fun expand( rootId: Long, nodeId: Long, anchorId: Int, name: String, value: Any?, reference: NodeParameterReference, startIndex: Int, maxElements: Int, maxRecursions: Int, maxInitialIterableSize: Int ): NodeParameter? { setup( rootId, nodeId, anchorId, reference.kind, reference.parameterIndex, maxRecursions, maxInitialIterableSize ) var parent: Pair<String, Any?>? = null var new = Pair(name, value) for (i in reference.indices) { parent = new new = find(new.first, new.second, i) ?: return null } recursions = 0 valueIndex.addAll(reference.indices.asSequence()) val parameter = if (startIndex == 0) { create(new.first, new.second, parent?.second) } else { createFromCompositeValue( new.first, new.second, parent?.second, startIndex, maxElements ) } if (parameter == null && reference.indices.isEmpty()) { return createEmptyParameter(name) } return parameter } fun clearReferenceCache() { rootValueIndexCache.clear() } private fun setup( newRootId: Long = 0, newNodeId: Long = 0, newAnchorId: Int = 0, newKind: ParameterKind = ParameterKind.Normal, newParameterIndex: Int = 0, maxRecursions: Int = 0, maxInitialIterableSize: Int = 0 ) { rootId = newRootId nodeId = newNodeId anchorId = newAnchorId kind = newKind parameterIndex = newParameterIndex this.maxRecursions = maxRecursions this.maxInitialIterableSize = maxInitialIterableSize recursions = 0 valueIndex.clear() valueLazyReferenceMap.clear() valueIndexMap = rootValueIndexCache.getOrPut(newRootId) { IdentityHashMap() } } private fun create(name: String, value: Any?, parentValue: Any?): NodeParameter? { if (value == null) { return null } createFromSimpleValue(name, value)?.let { return it } val existing = valueIndexMap[value] ?: return createFromCompositeValue(name, value, parentValue) // Do not decompose an instance we already decomposed. // Instead reference the data that was already decomposed. return createReferenceToExistingValue(name, value, parentValue, existing) } private fun create( name: String, value: Any?, parentValue: Any?, specifiedIndex: Int = 0 ): NodeParameter? = create(name, value, parentValue)?.apply { index = specifiedIndex } private fun createFromSimpleValue(name: String, value: Any?): NodeParameter? { if (value == null) { return null } createFromConstant(name, value)?.let { return it } return when (value) { is AnnotatedString -> NodeParameter(name, ParameterType.String, value.text) is BaselineShift -> createFromBaselineShift(name, value) is Boolean -> NodeParameter(name, ParameterType.Boolean, value) is ComposableLambda -> createFromCLambda(name, value) is Color -> NodeParameter(name, ParameterType.Color, value.toArgb()) is Double -> NodeParameter(name, ParameterType.Double, value) is Dp -> NodeParameter(name, DimensionDp, value.value) is Enum<*> -> NodeParameter(name, ParameterType.String, value.toString()) is Float -> NodeParameter(name, ParameterType.Float, value) is FunctionReference -> createFromFunctionReference(name, value) is FontListFontFamily -> createFromFontListFamily(name, value) is FontWeight -> NodeParameter(name, ParameterType.Int32, value.weight) is Int -> NodeParameter(name, ParameterType.Int32, value) is Lambda<*> -> createFromLambda(name, value) is Locale -> NodeParameter(name, ParameterType.String, value.toString()) is Long -> NodeParameter(name, ParameterType.Int64, value) is SolidColor -> NodeParameter(name, ParameterType.Color, value.value.toArgb()) is String -> NodeParameter(name, ParameterType.String, value) is TextUnit -> createFromTextUnit(name, value) is ImageVector -> createFromImageVector(name, value) is View -> NodeParameter(name, ParameterType.String, value.javaClass.simpleName) else -> null } } private fun createFromCompositeValue( name: String, value: Any?, parentValue: Any?, startIndex: Int = 0, maxElements: Int = maxInitialIterableSize ): NodeParameter? = when { value == null -> null value is Modifier -> createFromModifier(name, value) value is InspectableValue -> createFromInspectableValue(name, value) value is Sequence<*> -> createFromSequence(name, value, value, startIndex, maxElements) value is Map<*, *> -> createFromSequence(name, value, value.asSequence(), startIndex, maxElements) value is Map.Entry<*, *> -> createFromMapEntry(name, value, parentValue) value is Iterable<*> -> createFromSequence(name, value, value.asSequence(), startIndex, maxElements) value.javaClass.isArray -> createFromArray(name, value, startIndex, maxElements) value is Offset -> createFromOffset(name, value) value is Shadow -> createFromShadow(name, value) value is TextStyle -> createFromTextStyle(name, value) else -> createFromKotlinReflection(name, value) } private fun find(name: String, value: Any?, index: Int): Pair<String, Any?>? = when { value == null -> null value is Modifier -> findFromModifier(name, value, index) value is InspectableValue -> findFromInspectableValue(value, index) value is Sequence<*> -> findFromSequence(value, index) value is Map<*, *> -> findFromSequence(value.asSequence(), index) value is Map.Entry<*, *> -> findFromMapEntry(value, index) value is Iterable<*> -> findFromSequence(value.asSequence(), index) value.javaClass.isArray -> findFromArray(value, index) value is Offset -> findFromOffset(value, index) value is Shadow -> findFromShadow(value, index) value is TextStyle -> findFromTextStyle(value, index) else -> findFromKotlinReflection(value, index) } private fun createRecursively( name: String, value: Any?, parentValue: Any?, index: Int ): NodeParameter? { valueIndex.add(index) recursions++ val parameter = create(name, value, parentValue)?.apply { this.index = index } recursions-- valueIndex.removeLast() return parameter } private fun shouldRecurseDeeper(): Boolean = recursions < maxRecursions /** * Create a [NodeParameter] as a reference to a previously created parameter. * * Use [createFromCompositeValue] to compute the data type and top value, * however no children will be created. Instead a reference to the previously * created parameter is specified. */ private fun createReferenceToExistingValue( name: String, value: Any?, parentValue: Any?, ref: NodeParameterReference ): NodeParameter? { val remember = recursions recursions = maxRecursions val parameter = createFromCompositeValue(name, value, parentValue)?.apply { reference = ref } recursions = remember return parameter } /** * Returns `true` if the value can be mapped to a [NodeParameter]. * * Composite values should NOT be added to the [valueIndexMap] since we * do not intend to include this parameter in the response. */ private fun hasMappableValue(value: Any?): Boolean { if (value == null) { return false } if (valueIndexMap.containsKey(value)) { return true } val remember = recursions recursions = maxRecursions val parameter = create("p", value, null) recursions = remember valueIndexMap.remove(value) return parameter != null } /** * Store the reference of this [NodeParameter] by its [value] * * If the value is seen in other parameter values again, there is * no need to create child parameters a second time. */ private fun NodeParameter.store(value: Any?): NodeParameter { if (value != null) { val index = valueIndexToReference() valueIndexMap[value] = index } return this } /** * Remove the [value] of this [NodeParameter] if there are no child elements. */ private fun NodeParameter.removeIfEmpty(value: Any?): NodeParameter { if (value != null) { if (elements.isEmpty()) { valueIndexMap.remove(value) } val reference = valueIndexMap[value] valueLazyReferenceMap.remove(value)?.forEach { it.reference = reference } } return this } /** * Delay the creation of all child parameters of this composite parameter. * * If the child parameters are omitted because of [maxRecursions], store the * parameter itself such that its reference can be updated if it turns out * that child [NodeParameter]s need to be generated later. */ private fun NodeParameter.withChildReference(value: Any): NodeParameter { valueLazyReferenceMap.getOrPut(value, { mutableListOf() }).add(this) reference = valueIndexToReference() return this } private fun valueIndexToReference(): NodeParameterReference = NodeParameterReference(nodeId, anchorId, kind, parameterIndex, valueIndex) private fun createEmptyParameter(name: String): NodeParameter = NodeParameter(name, ParameterType.String, "") private fun createFromArray( name: String, value: Any, startIndex: Int, maxElements: Int ): NodeParameter? { val sequence = arrayToSequence(value) ?: return null return createFromSequence(name, value, sequence, startIndex, maxElements) } private fun findFromArray(value: Any, index: Int): Pair<String, Any?>? { val sequence = arrayToSequence(value) ?: return null return findFromSequence(sequence, index) } private fun arrayToSequence(value: Any): Sequence<*>? = when (value) { is Array<*> -> value.asSequence() is ByteArray -> value.asSequence() is IntArray -> value.asSequence() is LongArray -> value.asSequence() is FloatArray -> value.asSequence() is DoubleArray -> value.asSequence() is BooleanArray -> value.asSequence() is CharArray -> value.asSequence() else -> null } private fun createFromBaselineShift(name: String, value: BaselineShift): NodeParameter { val converted = when (value.multiplier) { BaselineShift.None.multiplier -> "None" BaselineShift.Subscript.multiplier -> "Subscript" BaselineShift.Superscript.multiplier -> "Superscript" else -> return NodeParameter(name, ParameterType.Float, value.multiplier) } return NodeParameter(name, ParameterType.String, converted) } private fun createFromCLambda(name: String, value: ComposableLambda): NodeParameter? = try { val lambda = value.javaClass.getDeclaredField("_block") .apply { isAccessible = true } .get(value) NodeParameter(name, ParameterType.Lambda, arrayOf<Any?>(lambda)) } catch (_: Throwable) { null } private fun createFromConstant(name: String, value: Any): NodeParameter? { loadConstantsFrom(value.javaClass) return valueLookup[value]?.let { NodeParameter(name, ParameterType.String, it) } } // For now: select ResourceFontFont closest to W400 and Normal, and return the resId private fun createFromFontListFamily( name: String, value: FontListFontFamily ): NodeParameter? = findBestResourceFont(value)?.let { NodeParameter(name, ParameterType.Resource, it.resId) } private fun createFromFunctionReference( name: String, value: FunctionReference ): NodeParameter = NodeParameter(name, ParameterType.FunctionReference, arrayOf<Any>(value, value.name)) private fun createFromKotlinReflection(name: String, value: Any): NodeParameter? { val simpleName = value::class.simpleName val properties = lookup(value) ?: return null val parameter = NodeParameter(name, ParameterType.String, simpleName) return when { properties.isEmpty() -> parameter !shouldRecurseDeeper() -> parameter.withChildReference(value) else -> { val elements = parameter.store(value).elements properties.values.mapIndexedNotNullTo(elements) { index, part -> createRecursively(part.name, valueOf(part, value), value, index) } parameter.removeIfEmpty(value) } } } private fun findFromKotlinReflection(value: Any, index: Int): Pair<String, Any?>? { val properties = lookup(value)?.entries?.iterator()?.asSequence() ?: return null val element = properties.elementAtOrNull(index)?.value ?: return null return Pair(element.name, valueOf(element, value)) } private fun lookup(value: Any): Map<String, KProperty<*>>? { val kClass = value::class val simpleName = kClass.simpleName val qualifiedName = kClass.qualifiedName if (simpleName == null || qualifiedName == null || ignoredPackagePrefixes.any { qualifiedName.startsWith(it) } ) { // Exit without creating a parameter for: // - internal synthetic classes // - certain android packages return null } return try { sequenceOf(kClass).plus(kClass.allSuperclasses.asSequence()) .flatMap { it.declaredMemberProperties.asSequence() } .associateBy { it.name } } catch (ex: Throwable) { Log.w("Compose", "Could not decompose ${kClass.simpleName}", ex) null } } private fun valueOf(property: KProperty<*>, instance: Any): Any? = try { property.isAccessible = true // Bug in kotlin reflection API: if the type is a nullable inline type with a null // value, we get an IllegalArgumentException in this line: property.getter.call(instance) } catch (ex: Throwable) { // TODO: Remove this warning since this is expected with nullable inline types Log.w("Compose", "Could not get value of ${property.name}") null } private fun createFromInspectableValue( name: String, value: InspectableValue ): NodeParameter { val tempValue = value.valueOverride ?: "" val parameterName = name.ifEmpty { value.nameFallback } ?: "element" val parameterValue = if (tempValue is InspectableValue) "" else tempValue val parameter = createFromSimpleValue(parameterName, parameterValue) ?: NodeParameter(parameterName, ParameterType.String, "") if (!shouldRecurseDeeper()) { return parameter.withChildReference(value) } val elements = parameter.store(value).elements value.inspectableElements.mapIndexedNotNullTo(elements) { index, element -> createRecursively(element.name, element.value, value, index) } return parameter.removeIfEmpty(value) } private fun findFromInspectableValue( value: InspectableValue, index: Int ): Pair<String, Any?>? { val elements = value.inspectableElements.toList() if (index !in elements.indices) { return null } val element = elements[index] return Pair(element.name, element.value) } private fun createFromMapEntry( name: String, entry: Map.Entry<*, *>, parentValue: Any? ): NodeParameter? { val key = createRecursively("key", entry.key, entry, 0) ?: return null val value = createRecursively("value", entry.value, entry, 1) ?: return null val keyName = (key.value?.toString() ?: "").ifEmpty { "entry" } val valueName = value.value?.toString()?.ifEmpty { null } val nodeName = if (parentValue is Map<*, *>) "[$keyName]" else name return NodeParameter(nodeName, ParameterType.String, valueName).apply { elements.add(key) elements.add(value) } } private fun findFromMapEntry(entry: Map.Entry<*, *>, index: Int): Pair<String, Any?>? = when (index) { 0 -> Pair("key", entry.key) 1 -> Pair("value", entry.value) else -> null } private fun createFromSequence( name: String, value: Any, sequence: Sequence<*>, startIndex: Int, maxElements: Int ): NodeParameter { val parameter = NodeParameter(name, ParameterType.Iterable, sequenceName(value)) return when { !sequence.any() -> parameter !shouldRecurseDeeper() -> parameter.withChildReference(value) else -> { val elements = parameter.store(value).elements val rest = sequence.drop(startIndex).iterator() var index = startIndex while (rest.hasNext() && elements.size < maxElements) { createRecursively("[$index]", rest.next(), value, index)?.let { elements.add(it) } index++ } while (rest.hasNext()) { if (hasMappableValue(rest.next())) { parameter.withChildReference(value) break } } parameter.removeIfEmpty(value) } } } private fun findFromSequence(value: Sequence<*>, index: Int): Pair<String, Any?>? { val element = value.elementAtOrNull(index) ?: return null return Pair("[$index]", element) } private fun sequenceName(value: Any): String = when (value) { is Array<*> -> "Array[${value.size}]" is ByteArray -> "ByteArray[${value.size}]" is IntArray -> "IntArray[${value.size}]" is LongArray -> "LongArray[${value.size}]" is FloatArray -> "FloatArray[${value.size}]" is DoubleArray -> "DoubleArray[${value.size}]" is BooleanArray -> "BooleanArray[${value.size}]" is CharArray -> "CharArray[${value.size}]" is List<*> -> "List[${value.size}]" is Set<*> -> "Set[${value.size}]" is Map<*, *> -> "Map[${value.size}]" is Collection<*> -> "Collection[${value.size}]" is Iterable<*> -> "Iterable" else -> "Sequence" } private fun createFromLambda(name: String, value: Lambda<*>): NodeParameter = NodeParameter(name, ParameterType.Lambda, arrayOf<Any>(value)) private fun createFromModifier(name: String, value: Modifier): NodeParameter? = when { name.isNotEmpty() -> { val parameter = NodeParameter(name, ParameterType.String, "") val modifiers = unwrap(value) when { modifiers.isEmpty() -> parameter !shouldRecurseDeeper() -> parameter.withChildReference(value) else -> { val elements = parameter.elements modifiers.mapIndexedNotNullTo(elements) { index, element -> createRecursively("", element, value, index) } parameter.store(value).removeIfEmpty(value) } } } value is InspectableValue -> createFromInspectableValue(name, value) else -> null } private fun unwrap(value: Modifier): List<Modifier.Element> { val collector = ModifierCollector() value.foldIn(collector) { acc, m -> acc.apply { add(m) } } return collector.modifiers } private fun findFromModifier( name: String, value: Modifier, index: Int ): Pair<String, Any?>? = when { name.isNotEmpty() -> { val modifiers = unwrap(value) if (index in modifiers.indices) Pair("", modifiers[index]) else null } value is InspectableValue -> findFromInspectableValue(value, index) else -> null } private fun createFromOffset(name: String, value: Offset): NodeParameter { val parameter = NodeParameter(name, ParameterType.String, Offset::class.java.simpleName) val elements = parameter.elements val x = with(density) { value.x.toDp().value } val y = with(density) { value.y.toDp().value } elements.add(NodeParameter("x", DimensionDp, x)) elements.add(NodeParameter("y", DimensionDp, y).apply { index = 1 }) return parameter } private fun findFromOffset(value: Offset, index: Int): Pair<String, Any?>? = when (index) { 0 -> Pair("x", with(density) { value.x.toDp() }) 1 -> Pair("y", with(density) { value.y.toDp() }) else -> null } // Special handling of blurRadius: convert to dp: private fun createFromShadow(name: String, value: Shadow): NodeParameter? { val parameter = createFromKotlinReflection(name, value) ?: return null val elements = parameter.elements val index = elements.indexOfFirst { it.name == "blurRadius" } if (index >= 0) { val existing = elements[index] val blurRadius = with(density) { value.blurRadius.toDp().value } elements[index] = NodeParameter("blurRadius", DimensionDp, blurRadius) elements[index].index = existing.index } return parameter } private fun findFromShadow(value: Shadow, index: Int): Pair<String, Any?>? { val result = findFromKotlinReflection(value, index) if (result == null || result.first != "blurRadius") { return result } return Pair("blurRadius", with(density) { value.blurRadius.toDp() }) } // Temporary handling of TextStyle: remove when TextStyle implements InspectableValue // Hide: paragraphStyle, spanStyle, platformStyle, lineHeightStyle private fun createFromTextStyle(name: String, value: TextStyle): NodeParameter? { val parameter = NodeParameter(name, ParameterType.String, TextStyle::class.java.simpleName) val elements = parameter.elements create("color", value.color, value)?.let { elements.add(it) } create("fontSize", value.fontSize, value, 1)?.let { elements.add(it) } create("fontWeight", value.fontWeight, value, 2)?.let { elements.add(it) } create("fontStyle", value.fontStyle, value, 3)?.let { elements.add(it) } create("fontSynthesis", value.fontSynthesis, value, 4)?.let { elements.add(it) } create("fontFamily", value.fontFamily, value, 5)?.let { elements.add(it) } create("fontFeatureSettings", value.fontFeatureSettings, value, 6)?.let { elements.add(it) } create("letterSpacing", value.letterSpacing, value, 7)?.let { elements.add(it) } create("baselineShift", value.baselineShift, value, 8)?.let { elements.add(it) } create("textGeometricTransform", value.textGeometricTransform, value, 9)?.let { elements.add(it) } create("localeList", value.localeList, value, 10)?.let { elements.add(it) } create("background", value.background, value, 11)?.let { elements.add(it) } create("textDecoration", value.textDecoration, value, 12)?.let { elements.add(it) } create("shadow", value.shadow, value, 13)?.let { elements.add(it) } create("textDirection", value.textDirection, value, 14)?.let { elements.add(it) } create("lineHeight", value.lineHeight, value, 15)?.let { elements.add(it) } create("textIndent", value.textIndent, value, 16)?.let { elements.add(it) } return parameter } private fun findFromTextStyle(value: TextStyle, index: Int): Pair<String, Any?>? = when (index) { 0 -> Pair("color", value.color) 1 -> Pair("fontSize", value.fontSize) 2 -> Pair("fontWeight", value.fontWeight) 3 -> Pair("fontStyle", value.fontStyle) 4 -> Pair("fontSynthesis", value.fontSynthesis) 5 -> Pair("fontFamily", value.fontFamily) 6 -> Pair("fontFeatureSettings", value.fontFeatureSettings) 7 -> Pair("letterSpacing", value.letterSpacing) 8 -> Pair("baselineShift", value.baselineShift) 9 -> Pair("textGeometricTransform", value.textGeometricTransform) 10 -> Pair("localeList", value.localeList) 11 -> Pair("background", value.background) 12 -> Pair("textDecoration", value.textDecoration) 13 -> Pair("shadow", value.shadow) 14 -> Pair("textDirection", value.textDirection) 15 -> Pair("lineHeight", value.lineHeight) 16 -> Pair("textIndent", value.textIndent) else -> null } @Suppress("DEPRECATION") private fun createFromTextUnit(name: String, value: TextUnit): NodeParameter = when (value.type) { TextUnitType.Sp -> NodeParameter(name, ParameterType.DimensionSp, value.value) TextUnitType.Em -> NodeParameter(name, ParameterType.DimensionEm, value.value) else -> NodeParameter(name, ParameterType.String, "Unspecified") } private fun createFromImageVector(name: String, value: ImageVector): NodeParameter = NodeParameter(name, ParameterType.String, value.name) /** * Select a resource font among the font in the family to represent the font * * Prefer the font closest to [FontWeight.Normal] and [FontStyle.Normal] */ private fun findBestResourceFont(value: FontListFontFamily): ResourceFont? = value.fonts.asSequence().filterIsInstance<ResourceFont>().minByOrNull { abs(it.weight.weight - FontWeight.Normal.weight) + it.style.value } } private class ModifierCollector { val modifiers = mutableListOf<Modifier.Element>() var start: InspectableModifier? = null fun add(element: Modifier.Element) = when { element == start?.end -> start = null start != null -> {} else -> { modifiers.add(element) start = element as? InspectableModifier } } } }
apache-2.0
026ac730ff7ebf6a45a761cc50589a2f
41.02924
100
0.585131
5.077358
false
false
false
false
AndroidX/androidx
compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/InspectableModifierSample.kt
3
1796
/* * 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.compose.ui.samples import androidx.annotation.Sampled import androidx.compose.foundation.background import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.platform.inspectable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Sampled @Composable fun InspectableModifierSample() { /** * Sample with a single parameter */ fun Modifier.simpleFrame(color: Color) = inspectable( inspectorInfo = debugInspectorInfo { name = "simpleFrame" value = color } ) { background(color, RoundedCornerShape(5.0.dp)) } /** * Sample with multiple parameters */ fun Modifier.fancyFrame(size: Dp, color: Color) = inspectable( inspectorInfo = debugInspectorInfo { name = "fancyFrame" properties["size"] = size properties["color"] = color } ) { background(color, RoundedCornerShape(size)) } }
apache-2.0
497232770dad5dec034e1e1a6d5eb29a
29.965517
75
0.707127
4.434568
false
false
false
false
rejasupotaro/octodroid
app/src/main/kotlin/com/example/octodroid/views/adapters/RepositoryAdapter.kt
1
5657
package com.example.octodroid.views.adapters import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.example.octodroid.data.GitHub import com.example.octodroid.data.prefs.OctodroidPrefs import com.example.octodroid.views.components.DividerItemDecoration import com.example.octodroid.views.components.LinearLayoutLoadMoreListener import com.example.octodroid.views.helpers.ToastHelper import com.example.octodroid.views.holders.ProgressViewHolder import com.example.octodroid.views.holders.SelectableRepositoryItemViewHolder import com.jakewharton.rxbinding.view.RxView import com.rejasupotaro.octodroid.http.Params import com.rejasupotaro.octodroid.http.Response import com.rejasupotaro.octodroid.models.Repository import com.rejasupotaro.octodroid.models.Resource import rx.Observable import rx.subjects.BehaviorSubject import java.util.* class RepositoryAdapter(private val recyclerView: RecyclerView) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private object ViewType { val ITEM = 1 val FOOTER = 2 } private val context: Context private val repositories = ArrayList<Repository>() private var responseSubject: BehaviorSubject<Observable<Response<List<Repository>>>>? = null private var pagedResponse: Observable<Response<List<Repository>>>? = null private var isReachedLast: Boolean = false private val prefs: OctodroidPrefs private val selectedRepositories = HashMap<Int, Repository>() init { this.context = recyclerView.context prefs = OctodroidPrefs.get(context) for (serializedRepositories in prefs.selectedSerializedRepositories) { val repository = Resource.fromJson(serializedRepositories, Repository::class.java) selectedRepositories.put(repository.id, repository) } val layoutManager = LinearLayoutManager(context) recyclerView.layoutManager = layoutManager recyclerView.setHasFixedSize(false) recyclerView.itemAnimator = null recyclerView.addItemDecoration(DividerItemDecoration(context)) recyclerView.addOnScrollListener(object : LinearLayoutLoadMoreListener(layoutManager) { override fun onLoadMore() { if (pagedResponse != null) { responseSubject!!.onNext(pagedResponse) } } }) requestUserRepositories() } private fun requestUserRepositories() { val params = Params() params.add("per_page", "100") params.add("sort", "updated") responseSubject = BehaviorSubject.create(GitHub.client().userRepositories(params)) responseSubject!!.takeUntil(RxView.detaches(recyclerView)) .flatMap { r -> r } .subscribe({ r -> if (!r.isSuccessful) { isReachedLast = true notifyDataSetChanged() ToastHelper.showError(context) return@subscribe } val items = r.entity() val startPosition = repositories.size repositories.addAll(items) if (r.hasNext()) { pagedResponse = r.next() } else { isReachedLast = true } if (startPosition == 0) { notifyDataSetChanged() } else { notifyItemRangeInserted(startPosition, items.size) } }) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { if (viewType == ViewType.FOOTER) { return ProgressViewHolder.create(parent) } else { return SelectableRepositoryItemViewHolder.create(parent) } } override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { when (getItemViewType(position)) { ViewType.FOOTER -> { } else -> { val repository = repositories[position] (viewHolder as SelectableRepositoryItemViewHolder).bind( repository, selectedRepositories.containsKey(repository.id), object : SelectableRepositoryItemViewHolder.OnSelectRepositoryListener { override fun onSelect(id: Int) { selectedRepositories.put(id, repository) } override fun onUnSelect(id: Int) { selectedRepositories.remove(id) } }) } } } override fun getItemViewType(position: Int): Int { if (repositories.size == 0 || position == repositories.size) { return ViewType.FOOTER } else { return ViewType.ITEM } } override fun getItemCount(): Int { return repositories.size + if (isReachedLast) 0 else 1 } fun saveSelectedRepositories() { val selectedSerializedRepositories = HashSet<String>() for (repositoryId in selectedRepositories.keys) { val repository = selectedRepositories[repositoryId] selectedSerializedRepositories.add(repository!!.toJson()) } prefs.selectedSerializedRepositories = selectedSerializedRepositories } }
mit
4b3f7f2102388e5a767f8d3f882bc32f
37.482993
115
0.621354
5.434198
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/tasks/TasksFragment.kt
1
18113
package com.habitrpg.android.habitica.ui.fragments.tasks import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.graphics.PorterDuff import android.os.Bundle import android.text.format.DateUtils 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.activity.result.contract.ActivityResultContracts import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.core.content.edit import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.TagRepository import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding import com.habitrpg.android.habitica.extensions.getThemeColor import com.habitrpg.android.habitica.extensions.setTintWith import com.habitrpg.android.habitica.helpers.AmplitudeManager import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.helpers.TaskFilterHelper import com.habitrpg.android.habitica.models.tasks.TaskType import com.habitrpg.android.habitica.modules.AppModule import com.habitrpg.android.habitica.ui.activities.TaskFormActivity import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.views.navigation.HabiticaBottomNavigationViewListener import com.habitrpg.android.habitica.ui.views.tasks.TaskFilterDialog import io.reactivex.rxjava3.disposables.Disposable import java.util.Date import java.util.WeakHashMap import javax.inject.Inject import javax.inject.Named class TasksFragment : BaseMainFragment<FragmentViewpagerBinding>(), SearchView.OnQueryTextListener, HabiticaBottomNavigationViewListener { override var binding: FragmentViewpagerBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding { return FragmentViewpagerBinding.inflate(inflater, container, false) } @field:[Inject Named(AppModule.NAMED_USER_ID)] lateinit var userID: String @Inject lateinit var taskFilterHelper: TaskFilterHelper @Inject lateinit var tagRepository: TagRepository @Inject lateinit var appConfigManager: AppConfigManager @Inject lateinit var sharedPreferences: SharedPreferences private var refreshItem: MenuItem? = null internal var viewFragmentsDictionary: MutableMap<Int, TaskRecyclerViewFragment>? = WeakHashMap() private var filterMenuItem: MenuItem? = null private val activeFragment: TaskRecyclerViewFragment? get() { var fragment = viewFragmentsDictionary?.get(binding?.viewPager?.currentItem) if (fragment == null) { if (isAdded) { fragment = (childFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + binding?.viewPager?.currentItem) as? TaskRecyclerViewFragment) } } return fragment } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { this.usesTabLayout = false this.usesBottomNavigation = true return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loadTaskLists() arguments?.let { val args = TasksFragmentArgs.fromBundle(it) val taskTypeValue = args.taskType if (taskTypeValue?.isNotBlank() == true) { val taskType = TaskType.from(taskTypeValue) switchToTaskTab(taskType) } else { when (sharedPreferences.getString("launch_screen", "")) { "/user/tasks/habits" -> onTabSelected(TaskType.HABIT, false) "/user/tasks/dailies" -> onTabSelected(TaskType.DAILY, false) "/user/tasks/todos" -> onTabSelected(TaskType.TODO, false) "/user/tasks/rewards" -> onTabSelected(TaskType.REWARD, false) } } } } override fun onResume() { super.onResume() bottomNavigation?.activeTaskType = when (binding?.viewPager?.currentItem) { 0 -> TaskType.HABIT 1 -> TaskType.DAILY 2 -> TaskType.TODO 3 -> TaskType.REWARD else -> TaskType.HABIT } binding?.viewPager?.currentItem = binding?.viewPager?.currentItem ?: 0 bottomNavigation?.listener = this bottomNavigation?.canAddTasks = true } override fun onPause() { if (bottomNavigation?.listener == this) { bottomNavigation?.listener = null } super.onPause() } override fun onDestroy() { tagRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_main_activity, menu) filterMenuItem = menu.findItem(R.id.action_filter) updateFilterIcon() val item = menu.findItem(R.id.action_search) tintMenuIcon(item) val sv = item.actionView as? SearchView sv?.setOnQueryTextListener(this) sv?.setIconifiedByDefault(false) item.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionCollapse(item: MenuItem): Boolean { filterMenuItem?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) return true } override fun onMenuItemActionExpand(item: MenuItem): Boolean { // Do something when expanded filterMenuItem?.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER) return true } }) } override fun onQueryTextSubmit(query: String?): Boolean { return true } override fun onQueryTextChange(newText: String?): Boolean { taskFilterHelper.searchQuery = newText viewFragmentsDictionary?.values?.forEach { values -> values.recyclerAdapter?.filter() } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_filter -> { showFilterDialog() true } R.id.action_reload -> { refreshItem = item refresh() true } else -> super.onOptionsItemSelected(item) } } private fun showFilterDialog() { context?.let { val disposable: Disposable val dialog = TaskFilterDialog(it, HabiticaBaseApplication.userComponent) disposable = tagRepository.getTags().subscribe({ tagsList -> dialog.setTags(tagsList) }, RxErrorHandler.handleEmptyError()) dialog.setActiveTags(taskFilterHelper.tags) // There are some cases where these things might not be correctly set after the app resumes. This is just to catch that as best as possible val navigation = bottomNavigation ?: activity?.binding?.bottomNavigation val taskType = navigation?.activeTaskType ?: activeFragment?.taskType if (taskType != null) { dialog.setTaskType(taskType, taskFilterHelper.getActiveFilter(taskType)) } dialog.setListener(object : TaskFilterDialog.OnFilterCompletedListener { override fun onFilterCompleted(activeTaskFilter: String?, activeTags: MutableList<String>) { if (viewFragmentsDictionary == null) { return } taskFilterHelper.tags = activeTags if (activeTaskFilter != null) { activeFragment?.setActiveFilter(activeTaskFilter) } viewFragmentsDictionary?.values?.forEach { values -> values.recyclerAdapter?.filter() } updateFilterIcon() } }) dialog.setOnDismissListener { if (!disposable.isDisposed) { disposable.dispose() } } dialog.show() } } private fun refresh() { activeFragment?.onRefresh() } private fun loadTaskLists() { val fragmentManager = childFragmentManager binding?.viewPager?.adapter = object : FragmentStateAdapter(fragmentManager, lifecycle) { override fun createFragment(position: Int): Fragment { val fragment: TaskRecyclerViewFragment = when (position) { 0 -> TaskRecyclerViewFragment.newInstance(context, TaskType.HABIT) 1 -> TaskRecyclerViewFragment.newInstance(context, TaskType.DAILY) 3 -> RewardsRecyclerviewFragment.newInstance(context, TaskType.REWARD, true) else -> TaskRecyclerViewFragment.newInstance(context, TaskType.TODO) } fragment.refreshAction = { compositeSubscription.add( userRepository.retrieveUser( withTasks = true, forced = true ).doOnTerminate { it() }.subscribe({ }, RxErrorHandler.handleEmptyError()) ) } viewFragmentsDictionary?.put(position, fragment) return fragment } override fun getItemCount(): Int = 4 } binding?.viewPager?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) bottomNavigation?.selectedPosition = position updateFilterIcon() } }) } private fun updateFilterIcon() { val filterCount = taskFilterHelper.howMany(activeFragment?.taskType) filterMenuItem?.isVisible = activeFragment?.taskType != TaskType.REWARD if (filterCount == 0) { filterMenuItem?.setIcon(R.drawable.ic_action_filter_list) context?.let { val filterIcon = ContextCompat.getDrawable(it, R.drawable.ic_action_filter_list) filterIcon?.setTintWith(it.getThemeColor(R.attr.headerTextColor), PorterDuff.Mode.MULTIPLY) filterMenuItem?.setIcon(filterIcon) } } else { context?.let { val filterIcon = ContextCompat.getDrawable(it, R.drawable.ic_filters_active) filterIcon?.setTintWith(it.getThemeColor(R.attr.textColorPrimaryDark), PorterDuff.Mode.MULTIPLY) filterMenuItem?.setIcon(filterIcon) } } } private fun updateBottomBarBadges() { if (bottomNavigation == null) { return } compositeSubscription.add( tutorialRepository.getTutorialSteps(listOf("habits", "dailies", "todos", "rewards")).subscribe( { tutorialSteps -> val activeTutorialFragments = ArrayList<TaskType>() for (step in tutorialSteps) { var id = -1 val taskType = when (step.identifier) { "habits" -> { id = R.id.habits_tab TaskType.HABIT } "dailies" -> { id = R.id.dailies_tab TaskType.DAILY } "todos" -> { id = R.id.todos_tab TaskType.TODO } "rewards" -> { id = R.id.rewards_tab TaskType.REWARD } else -> TaskType.HABIT } val tab = bottomNavigation?.tabWithId(id) if (step.shouldDisplay()) { tab?.badgeCount = 1 activeTutorialFragments.add(taskType) } else { tab?.badgeCount = 0 } } if (activeTutorialFragments.size == 1) { val fragment = viewFragmentsDictionary?.get(indexForTaskType(activeTutorialFragments[0])) if (fragment?.tutorialTexts != null && context != null) { val finalText = context?.getString(R.string.tutorial_tasks_complete) if (!fragment.tutorialTexts.contains(finalText) && finalText != null) { fragment.tutorialTexts.add(finalText) } } } }, RxErrorHandler.handleEmptyError() ) ) } // endregion private fun openNewTaskActivity(type: TaskType) { if (Date().time - (lastTaskFormOpen?.time ?: 0) < 2000) { return } val additionalData = HashMap<String, Any>() additionalData["created task type"] = type additionalData["viewed task type"] = when (binding?.viewPager?.currentItem) { 0 -> TaskType.HABIT 1 -> TaskType.DAILY 2 -> TaskType.TODO 3 -> TaskType.REWARD else -> "" } AmplitudeManager.sendEvent("open create task form", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData) val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, type.value) bundle.putStringArrayList(TaskFormActivity.SELECTED_TAGS_KEY, ArrayList(taskFilterHelper.tags)) val intent = Intent(activity, TaskFormActivity::class.java) intent.putExtras(bundle) intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT if (this.isAdded) { lastTaskFormOpen = Date() taskCreateResult.launch(intent) } } //endregion Events private val taskCreateResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { onTaskCreatedResult(it.resultCode, it.data) } private fun onTaskCreatedResult(resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { val taskTypeValue = data?.getStringExtra(TaskFormActivity.TASK_TYPE_KEY) if (taskTypeValue != null) { val taskType = TaskType.from(taskTypeValue) switchToTaskTab(taskType) val index = indexForTaskType(taskType) if (index != -1) { val fragment = viewFragmentsDictionary?.get(index) fragment?.binding?.recyclerView?.scrollToPosition(0) } } if (!DateUtils.isToday(sharedPreferences.getLong("last_creation_reporting", 0))) { AmplitudeManager.sendEvent( "task created", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT ) sharedPreferences.edit { putLong("last_creation_reporting", Date().time) } } } } private fun switchToTaskTab(taskType: TaskType?) { val index = indexForTaskType(taskType) if (binding?.viewPager != null && index != -1) { binding?.viewPager?.currentItem = index updateBottomBarBadges() } } private fun indexForTaskType(taskType: TaskType?): Int { if (taskType != null) { for (index in 0 until (viewFragmentsDictionary?.size ?: 0)) { val fragment = viewFragmentsDictionary?.get(index) if (fragment != null && taskType == fragment.className) { return index } } } return -1 } override val displayedClassName: String? get() = null override fun addToBackStack(): Boolean = false companion object { var lastTaskFormOpen: Date? = null } override fun onTabSelected(taskType: TaskType, smooth: Boolean) { val newItem = when (taskType) { TaskType.HABIT -> 0 TaskType.DAILY -> 1 TaskType.TODO -> 2 TaskType.REWARD -> 3 else -> 0 } binding?.viewPager?.setCurrentItem(newItem, smooth) updateBottomBarBadges() } override fun onAdd(taskType: TaskType) { openNewTaskActivity(taskType) } }
gpl-3.0
165ef3aef40640ae7dfc15bc92c8a3d7
38.430804
178
0.579032
5.586983
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/HorizontalPageIndicatorScreenshotTest.kt
3
3596
/* * 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 import android.os.Build import androidx.compose.foundation.layout.size import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import androidx.wear.compose.material.HorizontalPageIndicatorTest.Companion.pageIndicatorState import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class HorizontalPageIndicatorScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(SCREENSHOT_GOLDEN_PATH) @get:Rule val testName = TestName() @Test fun horizontalPageIndicator_circular_selected_page() { selected_page(PageIndicatorStyle.Curved) } @Test fun horizontalPageIndicator_linear_selected_page() { selected_page(PageIndicatorStyle.Linear) } @Test fun horizontalPageIndicator_circular_between_pages() { between_pages(PageIndicatorStyle.Curved) } @Test fun horizontalPageIndicator_linear_between_pages() { between_pages(PageIndicatorStyle.Linear) } private fun selected_page(indicatorStyle: PageIndicatorStyle) { rule.setContentWithTheme { HorizontalPageIndicator( modifier = Modifier.testTag(TEST_TAG).size(150.dp), indicatorStyle = indicatorStyle, pageIndicatorState = pageIndicatorState(), selectedColor = Color.Yellow, unselectedColor = Color.Red, indicatorSize = 15.dp ) } rule.waitForIdle() rule.onNodeWithTag(TEST_TAG) .captureToImage() .assertAgainstGolden(screenshotRule, testName.methodName) } private fun between_pages(indicatorStyle: PageIndicatorStyle) { rule.setContentWithTheme { HorizontalPageIndicator( modifier = Modifier.testTag(TEST_TAG).size(150.dp), indicatorStyle = indicatorStyle, pageIndicatorState = pageIndicatorState(0.5f), selectedColor = Color.Yellow, unselectedColor = Color.Red, indicatorSize = 15.dp ) } rule.waitForIdle() rule.onNodeWithTag(TEST_TAG) .captureToImage() .assertAgainstGolden(screenshotRule, testName.methodName) } }
apache-2.0
1dccde0317127795722f67a2002b037c
32.305556
94
0.707453
4.712975
false
true
false
false
androidx/androidx
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/injectionscope/mouse/CancelTest.kt
3
2227
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.injectionscope.mouse import androidx.compose.testutils.expectError import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.PointerEventType.Companion.Enter import androidx.compose.ui.input.pointer.PointerEventType.Companion.Press import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.MouseButton import androidx.compose.ui.test.injectionscope.mouse.Common.PrimaryButton import androidx.compose.ui.test.injectionscope.mouse.Common.runMouseInputInjectionTest import androidx.compose.ui.test.injectionscope.mouse.Common.verifyMouseEvent import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalTestApi::class) class CancelTest { @Test fun cancel() = runMouseInputInjectionTest( mouseInput = { // press the primary button press(MouseButton.Primary) // cancel the gesture cancel() }, eventVerifiers = arrayOf( { this.verifyMouseEvent(0, Enter, false, Offset.Zero) }, { this.verifyMouseEvent(0, Press, true, Offset.Zero, PrimaryButton) }, ) ) @Test fun cancel_withoutPress() = runMouseInputInjectionTest( mouseInput = { expectError<IllegalStateException>( expectedMessage = "Cannot send mouse cancel event, no mouse buttons are pressed" ) { cancel() } } ) }
apache-2.0
8975cfab7c8813cde8a939c785dccba0
35.508197
96
0.7207
4.375246
false
true
false
false
Soya93/Extract-Refactoring
platform/script-debugger/protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/OutMessage.kt
5
6732
/* * 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.jsonProtocol import com.google.gson.stream.JsonWriter import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.containers.isNullOrEmpty import gnu.trove.TIntArrayList import gnu.trove.TIntHashSet import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBufAllocator import io.netty.buffer.ByteBufUtf8Writer import io.netty.buffer.ByteBufUtilEx import org.jetbrains.io.JsonUtil import java.io.IOException open class OutMessage() { val buffer: ByteBuf = ByteBufAllocator.DEFAULT.heapBuffer() val writer = JsonWriter(ByteBufUtf8Writer(buffer)) private var finalized: Boolean = false init { writer.beginObject() } open fun beginArguments() { } fun writeMap(name: String, value: Map<String, String>? = null) { if (value == null) return beginArguments() writer.name(name) writer.beginObject() for (entry in value.entries) { writer.name(entry.key).value(entry.value) } writer.endObject() } protected fun writeLongArray(name: String, value: LongArray) { beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v) } writer.endArray() } fun writeDoubleArray(name: String, value: DoubleArray) { beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v) } writer.endArray() } fun writeIntArray(name: String, value: IntArray? = null) { if (value == null) { return } beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v.toLong()) } writer.endArray() } fun writeIntSet(name: String, value: TIntHashSet) { beginArguments() writer.name(name) writer.beginArray() value.forEach { value -> writer.value(value.toLong()) true } writer.endArray() } fun writeIntList(name: String, value: TIntArrayList) { beginArguments() writer.name(name) writer.beginArray() for (i in 0..value.size() - 1) { writer.value(value.getQuick(i).toLong()) } writer.endArray() } fun writeSingletonIntArray(name: String, value: Int) { beginArguments() writer.name(name) writer.beginArray() writer.value(value.toLong()) writer.endArray() } fun <E : OutMessage> writeList(name: String, value: List<E>?) { if (value.isNullOrEmpty()) { return } beginArguments() writer.name(name) writer.beginArray() var isNotFirst = false for (item in value!!) { if (isNotFirst) { buffer.writeByte(','.toInt()).writeByte(' '.toInt()) } else { isNotFirst = true } if (!item.finalized) { item.finalized = true try { item.writer.endObject() } catch (e: IllegalStateException) { if ("Nesting problem." == e.message) { throw RuntimeException(item.buffer.toString(CharsetToolkit.UTF8_CHARSET) + "\nparent:\n" + buffer.toString(CharsetToolkit.UTF8_CHARSET), e) } else { throw e } } } buffer.writeBytes(item.buffer) } writer.endArray() } fun writeStringList(name: String, value: Collection<String>) { beginArguments() JsonWriters.writeStringList(writer, name, value) } fun writeEnumList(name: String, values: Collection<Enum<*>>) { beginArguments() writer.name(name).beginArray() for (item in values) { writer.value(item.toString()) } writer.endArray() } fun writeMessage(name: String, value: OutMessage?) { if (value == null) { return } beginArguments() prepareWriteRaw(this, name) if (!value.finalized) { value.close() } buffer.writeBytes(value.buffer) } fun close() { assert(!finalized) finalized = true writer.endObject() writer.close() } protected fun writeLong(name: String, value: Long) { beginArguments() writer.name(name).value(value) } fun writeString(name: String, value: String?) { if (value != null) { writeNullableString(name, value) } } fun writeNullableString(name: String, value: CharSequence?) { beginArguments() writer.name(name).value(value!!.toString()) } companion object { @Throws(IOException::class) fun prepareWriteRaw(message: OutMessage, name: String) { message.writer.name(name).nullValue() val itemBuffer = message.buffer itemBuffer.writerIndex(itemBuffer.writerIndex() - "null".length) } fun doWriteRaw(message: OutMessage, rawValue: String) { ByteBufUtilEx.writeUtf8(message.buffer, rawValue) } } } fun OutMessage.writeEnum(name: String, value: Enum<*>?, defaultValue: Enum<*>?) { if (value != null && value != defaultValue) { writeEnum(name, value) } } fun OutMessage.writeEnum(name: String, value: Enum<*>) { beginArguments() writer.name(name).value(value.toString()) } fun OutMessage.writeString(name: String, value: CharSequence?, defaultValue: CharSequence?) { if (value != null && value != defaultValue) { writeString(name, value) } } fun OutMessage.writeString(name: String, value: CharSequence) { beginArguments() OutMessage.prepareWriteRaw(this, name) JsonUtil.escape(value, buffer) } fun OutMessage.writeInt(name: String, value: Int, defaultValue: Int) { if (value != defaultValue) { writeInt(name, value) } } fun OutMessage.writeInt(name: String, value: Int) { beginArguments() writer.name(name).value(value.toLong()) } fun OutMessage.writeBoolean(name: String, value: Boolean, defaultValue: Boolean) { if (value != defaultValue) { writeBoolean(name, value) } } fun OutMessage.writeBoolean(name: String, value: Boolean) { beginArguments() writer.name(name).value(value) } fun OutMessage.writeDouble(name: String, value: Double, defaultValue: Double) { if (value != defaultValue) { writeDouble(name, value) } } fun OutMessage.writeDouble(name: String, value: Double) { beginArguments() writer.name(name).value(value) }
apache-2.0
114a55a0062fccd4ace42da5240e058e
23.48
151
0.659388
3.990516
false
false
false
false
inorichi/tachiyomi-extensions
src/all/ehentai/src/eu/kanade/tachiyomi/extension/all/ehentai/EHUtil.kt
1
1910
package eu.kanade.tachiyomi.extension.all.ehentai import kotlin.math.ln import kotlin.math.pow /** * Various utility methods used in the E-Hentai source */ /** * Return null if String is blank, otherwise returns the original String * @returns null if the String is blank, otherwise returns the original String */ fun String?.nullIfBlank(): String? = if (isNullOrBlank()) null else this /** * Ignores any exceptions thrown inside a block */ fun <T> ignore(expr: () -> T): T? { return try { expr() } catch (t: Throwable) { null } } /** * Use '+' to append Strings onto a StringBuilder */ operator fun StringBuilder.plusAssign(other: String) { append(other) } /** * Converts bytes into a human readable String */ fun humanReadableByteCount(bytes: Long, si: Boolean): String { val unit = if (si) 1000 else 1024 if (bytes < unit) return "$bytes B" val exp = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt() val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i" return String.format("%.1f %sB", bytes / unit.toDouble().pow(exp.toDouble()), pre) } private const val KB_FACTOR = 1000 private const val KIB_FACTOR = 1024 private const val MB_FACTOR = 1000 * KB_FACTOR private const val MIB_FACTOR = 1024 * KIB_FACTOR private const val GB_FACTOR = 1000 * MB_FACTOR private const val GIB_FACTOR = 1024 * MIB_FACTOR /** * Parse human readable size Strings */ fun parseHumanReadableByteCount(arg0: String): Double? { val spaceNdx = arg0.indexOf(" ") val ret = arg0.substring(0 until spaceNdx).toDouble() when (arg0.substring(spaceNdx + 1)) { "GB" -> return ret * GB_FACTOR "GiB" -> return ret * GIB_FACTOR "MB" -> return ret * MB_FACTOR "MiB" -> return ret * MIB_FACTOR "KB" -> return ret * KB_FACTOR "KiB" -> return ret * KIB_FACTOR } return null }
apache-2.0
1031dbfedeaa856acb2b3acd2385f20c
26.285714
86
0.646073
3.504587
false
false
false
false
mike-neck/kuickcheck
core/src/main/kotlin/org/mikeneck/kuickcheck/generator/internal/SizeGenerator.kt
1
1205
/* * Copyright 2016 Shinya Mochida * * Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.generator.internal import org.mikeneck.kuickcheck.Generator internal interface SizeGenerator : Generator<Int> { val max: Int fun <U> of(f: (Int) -> U): List<U> = 1.rangeTo(this.invoke()).map(f) } internal class Size1SizeGenerator : SizeGenerator { override fun invoke(): Int = 1 override val max: Int = 1 } internal class FixedSizeGenerator(val size: Int) : SizeGenerator { override val max: Int = 1 override fun invoke(): Int = size } internal class EmptySizeGenerator : SizeGenerator { override fun invoke(): Int = 0 override val max: Int = 0 }
apache-2.0
171e359c040b64ce9af0f52432c24bca
30.710526
74
0.725311
3.912338
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/connection.kt
1
10876
package org.jetbrains.kotlinx.jupyter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.encodeToJsonElement import kotlinx.serialization.json.jsonObject import org.jetbrains.kotlinx.jupyter.exceptions.ReplException import org.jetbrains.kotlinx.jupyter.messaging.InputReply import org.jetbrains.kotlinx.jupyter.messaging.InputRequest import org.jetbrains.kotlinx.jupyter.messaging.JupyterOutType import org.jetbrains.kotlinx.jupyter.messaging.KernelStatus import org.jetbrains.kotlinx.jupyter.messaging.Message import org.jetbrains.kotlinx.jupyter.messaging.MessageData import org.jetbrains.kotlinx.jupyter.messaging.MessageType import org.jetbrains.kotlinx.jupyter.messaging.StatusReply import org.jetbrains.kotlinx.jupyter.messaging.StreamResponse import org.jetbrains.kotlinx.jupyter.messaging.emptyJsonObject import org.jetbrains.kotlinx.jupyter.messaging.emptyJsonObjectStringBytes import org.jetbrains.kotlinx.jupyter.messaging.jsonObject import org.jetbrains.kotlinx.jupyter.messaging.makeHeader import org.jetbrains.kotlinx.jupyter.messaging.makeReplyMessage import org.zeromq.SocketType import org.zeromq.ZMQ import java.io.Closeable import java.io.IOException import java.security.SignatureException import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import kotlin.concurrent.thread import kotlin.math.min class JupyterConnection(val config: KernelConfig) : Closeable { inner class Socket(private val socket: JupyterSockets, type: SocketType = socket.zmqKernelType) : ZMQ.Socket(context, type) { val name: String get() = socket.name init { val port = config.ports[socket.ordinal] bind("${config.transport}://*:$port") if (type == SocketType.PUB) { // Workaround to prevent losing few first messages on kernel startup // For more information on losing messages see this scheme: // http://zguide.zeromq.org/page:all#Missing-Message-Problem-Solver // It seems we cannot do correct sync because messaging protocol // doesn't support this. Value of 500 ms was chosen experimentally. Thread.sleep(500) } log.debug("[$name] listen: ${config.transport}://*:$port") } inline fun onData(body: Socket.(ByteArray) -> Unit) = recv()?.let { body(it) } inline fun onMessage(body: Socket.(Message) -> Unit) = recv()?.let { bytes -> receiveMessage(bytes)?.let { body(it) } } fun sendStatus(status: KernelStatus, msg: Message) { connection.iopub.send(makeReplyMessage(msg, MessageType.STATUS, content = StatusReply(status))) } fun sendWrapped(incomingMessage: Message, msg: Message) { sendStatus(KernelStatus.BUSY, incomingMessage) send(msg) sendStatus(KernelStatus.IDLE, incomingMessage) } fun sendOut(msg: Message, stream: JupyterOutType, text: String) { send(makeReplyMessage(msg, header = makeHeader(MessageType.STREAM, msg), content = StreamResponse(stream.optionName(), text))) } fun send(msg: Message) { log.debug("[$name] snd>: $msg") sendMessage(msg, hmac) } fun receiveMessage(start: ByteArray): Message? { return try { val msg = receiveMessage(start, hmac) log.debug("[$name] >rcv: $msg") msg } catch (e: SignatureException) { log.error("[$name] ${e.message}") null } } val connection: JupyterConnection = this@JupyterConnection } inner class StdinInputStream : java.io.InputStream() { private var currentBuf: ByteArray? = null private var currentBufPos = 0 private fun getInput(): String { stdin.send( makeReplyMessage( contextMessage!!, MessageType.INPUT_REQUEST, content = InputRequest("stdin:") ) ) val msg = stdin.receiveMessage(stdin.recv()) val content = msg?.data?.content as? InputReply return content?.value ?: throw UnsupportedOperationException("Unexpected input message $msg") } private fun initializeCurrentBuf(): ByteArray { val buf = currentBuf return if (buf != null) { buf } else { val newBuf = getInput().toByteArray() currentBuf = newBuf currentBufPos = 0 newBuf } } @Synchronized override fun read(): Int { val buf = initializeCurrentBuf() if (currentBufPos >= buf.size) { currentBuf = null return -1 } return buf[currentBufPos++].toInt() } @Synchronized override fun read(b: ByteArray, off: Int, len: Int): Int { val buf = initializeCurrentBuf() val lenLeft = buf.size - currentBufPos if (lenLeft <= 0) { currentBuf = null return -1 } val lenToRead = min(len, lenLeft) for (i in 0 until lenToRead) { b[off + i] = buf[currentBufPos + i] } currentBufPos += lenToRead return lenToRead } } private val hmac = HMAC(config.signatureScheme.replace("-", ""), config.signatureKey) private val context = ZMQ.context(1) val heartbeat = Socket(JupyterSockets.HB) val shell = Socket(JupyterSockets.SHELL) val control = Socket(JupyterSockets.CONTROL) val stdin = Socket(JupyterSockets.STDIN) val iopub = Socket(JupyterSockets.IOPUB) val stdinIn = StdinInputStream() var contextMessage: Message? = null private val currentExecutions = HashSet<Thread>() private val coroutineScope = CoroutineScope(Dispatchers.Default) data class ConnectionExecutionResult<T>( val result: T?, val throwable: Throwable?, val isInterrupted: Boolean, ) fun <T> runExecution(body: () -> T, classLoader: ClassLoader): ConnectionExecutionResult<T> { var execRes: T? = null var execException: Throwable? = null val execThread = thread(contextClassLoader = classLoader) { try { execRes = body() } catch (e: Throwable) { execException = e } } currentExecutions.add(execThread) execThread.join() currentExecutions.remove(execThread) val exception = execException val isInterrupted = exception is ThreadDeath || (exception is ReplException && exception.cause is ThreadDeath) return ConnectionExecutionResult(execRes, exception, isInterrupted) } /** * We cannot use [Thread.interrupt] here because we have no way * to control the code user executes. [Thread.interrupt] will do nothing for * the simple calculation (like `while (true) 1`). Consider replacing with * something more smart in the future. */ fun interruptExecution() { @Suppress("deprecation") while (currentExecutions.isNotEmpty()) { val execution = currentExecutions.firstOrNull() execution?.stop() currentExecutions.remove(execution) } } fun launchJob(runnable: suspend CoroutineScope.() -> Unit) { coroutineScope.launch(block = runnable) } override fun close() { heartbeat.close() shell.close() control.close() stdin.close() iopub.close() context.close() } } private val MESSAGE_DELIMITER: ByteArray = "<IDS|MSG>".map { it.code.toByte() }.toByteArray() class HMAC(algorithm: String, key: String?) { private val mac = if (key?.isNotBlank() == true) Mac.getInstance(algorithm) else null init { mac?.init(SecretKeySpec(key!!.toByteArray(), algorithm)) } @Synchronized operator fun invoke(data: Iterable<ByteArray>): String? = mac?.let { mac -> data.forEach { mac.update(it) } mac.doFinal().toHexString() } operator fun invoke(vararg data: ByteArray): String? = invoke(data.asIterable()) } fun ByteArray.toHexString(): String = joinToString("", transform = { "%02x".format(it) }) fun ZMQ.Socket.sendMessage(msg: Message, hmac: HMAC) { synchronized(this) { msg.id.forEach { sendMore(it) } sendMore(MESSAGE_DELIMITER) val dataJson = Json.encodeToJsonElement(msg.data).jsonObject val signableMsg = listOf("header", "parent_header", "metadata", "content") .map { fieldName -> dataJson[fieldName]?.let { Json.encodeToString(it) }?.toByteArray() ?: emptyJsonObjectStringBytes } sendMore(hmac(signableMsg) ?: "") signableMsg.take(signableMsg.size - 1).forEach { sendMore(it) } send(signableMsg.last()) } } fun ZMQ.Socket.receiveMessage(start: ByteArray, hmac: HMAC): Message { val ids = listOf(start) + generateSequence { recv() }.takeWhile { !it.contentEquals(MESSAGE_DELIMITER) } val sig = recvStr().lowercase() val header = recv() val parentHeader = recv() val metadata = recv() val content = recv() val calculatedSig = hmac(header, parentHeader, metadata, content) if (calculatedSig != null && sig != calculatedSig) { throw SignatureException("Invalid signature: expected $calculatedSig, received $sig - $ids") } fun ByteArray.parseJson(): JsonElement { val json = Json.decodeFromString<JsonElement>(this.toString(Charsets.UTF_8)) return if (json is JsonObject && json.isEmpty()) JsonNull else json } fun JsonElement.orEmptyObject() = if (this is JsonNull) emptyJsonObject else this val dataJson = jsonObject( "header" to header.parseJson(), "parent_header" to parentHeader.parseJson(), "metadata" to metadata.parseJson().orEmptyObject(), "content" to content.parseJson().orEmptyObject() ) val data = Json.decodeFromJsonElement<MessageData>(dataJson) return Message( ids, data ) } object DisabledStdinInputStream : java.io.InputStream() { override fun read(): Int { throw IOException("Input from stdin is unsupported by the client") } }
apache-2.0
da42ca7e7c203b98785ff43544080a7f
35.496644
138
0.64224
4.558256
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2275.kt
1
564
package leetcode import kotlin.math.max /** * https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/ */ class Problem2275 { fun largestCombination(candidates: IntArray): Int { var answer = 0 var i = 1 while (i < 10000000) { var count = 0 for (candidate in candidates) { if (candidate and i > 0) { count++ } } answer = max(answer, count) i = i shl 1 } return answer } }
mit
1e3bdeec6cf4169992ccc1fcaf8b6db1
22.5
88
0.503546
4.240602
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/viewcontroller/overlay/ViewControllerOverlay.kt
1
864
package com.reactnativenavigation.viewcontrollers.viewcontroller.overlay import android.content.Context import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import com.reactnativenavigation.utils.removeFromParent open class ViewControllerOverlay(context: Context) { private val overlay = OverlayLayout(context) open fun add(parent: ViewGroup, view: View, layoutParams: ViewGroup.LayoutParams) { attachOverlayToParent(parent) overlay.addView(view, layoutParams) } fun remove(view: View) { overlay.removeView(view) if (overlay.childCount == 0) overlay.removeFromParent() } private fun attachOverlayToParent(parent: ViewGroup) { if (overlay.parent == null) { parent.addView(overlay, MATCH_PARENT, MATCH_PARENT) } } }
mit
d23749f8c34a594abbb02bf8cb77e6b0
31.037037
87
0.732639
4.595745
false
false
false
false
wix/react-native-navigation
lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/modal/ModalAnimatorTest.kt
1
9542
package com.reactnativenavigation.viewcontrollers.modal import android.app.Activity import org.mockito.kotlin.* import com.reactnativenavigation.BaseTest import com.reactnativenavigation.mocks.SimpleViewController import com.reactnativenavigation.options.* import com.reactnativenavigation.options.animations.ViewAnimationOptions import com.reactnativenavigation.utils.ScreenAnimationListener import com.reactnativenavigation.viewcontrollers.child.ChildControllersRegistry import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import com.reactnativenavigation.views.element.TransitionAnimatorCreator import org.assertj.core.api.Java6Assertions.assertThat import org.junit.Test class ModalAnimatorTest : BaseTest() { private lateinit var uut: ModalAnimator private lateinit var activity: Activity private lateinit var modal1: ViewController<*> private lateinit var root: ViewController<*> private lateinit var modal1View: SimpleViewController.SimpleView private lateinit var rootView: SimpleViewController.SimpleView private lateinit var mockDefaultAnimation: StackAnimationOptions private lateinit var screenAnimationListener: ScreenAnimationListener override fun beforeEach() { val mockTransitionAnimatorCreator = spy(TransitionAnimatorCreator()) val childRegistry = mock<ChildControllersRegistry>() val enter = spy(AnimationOptions()) val exit = spy(AnimationOptions()) screenAnimationListener = mock { } activity = newActivity() modal1View = SimpleViewController.SimpleView(activity) rootView = SimpleViewController.SimpleView(activity) mockDefaultAnimation = StackAnimationOptions().apply { val viewAnimationOptions = ViewAnimationOptions() viewAnimationOptions.enter = enter viewAnimationOptions.exit = exit content = viewAnimationOptions } uut = spy(ModalAnimator(activity, defaultAnimation = mockDefaultAnimation, transitionAnimatorCreator = mockTransitionAnimatorCreator)) modal1 = object : SimpleViewController(activity, childRegistry, "child1", Options()) { override fun createView(): SimpleView { return modal1View } } root = object : SimpleViewController(activity, childRegistry, "root", Options()) { override fun createView(): SimpleView { return rootView } } } @Test fun show_isRunning() { uut.show(modal1, root, TransitionAnimationOptions(), object : ScreenAnimationListener() {}) assertThat(uut.isRunning).isTrue() } @Test fun `show shared elements - should make alpha 0 before animation`() { val sharedElements = SharedElements.parse(newAnimationOptionsJson(true).apply { put("sharedElementTransitions", newSharedElementAnimationOptionsJson()) }) val spyView = spy(modal1View) val mockModal = spy(modal1) whenever(mockModal.createView()).thenReturn(spyView) mockModal.onViewWillAppear() // to avoid wait for render uut.show(mockModal, root, TransitionAnimationOptions(sharedElements = sharedElements), screenAnimationListener) verify(spyView).alpha=0f } @Test fun `show shared elements - should play default fade-in`() { val sharedElements = SharedElements.parse(newAnimationOptionsJson(true).apply { put("sharedElementTransitions", newSharedElementAnimationOptionsJson()) }) val mockModal = spy(modal1) mockModal.onViewWillAppear() // to avoid wait for render uut.show(mockModal, root, TransitionAnimationOptions(sharedElements = sharedElements), screenAnimationListener) verify(mockDefaultAnimation.content.enter).getAnimation(mockModal.view) } @Test fun `dismiss shared elements - should play default fade-out`() { val sharedElements = SharedElements.parse(newAnimationOptionsJson(true).apply { put("sharedElementTransitions", newSharedElementAnimationOptionsJson()) }) val mockModal = spy(modal1) mockModal.onViewWillAppear() // to avoid wait for render uut.show(mockModal, root, TransitionAnimationOptions(sharedElements = sharedElements), screenAnimationListener) verify(mockDefaultAnimation.content.enter).getAnimation(mockModal.view) uut.dismiss(root, mockModal, TransitionAnimationOptions(sharedElements = sharedElements), screenAnimationListener) verify(mockDefaultAnimation.content.exit).getAnimation(mockModal.view) } @Test fun `show - should play shared transition if it has value`() { val sharedElements = SharedElements.parse(newAnimationOptionsJson(true).apply { put("sharedElementTransitions", newSharedElementAnimationOptionsJson()) }) val mockModal = spy(modal1) uut.show(mockModal, root, TransitionAnimationOptions(sharedElements = sharedElements), screenAnimationListener) verify(mockModal).setWaitForRender(any()) } @Test fun `show - should not play shared transition if it does not has value`() { val enter = spy(AnimationOptions(newAnimationOptionsJson(true))) val mockModal = spy(modal1) uut.show(mockModal, root, TransitionAnimationOptions(enter = enter), screenAnimationListener) verify(mockModal, never()).setWaitForRender(any()) } @Test fun `show - play enter animation on appearing if hasValue`() { val enter = spy(AnimationOptions(newAnimationOptionsJson(true))) val exit = spy(AnimationOptions()) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.show(modal1, root, animationOptions, screenAnimationListener) verify(enter).getAnimation(modal1.view) verify(exit, never()).getAnimation(root.view) } @Test fun `show - play default animation on appearing modal if enter does not hasValue`() { val enter = spy(AnimationOptions()) val exit = spy(AnimationOptions()) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.show(modal1, root, animationOptions, screenAnimationListener) verify(uut).getDefaultPushAnimation(modal1.view) verify(enter, never()).getAnimation(modal1.view) verify(exit, never()).getAnimation(root.view) } @Test fun `show - play enter animation on appearing modal, exit on disappearing one`() { val enter = spy(AnimationOptions(newAnimationOptionsJson(true))) val exit = spy(AnimationOptions(newAnimationOptionsJson(true))) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.show(modal1, root, animationOptions, screenAnimationListener) verify(enter).getAnimation(modal1.view) verify(exit).getAnimation(root.view) } @Test fun `show - should not play exit on null disappearing one`() { val enter = spy(AnimationOptions(newAnimationOptionsJson(true))) val exit = spy(AnimationOptions(newAnimationOptionsJson(true))) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.show(modal1, null, animationOptions, screenAnimationListener) verify(enter).getAnimation(modal1.view) verify(exit, never()).getAnimation(root.view) } @Test fun `dismiss - play default animation on disappearing modal if exit does not hasValue`() { val enter = spy(AnimationOptions()) val exit = spy(AnimationOptions()) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.dismiss(root, modal1, animationOptions, screenAnimationListener) verify(uut).getDefaultPopAnimation(modal1.view) verify(enter, never()).getAnimation(any()) verify(exit, never()).getAnimation(any()) } @Test fun `dismiss - play exit animation on disappearing modal, enter on appearing one`() { val enter = spy(AnimationOptions(newAnimationOptionsJson(true))) val exit = spy(AnimationOptions(newAnimationOptionsJson(true))) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.dismiss(root, modal1, animationOptions, screenAnimationListener) verify(exit).getAnimation(modal1.view) verify(enter).getAnimation(root.view) } @Test fun `dismiss - should not play enter on null appearing one`() { val enter = spy(AnimationOptions(newAnimationOptionsJson(true))) val exit = spy(AnimationOptions(newAnimationOptionsJson(true))) val animationOptions = TransitionAnimationOptions(enter = enter, exit = exit) uut.dismiss(null, root, animationOptions, screenAnimationListener) verify(enter, never()).getAnimation(any()) verify(exit).getAnimation(root.view) } @Test fun dismiss_dismissModalDuringShowAnimation() { val showListener = spy<ScreenAnimationListener>() uut.show(modal1, root, TransitionAnimationOptions(), showListener) verify(showListener).onStart() val dismissListener = spy<ScreenAnimationListener>() uut.dismiss(root, modal1, TransitionAnimationOptions(), dismissListener) verify(showListener).onCancel() verify(showListener, never()).onEnd() verify(dismissListener).onEnd() assertThat(uut.isRunning).isFalse() } }
mit
803a1d5ae1576a95b51c30fbdab2146e
43.802817
142
0.711381
5.177428
false
true
false
false
walleth/walleth
app/src/main/java/org/walleth/notifications/TransactionNotificationService.kt
1
4462
package org.walleth.notifications import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.lifecycle.LifecycleService import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import org.kethereum.model.Address import org.koin.android.ext.android.inject import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneOffset import org.walleth.R import org.walleth.data.AppDatabase import org.walleth.data.addresses.AddressBookEntry import org.walleth.data.transactions.TransactionEntity import org.walleth.transactions.getTransactionActivityIntentForHash class TransactionNotificationService : LifecycleService() { private val appDatabase: AppDatabase by inject() private val allThatWantNotificationsLive by lazy { appDatabase.addressBook.allThatWantNotificationsLive() } private var liveDataAllNotifications: LiveData<List<TransactionEntity>>? = null private var addressesToNotify: List<Address> = emptyList() private val alreadyNotified: MutableSet<String> = mutableSetOf() override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) val allTransactionsToNotifyObserver = Observer<List<TransactionEntity>> { txList -> txList?.let { allTransactionsToNotify -> val relevantTransaction = allTransactionsToNotify.firstOrNull { val currentEpochSeconds = LocalDateTime.now().atZone(ZoneOffset.systemDefault()).toEpochSecond() val isRecent = currentEpochSeconds - (it.transaction.creationEpochSecond ?: 0) < 60 !it.transactionState.isPending && isRecent && !alreadyNotified.contains(it.hash) } if (relevantTransaction != null) { alreadyNotified.add(relevantTransaction.hash) val transactionIntent = baseContext.getTransactionActivityIntentForHash(relevantTransaction.hash) val contentIntent = PendingIntent.getActivity(baseContext, 0, transactionIntent, PendingIntent.FLAG_UPDATE_CURRENT) val notificationService = baseContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT > 25) { val channel = NotificationChannel("transactions", NOTIFICATION_CHANNEL_ID_TRANSACTION_NOTIFICATIONS, NotificationManager.IMPORTANCE_HIGH) channel.description = "View and Stop Geth Service" notificationService.createNotificationChannel(channel) } val notification = NotificationCompat.Builder(baseContext, NOTIFICATION_CHANNEL_ID_TRANSACTION_NOTIFICATIONS).apply { setContentTitle("WallETH Transaction") setContentText("Got transaction") setAutoCancel(true) setContentIntent(contentIntent) val myFrom = relevantTransaction.transaction.from // TODO better handle from==null if (myFrom == null || addressesToNotify.contains(myFrom)) { setSmallIcon(R.drawable.notification_minus) } else { setSmallIcon(R.drawable.notification_plus) } }.build() notificationService.notify(NOTIFICATION_ID_TRANSACTION_NOTIFICATIONS, notification) } } } val allThatWantNotificationObserver = Observer<List<AddressBookEntry>> { addressesToNotify -> if (addressesToNotify != null) { liveDataAllNotifications?.removeObserver(allTransactionsToNotifyObserver) liveDataAllNotifications = appDatabase.transactions.getAllTransactionsForAddressLive(addressesToNotify.map { it.address }) liveDataAllNotifications?.observe(this, allTransactionsToNotifyObserver) } } allThatWantNotificationsLive.removeObserver(allThatWantNotificationObserver) allThatWantNotificationsLive.observe(this, allThatWantNotificationObserver) return START_STICKY } }
gpl-3.0
49230c919ca7ccf185a808cf4803eeef
48.032967
161
0.683774
5.662437
false
false
false
false
apollostack/apollo-android
apollo-normalized-cache/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/internal/OperationCacheExtensions.kt
1
4798
package com.apollographql.apollo3.cache.normalized.internal import com.apollographql.apollo3.api.ResponseAdapterCache import com.apollographql.apollo3.api.Fragment import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.cache.normalized.Record import com.apollographql.apollo3.api.ResponseField import com.apollographql.apollo3.api.internal.json.MapJsonReader import com.apollographql.apollo3.api.internal.json.MapJsonWriter import com.apollographql.apollo3.api.ResponseAdapter import com.apollographql.apollo3.api.variables import com.apollographql.apollo3.cache.CacheHeaders import com.apollographql.apollo3.cache.normalized.CacheKey import com.apollographql.apollo3.cache.normalized.CacheKeyResolver import com.apollographql.apollo3.cache.normalized.NormalizedCache import com.apollographql.apollo3.cache.normalized.ReadOnlyNormalizedCache fun <D : Operation.Data> Operation<D>.normalize( data: D, responseAdapterCache: ResponseAdapterCache, cacheKeyResolver: CacheKeyResolver, ) = normalizeInternal( data, responseAdapterCache, cacheKeyResolver, CacheKeyResolver.rootKey().key, adapter(), variables(responseAdapterCache), responseFields()) fun <D : Fragment.Data> Fragment<D>.normalize( data: D, responseAdapterCache: ResponseAdapterCache, cacheKeyResolver: CacheKeyResolver, rootKey: String, ) = normalizeInternal( data, responseAdapterCache, cacheKeyResolver, rootKey, adapter(), variables(responseAdapterCache), responseFields()) private fun <D> normalizeInternal( data: D, responseAdapterCache: ResponseAdapterCache, cacheKeyResolver: CacheKeyResolver, rootKey: String, adapter: ResponseAdapter<D>, variables: Operation.Variables, fieldSets: List<ResponseField.FieldSet>, ): Map<String, Record> { val writer = MapJsonWriter() adapter.toResponse(writer, responseAdapterCache, data) return Normalizer(variables) { responseField, fields -> cacheKeyResolver.fromFieldRecordSet(responseField, fields).let { if (it == CacheKey.NO_KEY) null else it.key } }.normalize(writer.root() as Map<String, Any?>, null, rootKey, fieldSets) } enum class ReadMode { /** * Depth-first traversal. Resolve CacheReferences as they are encountered */ SEQUENTIAL, /** * Breadth-first traversal. Batches CacheReferences at a certain depth and resolve them all at once. This is useful for SQLite */ BATCH, } fun <D : Operation.Data> Operation<D>.readDataFromCache( responseAdapterCache: ResponseAdapterCache, cache: ReadOnlyNormalizedCache, cacheKeyResolver: CacheKeyResolver, cacheHeaders: CacheHeaders, mode: ReadMode = ReadMode.BATCH, ) = readInternal( cache = cache, cacheKeyResolver = cacheKeyResolver, cacheHeaders = cacheHeaders, variables = variables(responseAdapterCache), adapter = adapter(), responseAdapterCache = responseAdapterCache, mode = mode, cacheKey = CacheKeyResolver.rootKey(), fieldSets = responseFields() ) fun <D : Fragment.Data> Fragment<D>.readDataFromCache( cacheKey: CacheKey, responseAdapterCache: ResponseAdapterCache, cache: ReadOnlyNormalizedCache, cacheKeyResolver: CacheKeyResolver, cacheHeaders: CacheHeaders, mode: ReadMode = ReadMode.SEQUENTIAL, ) = readInternal( cacheKey = cacheKey, cache = cache, cacheKeyResolver = cacheKeyResolver, cacheHeaders = cacheHeaders, variables = variables(responseAdapterCache), adapter = adapter(), responseAdapterCache = responseAdapterCache, mode = mode, fieldSets = responseFields() ) private fun <D> readInternal( cacheKey: CacheKey, cache: ReadOnlyNormalizedCache, cacheKeyResolver: CacheKeyResolver, cacheHeaders: CacheHeaders, variables: Operation.Variables, adapter: ResponseAdapter<D>, responseAdapterCache: ResponseAdapterCache, mode: ReadMode = ReadMode.SEQUENTIAL, fieldSets: List<ResponseField.FieldSet>, ): D? { val map = if (mode == ReadMode.BATCH) { CacheBatchReader( cache = cache, cacheHeaders = cacheHeaders, cacheKeyResolver = cacheKeyResolver, variables = variables, rootKey = cacheKey.key, rootFieldSets = fieldSets ).toMap() } else { CacheSequentialReader( cache = cache, cacheHeaders = cacheHeaders, cacheKeyResolver = cacheKeyResolver, variables = variables, rootKey = cacheKey.key, rootFieldSets = fieldSets ).toMap() } val reader = MapJsonReader( root = map, ) return adapter.fromResponse(reader, responseAdapterCache) } fun Collection<Record>?.dependentKeys(): Set<String> { return this?.flatMap { it.fieldKeys() + it.key }?.toSet() ?: emptySet() }
mit
4869797af41fcba22ca25505b0f55825
30.565789
128
0.737391
4.513641
false
false
false
false
Mindera/skeletoid
base/src/test/java/com/mindera/skeletoid/generic/DateUtilsUnitTests.kt
1
886
package com.mindera.skeletoid.generic import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class DateUtilsUnitTest { @Test fun testSameDay() { val after = 1481429921000L val original = 1481429921000L assertTrue(DateUtils.isSameDayOrAfter(after, original)) } @Test fun testAfterYear() { val after = 1481429921000L val original = 1381429921000L assertTrue(DateUtils.isSameDayOrAfter(after, original)) } @Test fun testBeforeYear() { val after = 1381429921000L val original = 1481429921000L assertFalse(DateUtils.isSameDayOrAfter(after, original)) } @Test fun testBeforeDay() { val after = 1480429921000L val original = 1481429921000L assertFalse(DateUtils.isSameDayOrAfter(after, original)) } }
mit
198ca78bf632909cb924bdb7fff12166
21.15
64
0.671558
3.973094
false
true
false
false
ahant-pabi/field-validator
src/test/kotlin/com/github/ahant/validator/validation/Person.kt
1
1046
package com.github.ahant.validator.validation import com.github.ahant.validator.annotation.CollectionType import com.github.ahant.validator.annotation.FieldInfo import com.github.ahant.validator.validation.FieldValidatorType.CUSTOM import com.github.ahant.validator.validation.FieldValidatorType.EMAIL import com.github.ahant.validator.validation.FieldValidatorType.PHONE import com.github.ahant.validator.validation.FieldValidatorType.STRING import java.util.Date /** * Created by ahant on 8/22/2016. */ class Person { @FieldInfo(validatorType = STRING, optional = false) var fullName: String? = null var birthDate: Date? = null var gender: Gender? = null @FieldInfo(name = "contactNumber", validatorType = PHONE, optional = false) @CollectionType var contactNumberList: List<String>? = null @FieldInfo(validatorType = CUSTOM) var address: Address? = null @FieldInfo(name = "email", validatorType = EMAIL) var emailAddress: String? = null @FieldInfo(optional = false) val score: Int = 0 }
apache-2.0
124d8940ed6f2dc1cbcda041a71c51e4
36.357143
79
0.758126
4.085938
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/grammar/symbol/ManageScopeSymbol.kt
1
7318
package com.bajdcc.LALR1.grammar.symbol import com.bajdcc.LALR1.grammar.runtime.RuntimeObject import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder import com.bajdcc.LALR1.grammar.tree.Func import com.bajdcc.LALR1.grammar.type.TokenTools import com.bajdcc.util.HashListMap import com.bajdcc.util.HashListMapEx import com.bajdcc.util.Position import com.bajdcc.util.lexer.token.Token import com.bajdcc.util.lexer.token.TokenType import java.util.* /** * 命名空间管理 * * @author bajdcc */ class ManageScopeSymbol : IQueryScopeSymbol, IQueryBlockSymbol, IManageDataSymbol, IManageScopeSymbol { private var lambdaId = 0 override val symbolList = HashListMap<Any>() override val funcMap = HashListMapEx<String, MutableList<Func>>() private val funcScope = mutableListOf<MutableMap<String, Func>>() private val stkScope = mutableListOf<MutableSet<String>>() private val stkLambdaId = Stack<Int>() private val stkLambdaLine = Stack<Int>() private val symbolsInFutureBlock = mutableSetOf<String>() private val blockLevel = mutableMapOf<BlockType, Int>() private val blockStack = Stack<BlockType>() override val entryName: String get() = ENTRY_NAME override val entryToken: Token get() { val token = Token() token.type = TokenType.ID token.obj = entryName token.position = Position() return token } override val lambda: Func get() { val lambdaId = stkLambdaId.pop() val lambdaLine = stkLambdaLine.pop() return funcMap["$LAMBDA_PREFIX$lambdaId!$lambdaLine"][0] } private val symbolString: String get() { val sb = StringBuilder() sb.append("#### 符号表 ####") sb.append(System.lineSeparator()) symbolList.toList().withIndex().forEach { (i, symbol) -> sb.append(i).append(": ").append("[").append(RuntimeObject.fromObject(symbol).desc).append("] ").append(symbol) sb.append(System.lineSeparator()) } return sb.toString() } private val funcString: String get() { val sb = StringBuilder() sb.append("#### 过程表 ####") sb.append(System.lineSeparator()) var i = 0 for (funcs in funcMap.toList()) { for (func in funcs) { sb.append("----==== #").append(i).append(" ====----") sb.append(System.lineSeparator()) sb.append(func.toString()) sb.append(System.lineSeparator()) sb.append(System.lineSeparator()) i++ } } return sb.toString() } init { enterScope() val entry = mutableListOf<Func>() entry.add(Func(Token())) funcMap.add(ENTRY_NAME, entry) for (type in BlockType.values()) { blockLevel[type] = 0 } } private val currentScope: MutableSet<String> get() = stkScope[stkScope.size - 1] private val currentFuncScope: MutableMap<String, Func> get() = funcScope[funcScope.size - 1] override fun enterScope() { stkScope.add(mutableSetOf()) funcScope.add(mutableMapOf()) symbolsInFutureBlock.forEach { this.registerSymbol(it) } clearFutureArgs() } override fun leaveScope() { stkScope.removeAt(stkScope.size - 1) funcScope.removeAt(funcScope.size - 1) clearFutureArgs() } override fun clearFutureArgs() { symbolsInFutureBlock.clear() } override fun findDeclaredSymbol(name: String): Boolean { if (symbolsInFutureBlock.contains(name)) { return true } if (stkScope.isNotEmpty() && stkScope.reversed().any { it.contains(name) }) return true if (TokenTools.isExternalName(name)) { registerSymbol(name) return true } return false } override fun findDeclaredSymbolDirect(name: String): Boolean { return symbolsInFutureBlock.contains(name) || currentScope.contains(name) } override fun isUniqueSymbolOfBlock(name: String): Boolean { return currentScope.contains(name) } override fun getFuncByName(name: String): Func? { funcScope.indices.reversed().forEach { i -> val f = funcScope[i] val f1 = f[name] if (f1 != null) return f1 for (func in f.values) { val funcName = func.realName if (funcName == name) { return func } } } return null } override fun isLambda(name: String): Boolean { return name.startsWith(LAMBDA_PREFIX) } override fun registerSymbol(name: String) { currentScope.add(name) symbolList.add(name) } override fun registerFunc(func: Func) { if (func.name.type === TokenType.ID) { func.realName = func.name.toRealString() symbolList.add(func.realName) } else { func.realName = LAMBDA_PREFIX + lambdaId++ } val f = mutableListOf<Func>() f.add(func) funcMap.add(func.realName, f) currentFuncScope[func.realName] = func } override fun registerLambda(func: Func) { stkLambdaId.push(lambdaId) stkLambdaLine.push(func.name.position.line) func.name.type = TokenType.ID func.realName = LAMBDA_PREFIX + lambdaId++ + "!" + stkLambdaLine.peek() currentFuncScope[func.realName] = func val f = mutableListOf<Func>() f.add(func) funcMap.add(func.realName, f) } override fun isRegisteredFunc(name: String): Boolean { return funcMap.contains(name) } override fun registerFutureSymbol(name: String): Boolean { return symbolsInFutureBlock.add(name) } fun check(recorder: ISemanticRecorder) { funcMap.toList().flatMap { it }.forEach { it.analysis(recorder) } } override fun toString(): String { return symbolString + funcString } override fun enterBlock(type: BlockType) { when (type) { BlockType.kCycle -> { val level = blockLevel[type]!! blockLevel[type] = level + 1 } BlockType.kFunc, BlockType.kYield -> blockStack.push(type) } } override fun leaveBlock(type: BlockType) { when (type) { BlockType.kCycle -> { val level = blockLevel[type]!! blockLevel[type] = level - 1 } BlockType.kFunc, BlockType.kYield -> if (blockStack.peek() == type) { blockStack.pop() } } } override fun isInBlock(type: BlockType): Boolean { return when (type) { BlockType.kCycle -> blockLevel[type]!! > 0 BlockType.kFunc, BlockType.kYield -> !blockStack.isEmpty() && blockStack.peek() == type } } companion object { private const val ENTRY_NAME = "main" private const val LAMBDA_PREFIX = "~lambda#" } }
mit
60dfb89f3eef8e525f13d883779c0c21
30.304721
127
0.580066
4.388688
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/contacts/ContactImageModelLoader.kt
2
1709
package com.fsck.k9.contacts import com.bumptech.glide.Priority import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.Options import com.bumptech.glide.load.ResourceDecoder import com.bumptech.glide.load.data.DataFetcher import com.bumptech.glide.load.model.ModelLoader import com.bumptech.glide.load.model.ModelLoaderFactory import com.bumptech.glide.load.model.MultiModelLoaderFactory /** * [ModelLoader] implementation that does nothing put pass through [ContactImage] to be handled by our custom * [ResourceDecoder] implementation, [ContactImageBitmapDecoder]. */ class ContactImageModelLoader : ModelLoader<ContactImage, ContactImage> { override fun buildLoadData( contactImage: ContactImage, width: Int, height: Int, options: Options ): ModelLoader.LoadData<ContactImage> { return ModelLoader.LoadData(contactImage, ContactImageDataFetcher(contactImage)) } override fun handles(model: ContactImage) = true } class ContactImageDataFetcher(private val contactImage: ContactImage) : DataFetcher<ContactImage> { override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ContactImage>) { callback.onDataReady(contactImage) } override fun getDataClass() = ContactImage::class.java override fun getDataSource() = DataSource.LOCAL override fun cleanup() = Unit override fun cancel() = Unit } class ContactImageModelLoaderFactory : ModelLoaderFactory<ContactImage, ContactImage> { override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<ContactImage, ContactImage> { return ContactImageModelLoader() } override fun teardown() = Unit }
apache-2.0
23d1d309e4cbce0963ca96f362d40c71
33.877551
109
0.768286
4.557333
false
false
false
false
fashare2015/MVVM-JueJin
net/src/main/kotlin/com/fashare/net/exception/ExceptionFactory.kt
1
1802
package com.fashare.net.exception import com.google.gson.JsonIOException import com.google.gson.JsonParseException import com.google.gson.JsonSyntaxException import org.json.JSONException import retrofit2.HttpException import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.text.ParseException object ExceptionFactory { //未知错误 val UNKNOWN = 1000 //解析错误 val PARSE_ERROR = 1001 //网络错误 val NETWORK_ERROR = 1002 //协议出错 val HTTP_ERROR = 1003 class ServerException(val code: Int, val msg: String) : RuntimeException() fun create(throwable: Throwable): ApiException { val apiException: ApiException if (throwable is ConnectException || throwable is SocketTimeoutException || throwable is UnknownHostException) { apiException = ApiException(throwable, NETWORK_ERROR, "网络连接错误") }else if (throwable is HttpException) { apiException = ApiException(throwable, HTTP_ERROR, "HTTP协议错误: ${throwable.code()}") } else if (throwable is JsonParseException || throwable is JsonSyntaxException || throwable is JsonIOException || throwable is JSONException || throwable is ParseException) { apiException = ApiException(throwable, PARSE_ERROR, "Json 解析错误") } else if (throwable is ServerException) { apiException = ApiException(throwable, throwable.code, throwable.msg) } else { apiException = ApiException(throwable, UNKNOWN, "未知错误") } // Log.e(javaClass.name, apiException.toString()) return apiException } }
mit
ff780848176e4551a0cdfc73f9ac9f6b
31.716981
95
0.672434
4.954286
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/component/validation/ValidationFlags.kt
1
2353
/* * Copyright 2020 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.component.validation import kotlin.math.log2 /** * A list of validation bit flags Acorn internally uses. * Extended validation flags should start at `1 shl 16` * * @author nbilyk */ object ValidationFlags { /** * A flag reserved for the general properties of a component. UiComponentImpl does not contain a validation node * for this by default. */ const val PROPERTIES: Int = 1 shl 1 /** * The size and position of this component's children need to be changed. */ const val LAYOUT: Int = 1 shl 4 /** * Whether a component should be included in layout has changed. (includeInLayout or visible) */ const val LAYOUT_ENABLED: Int = 1 shl 5 const val RESERVED_1: Int = 1 shl 12 const val RESERVED_2: Int = 1 shl 13 const val RESERVED_3: Int = 1 shl 14 const val RESERVED_4: Int = 1 shl 15 /** * Prints out the name of the flag for reserved flags, or the power of two for non-reserved flags. */ fun flagToString(flag: Int): String = when (flag) { PROPERTIES -> "PROPERTIES" LAYOUT -> "LAYOUT" LAYOUT_ENABLED -> "LAYOUT_ENABLED" RESERVED_1 -> "RESERVED_1" RESERVED_2 -> "RESERVED_2" RESERVED_3 -> "RESERVED_3" RESERVED_4 -> "RESERVED_4" else -> log2(flag.toDouble()).toInt().toString() } /** * Using the ValidationFlags list, prints out a comma separated list of the flags this bit mask contains. * For non-reserved flags (flags at least 1 shl 16), the power of two will be printed. * @see ValidationFlags * @see ValidationFlags.flagToString */ fun flagsToString(flags: Int): String { var str = "" for (i in 0..31) { val flag = 1 shl i if (flag and flags > 0) { if (str.isNotEmpty()) str += "," str += flagToString(flag) } } return str } }
apache-2.0
d62292d8443907709eed46d1d29ab40f
27.707317
113
0.690608
3.58689
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/editor/media/EditorMedia.kt
1
13492
package org.wordpress.android.ui.posts.editor.media import android.net.Uri import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.analytics.AnalyticsTracker.Stat.EDITOR_UPLOAD_MEDIA_FAILED import org.wordpress.android.editor.EditorMediaUploadListener import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.MediaActionBuilder import org.wordpress.android.fluxc.model.MediaModel import org.wordpress.android.fluxc.model.MediaModel.MediaUploadState import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.MediaStore import org.wordpress.android.fluxc.store.MediaStore.CancelMediaPayload import org.wordpress.android.fluxc.store.MediaStore.FetchMediaListPayload import org.wordpress.android.fluxc.store.MediaStore.MediaError import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.pages.SnackbarMessageHolder import org.wordpress.android.ui.posts.EditPostRepository import org.wordpress.android.ui.posts.ProgressDialogUiState import org.wordpress.android.ui.posts.ProgressDialogUiState.HiddenProgressDialog import org.wordpress.android.ui.posts.ProgressDialogUiState.VisibleProgressDialog import org.wordpress.android.ui.posts.editor.media.EditorMedia.AddMediaToPostUiState.AddingMediaIdle import org.wordpress.android.ui.posts.editor.media.EditorMedia.AddMediaToPostUiState.AddingMultipleMedia import org.wordpress.android.ui.posts.editor.media.EditorMedia.AddMediaToPostUiState.AddingSingleMedia import org.wordpress.android.ui.uploads.UploadService import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.util.MediaUtilsWrapper import org.wordpress.android.util.NetworkUtilsWrapper import org.wordpress.android.util.StringUtils import org.wordpress.android.util.ToastUtils.Duration import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.SingleLiveEvent import org.wordpress.android.viewmodel.helpers.ToastMessageHolder import java.util.ArrayList import javax.inject.Inject import javax.inject.Named import kotlin.coroutines.CoroutineContext class EditorMedia @Inject constructor( private val updateMediaModelUseCase: UpdateMediaModelUseCase, private val getMediaModelUseCase: GetMediaModelUseCase, private val dispatcher: Dispatcher, private val mediaUtilsWrapper: MediaUtilsWrapper, private val networkUtilsWrapper: NetworkUtilsWrapper, private val addLocalMediaToPostUseCase: AddLocalMediaToPostUseCase, private val addExistingMediaToPostUseCase: AddExistingMediaToPostUseCase, private val retryFailedMediaUploadUseCase: RetryFailedMediaUploadUseCase, private val cleanUpMediaToPostAssociationUseCase: CleanUpMediaToPostAssociationUseCase, private val removeMediaUseCase: RemoveMediaUseCase, private val reattachUploadingMediaUseCase: ReattachUploadingMediaUseCase, private val analyticsUtilsWrapper: AnalyticsUtilsWrapper, private val analyticsTrackerWrapper: AnalyticsTrackerWrapper, @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) : CoroutineScope { // region Fields private var job: Job = Job() override val coroutineContext: CoroutineContext get() = mainDispatcher + job private lateinit var site: SiteModel private lateinit var editorMediaListener: EditorMediaListener private val deletedMediaItemIds = mutableListOf<String>() private val _uiState: MutableLiveData<AddMediaToPostUiState> = MutableLiveData() val uiState: LiveData<AddMediaToPostUiState> = _uiState private val _snackBarMessage = MutableLiveData<Event<SnackbarMessageHolder>>() val snackBarMessage = _snackBarMessage as LiveData<Event<SnackbarMessageHolder>> private val _toastMessage = SingleLiveEvent<Event<ToastMessageHolder>>() val toastMessage: LiveData<Event<ToastMessageHolder>> = _toastMessage // for keeping the media uri while asking for permissions var droppedMediaUris: ArrayList<Uri> = ArrayList() // endregion fun start(site: SiteModel, editorMediaListener: EditorMediaListener) { this.site = site this.editorMediaListener = editorMediaListener _uiState.value = AddingMediaIdle } // region Adding new media to a post fun advertiseImageOptimisationAndAddMedia(uriList: List<Uri>) { if (mediaUtilsWrapper.shouldAdvertiseImageOptimization()) { editorMediaListener.advertiseImageOptimization { addNewMediaItemsToEditorAsync( uriList, false ) } } else { addNewMediaItemsToEditorAsync(uriList, false) } } fun addNewMediaToEditorAsync(mediaUri: Uri, freshlyTaken: Boolean) { addNewMediaItemsToEditorAsync(listOf(mediaUri), freshlyTaken) } fun addNewMediaItemsToEditorAsync(uriList: List<Uri>, freshlyTaken: Boolean) { launch { _uiState.value = if (uriList.size > 1) { AddingMultipleMedia } else { AddingSingleMedia } val allMediaSucceed = addLocalMediaToPostUseCase.addNewMediaToEditorAsync( uriList, site, freshlyTaken, editorMediaListener, true ) if (!allMediaSucceed) { _snackBarMessage.value = Event(SnackbarMessageHolder(UiStringRes(R.string.gallery_error))) } _uiState.value = AddingMediaIdle } } /** * This won't create a MediaModel. It assumes the model was already created. */ fun addGifMediaToPostAsync(localMediaIds: IntArray) { launch { addLocalMediaToPostUseCase.addLocalMediaToEditorAsync( localMediaIds.toList(), editorMediaListener ) } } fun addFreshlyTakenVideoToEditor() { addNewMediaItemsToEditorAsync(listOf(mediaUtilsWrapper.getLastRecordedVideoUri()), true) .also { AnalyticsTracker.track(Stat.EDITOR_ADDED_VIDEO_NEW) } } fun onPhotoPickerMediaChosen(uriList: List<Uri>) { val onlyVideos = uriList.all { mediaUtilsWrapper.isVideo(it.toString()) } if (onlyVideos) { addNewMediaItemsToEditorAsync(uriList, false) } else { advertiseImageOptimisationAndAddMedia(uriList) } } // endregion // region Add existing media to a post fun addExistingMediaToEditorAsync( mediaModels: List<MediaModel>, source: AddExistingMediaSource ) { addExistingMediaToEditorAsync(source, mediaModels.map { it.mediaId }) } fun addExistingMediaToEditorAsync(source: AddExistingMediaSource, mediaIds: LongArray) { addExistingMediaToEditorAsync(source, mediaIds.toList()) } fun addExistingMediaToEditorAsync(source: AddExistingMediaSource, mediaIdList: List<Long>) { launch { addExistingMediaToPostUseCase.addMediaExistingInRemoteToEditorAsync( site, source, mediaIdList, editorMediaListener ) } } // endregion // region Other fun cancelMediaUploadAsync(localMediaId: Int, delete: Boolean) { launch { getMediaModelUseCase .loadMediaByLocalId(listOf(localMediaId)) .firstOrNull() ?.let { mediaModel -> val payload = CancelMediaPayload(site, mediaModel, delete) dispatcher.dispatch(MediaActionBuilder.newCancelMediaUploadAction(payload)) } } } fun refreshBlogMedia() { if (networkUtilsWrapper.isNetworkAvailable()) { val payload = FetchMediaListPayload(site, MediaStore.DEFAULT_NUM_MEDIA_PER_FETCH, false) dispatcher.dispatch(MediaActionBuilder.newFetchMediaListAction(payload)) } else { _toastMessage.value = Event( ToastMessageHolder( R.string.error_media_refresh_no_connection, Duration.SHORT ) ) } } @Deprecated(message = "Blocking method shouldn't be used in new code.") fun updateMediaUploadStateBlocking(uri: Uri, mediaUploadState: MediaUploadState): MediaModel? { return runBlocking { getMediaModelUseCase.createMediaModelFromUri(site.id, uri).mediaModels.firstOrNull() ?.let { updateMediaModelUseCase.updateMediaModel( it, editorMediaListener.getImmutablePost(), mediaUploadState ) it } } } fun retryFailedMediaAsync(failedMediaIds: List<Int>) { launch { retryFailedMediaUploadUseCase.retryFailedMediaAsync(editorMediaListener, failedMediaIds) } } fun purgeMediaToPostAssociationsIfNotInPostAnymoreAsync() { launch { cleanUpMediaToPostAssociationUseCase .purgeMediaToPostAssociationsIfNotInPostAnymore(editorMediaListener.getImmutablePost()) } } fun reattachUploadingMediaForAztec( editPostRepository: EditPostRepository, isAztec: Boolean, editorMediaUploadListener: EditorMediaUploadListener ) { if (isAztec) { reattachUploadingMediaUseCase.reattachUploadingMediaForAztec( editPostRepository, editorMediaUploadListener ) } } /* * When the user deletes a media item that was being uploaded at that moment, we only cancel the * upload but keep the media item in FluxC DB because the user might have deleted it accidentally, * and they can always UNDO the delete action in Aztec. * So, when the user exits then editor (and thus we lose the undo/redo history) we are safe to * physically delete from the FluxC DB those items that have been deleted by the user using backspace. * */ fun definitelyDeleteBackspaceDeletedMediaItemsAsync() { launch { removeMediaUseCase.removeMediaIfNotUploading(deletedMediaItemIds) } } fun updateDeletedMediaItemIds(localMediaId: String) { deletedMediaItemIds.add(localMediaId) UploadService.setDeletedMediaItemIds(deletedMediaItemIds) } // endregion fun cancelAddMediaToEditorActions() { job.cancel() } fun onMediaDeleted( showAztecEditor: Boolean, showGutenbergEditor: Boolean, localMediaId: String ) { updateDeletedMediaItemIds(localMediaId) if (showAztecEditor && !showGutenbergEditor) { // passing false here as we need to keep the media item in case the user wants to undo cancelMediaUploadAsync(StringUtils.stringToInt(localMediaId), false) } else { launch { removeMediaUseCase.removeMediaIfNotUploading(listOf(localMediaId)) } } } fun onMediaUploadError(listener: EditorMediaUploadListener, media: MediaModel, error: MediaError) = launch { val properties: Map<String, Any?> = withContext(bgDispatcher) { analyticsUtilsWrapper .getMediaProperties(media.isVideo, null, media.filePath) .also { it["error_type"] = error.type.name } } analyticsTrackerWrapper.track(EDITOR_UPLOAD_MEDIA_FAILED, properties) listener.onMediaUploadFailed(media.id.toString()) } sealed class AddMediaToPostUiState( val editorOverlayVisibility: Boolean, val progressDialogUiState: ProgressDialogUiState ) { /** * Adding multiple media items at once can take several seconds on slower devices, so we show a blocking * progress dialog in this situation - otherwise the user could accidentally back out of the process * before all items were added */ object AddingMultipleMedia : AddMediaToPostUiState( editorOverlayVisibility = true, progressDialogUiState = VisibleProgressDialog( messageString = UiStringRes(R.string.add_media_progress), cancelable = false, indeterminate = true ) ) object AddingSingleMedia : AddMediaToPostUiState(true, HiddenProgressDialog) object AddingMediaIdle : AddMediaToPostUiState(false, HiddenProgressDialog) } }
gpl-2.0
609a1bccca2b092a2d0da2c2c3370953
39.761329
112
0.690335
5.347602
false
false
false
false
edwardharks/Aircraft-Recognition
app/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/filter/picker/FilterPicker.kt
1
3966
package com.edwardharker.aircraftrecognition.ui.filter.picker import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater.from import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.edwardharker.aircraftrecognition.R import com.edwardharker.aircraftrecognition.model.Filter import com.edwardharker.aircraftrecognition.model.FilterOption import com.edwardharker.aircraftrecognition.ui.bind import com.edwardharker.aircraftrecognition.ui.filter.selectedFilterOptions internal class FilterPicker : LinearLayout { private val filterText by bind<TextView>(R.id.filter_text) private val filterOptionsRecyclerView by bind<RecyclerView>(R.id.filter_options_recycler_view) private val selectedFilterOptions = selectedFilterOptions() private var filter: Filter? = null var selectionListener: (filter: String, filterOption: String) -> Unit = { _, _ -> } constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { orientation = VERTICAL clipToPadding = false clipChildren = false from(context).inflate(R.layout.view_filter_picker, this) filterOptionsRecyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false) } fun bindTo(filter: Filter) { this.filter = filter filterText.text = filter.filterText filterOptionsRecyclerView.adapter = FilterOptionsAdapter(filter.name, filter.filterOptions) } private fun onFilterOptionClicked(filterOption: FilterOption) { filter?.let { if (selectedFilterOptions.isSelected(it.name, filterOption.value)) { selectedFilterOptions.deselect(it.name) } else { selectedFilterOptions.select(it.name, filterOption.value) selectionListener.invoke(it.name, filterOption.value) } filterOptionsRecyclerView.adapter!!.notifyDataSetChanged() } } private inner class FilterOptionsAdapter( val filterName: String, val filterOptions: List<FilterOption> ) : RecyclerView.Adapter<FilterOptionsAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { val filterOption = filterOptions[position] holder.label.text = filterOption.label val selected = selectedFilterOptions.isSelected(filterName, filterOption.value) holder.itemView.isSelected = selected val imageRes = filterOption.imageRes if (imageRes != null) { holder.image.setImageResource(imageRes) } else { holder.image.setImageDrawable(null) } } override fun getItemCount(): Int = filterOptions.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder( from(parent.context).inflate(R.layout.view_filter_option, parent, false) ) private inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) { val label: TextView by lazy { view.findViewById<TextView>(R.id.filter_label) } val image: ImageView by lazy { view.findViewById<ImageView>(R.id.filter_image) } init { view.setOnClickListener { if (adapterPosition >= 0) { onFilterOptionClicked(filterOptions[adapterPosition]) } } } } } }
gpl-3.0
b369f50bcabf24bcbb24253daf944c6e
37.134615
99
0.679526
5.13066
false
false
false
false
mbrlabs/Mundus
editor/src/main/com/mbrlabs/mundus/editor/ui/widgets/ColorPickerField.kt
1
3617
/* * Copyright (c) 2016. See AUTHORS file. * * 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.mbrlabs.mundus.editor.ui.widgets import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Touchable import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.kotcrab.vis.ui.widget.VisTable import com.kotcrab.vis.ui.widget.VisTextButton import com.kotcrab.vis.ui.widget.VisTextField import com.kotcrab.vis.ui.widget.color.ColorPickerAdapter import com.kotcrab.vis.ui.widget.color.ColorPickerListener import com.mbrlabs.mundus.editor.ui.UI /** * An un-editable text field with a color picker. * * The text field shows the color hex value, the button launches a color picker dialog. * * @author Marcus Brummer * @version 08-01-2016 */ class ColorPickerField() : VisTable() { /** * The currently selected color. */ var selectedColor: Color = Color.WHITE.cpy() set(value) { field.set(value) textField.text = "#" + value.toString() } /** * An optional color picker listener. * Will be called if user changed color. */ var colorAdapter: ColorPickerAdapter? = null private val colorPickerListenerInternal: ColorPickerListener private val textField: VisTextField = VisTextField() private val cpBtn: VisTextButton = VisTextButton("Select") init { // setup internal color picker listener colorPickerListenerInternal = object : ColorPickerListener { override fun canceled(oldColor: Color?) { colorAdapter?.canceled(oldColor) } override fun reset(previousColor: Color?, newColor: Color?) { colorAdapter?.reset(previousColor, newColor) } override fun changed(newColor: Color?) { colorAdapter?.changed(newColor) } override fun finished(newColor: Color) { selectedColor = newColor colorAdapter?.finished(newColor) } } textField.isDisabled = true setupUI() setupListeners() } /** * Disables the button for the color picker. */ fun disable(disable: Boolean) { cpBtn.isDisabled = disable if (disable) { cpBtn.touchable = Touchable.disabled } else { cpBtn.touchable = Touchable.enabled } } private fun setupUI() { add<VisTextField>(textField).padRight(5f).fillX().expandX() add(cpBtn).row() } private fun setupListeners() { // selectedColor chooser button cpBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { super.clicked(event, x, y) val colorPicker = UI.colorPicker colorPicker.color = selectedColor colorPicker.listener = colorPickerListenerInternal UI.addActor(colorPicker.fadeIn()) } }) } }
apache-2.0
1cf9fccb2839f6aca6ef8b85aebd1612
31.00885
87
0.645839
4.459926
false
false
false
false
mdaniel/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/detection/Extensions.kt
7
436
package com.intellij.grazie.detection import ai.grazie.nlp.langs.Language import ai.grazie.nlp.langs.alphabet.Alphabet import com.intellij.grazie.jlanguage.Lang fun Lang.toLanguage() = Language.values().find { it.iso == this.iso }!! /** Note that it will return SOME dialect */ fun Language.toLang() = Lang.values().find { it.iso == this.iso }!! val Language.hasWhitespaces: Boolean get() = alphabet.group != Alphabet.Group.ASIAN
apache-2.0
878e9f41ba98cdc3866cf77cd80ef19e
32.538462
71
0.743119
3.488
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeAccessorTypeFix.kt
1
2725
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError class ChangeAccessorTypeFix(element: KtPropertyAccessor) : KotlinQuickFixAction<KtPropertyAccessor>(element) { private fun getType(): KotlinType? = element!!.property.resolveToDescriptorIfAny()?.type?.takeUnless(KotlinType::isError) override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = getType() != null override fun getFamilyName() = KotlinBundle.message("fix.change.accessor.family") override fun getText(): String { val element = element ?: return "" val type = getType() ?: return familyName val renderedType = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) return if (element.isGetter) { KotlinBundle.message("fix.change.accessor.getter", renderedType) } else { KotlinBundle.message("fix.change.accessor.setter.parameter", renderedType) } } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val type = getType()!! val newTypeReference = KtPsiFactory(file).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type)) val typeReference = if (element.isGetter) element.returnTypeReference else element.parameter!!.typeReference val insertedTypeRef = typeReference!!.replaced(newTypeReference) ShortenReferences.DEFAULT.process(insertedTypeRef) } companion object : KotlinSingleIntentionActionFactory() { public override fun createAction(diagnostic: Diagnostic): ChangeAccessorTypeFix? { return diagnostic.psiElement.getNonStrictParentOfType<KtPropertyAccessor>()?.let(::ChangeAccessorTypeFix) } } }
apache-2.0
2cad0bede7f24be2b9087fd566eb3cf1
47.660714
158
0.766972
4.848754
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CascadeIfInspection.kt
1
2745
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.isOneLiner import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getWhenConditionSubjectCandidate import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.IfToWhenIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.idea.intentions.branches import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class CascadeIfInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = ifExpressionVisitor(fun(expression) { val branches = expression.branches if (branches.size <= 2) return if (expression.isOneLiner()) return if (branches.any { it == null || it.lastBlockStatementOrThis() is KtIfExpression } ) return if (expression.isElseIf()) return if (expression.anyDescendantOfType<KtExpressionWithLabel> { it is KtBreakExpression || it is KtContinueExpression } ) return var current: KtIfExpression? = expression var lastSubjectCandidate: KtExpression? = null while (current != null) { val subjectCandidate = current.condition.getWhenConditionSubjectCandidate(checkConstants = false) ?: return if (lastSubjectCandidate != null && !lastSubjectCandidate.matches(subjectCandidate)) return lastSubjectCandidate = subjectCandidate current = current.`else` as? KtIfExpression } holder.registerProblem( expression.ifKeyword, KotlinBundle.message("cascade.if.should.be.replaced.with.when"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(IfToWhenIntention()) ) }) }
apache-2.0
bc59bf1603784c77358b8d95879a0ec6
47.157895
158
0.71949
5.501002
false
false
false
false
all-of-us/workbench
api/src/main/java/org/pmiops/workbench/actionaudit/ActionAuditEvent.kt
1
3334
package org.pmiops.workbench.actionaudit data class ActionAuditEvent constructor( val timestamp: Long, val agentType: AgentType, val agentIdMaybe: Long?, val agentEmailMaybe: String?, val actionId: String, val actionType: ActionType, val targetType: TargetType, val targetPropertyMaybe: String? = null, val targetIdMaybe: Long? = null, val previousValueMaybe: String? = null, val newValueMaybe: String? = null ) { /** * Since Java code can't take advantage of the named constructor parameters, we provide * a traditional Java-style builder. */ data class Builder internal constructor( var timestamp: Long? = null, var agentType: AgentType? = null, var agentIdMaybe: Long? = null, var agentEmailMaybe: String? = null, var actionId: String? = null, var actionType: ActionType? = null, var targetType: TargetType? = null, var targetPropertyMaybe: String? = null, var targetIdMaybe: Long? = null, var previousValueMaybe: String? = null, var newValueMaybe: String? = null ) { fun timestamp(timestamp: Long) = apply { this.timestamp = timestamp } fun agentType(agentType: AgentType) = apply { this.agentType = agentType } fun agentIdMaybe(agentIdMaybe: Long?) = apply { this.agentIdMaybe = agentIdMaybe } fun agentEmailMaybe(agentEmailMaybe: String?) = apply { this.agentEmailMaybe = agentEmailMaybe } fun actionId(actionId: String) = apply { this.actionId = actionId } fun actionType(actionType: ActionType) = apply { this.actionType = actionType } fun targetType(targetType: TargetType) = apply { this.targetType = targetType } fun targetPropertyMaybe(targetPropertyMaybe: String?) = apply { this.targetPropertyMaybe = targetPropertyMaybe } fun targetIdMaybe(targetIdMaybe: Long?) = apply { this.targetIdMaybe = targetIdMaybe } fun previousValueMaybe(previousValueMaybe: String?) = apply { this.previousValueMaybe = previousValueMaybe } fun newValueMaybe(newValueMaybe: String?) = apply { this.newValueMaybe = newValueMaybe } private fun verifyRequiredFields() { if (timestamp == null || agentType == null || actionId == null || actionType == null || targetType == null) { throw IllegalArgumentException("Missing required arguments.") } } fun build(): ActionAuditEvent { verifyRequiredFields() return ActionAuditEvent( timestamp = this.timestamp!!, agentType = agentType!!, agentIdMaybe = agentIdMaybe, agentEmailMaybe = agentEmailMaybe, actionId = actionId!!, actionType = actionType!!, targetType = targetType!!, targetPropertyMaybe = targetPropertyMaybe, targetIdMaybe = targetIdMaybe, previousValueMaybe = previousValueMaybe, newValueMaybe = newValueMaybe) } } companion object { @JvmStatic fun builder(): Builder { return Builder() } } }
bsd-3-clause
ef3a05449e14d320fc9c3dce52acdb04
41.74359
120
0.611578
5.412338
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/FunctionsBefore.kt
13
267
fun foo(<caret>x1: Int = 1, x2: Float, x3: ((Int) -> Int)?) { foo(2, 3.5, null); val y1 = x1; val y2 = x2; val y3 = x3; foo(x3 = null, x1 = 2, x2 = 3.5); } fun bar() { foo(x1 = 2, x2 = 3.5, x3 = null); foo(x3 = null, x1 = 2, x2 = 3.5); }
apache-2.0
c497d371a4b248fde93fbfd816619884
21.25
61
0.438202
2.007519
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeEntityImpl.kt
2
12539
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class TreeEntityImpl(val dataSource: TreeEntityData) : TreeEntity, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, PARENTENTITY_CONNECTION_ID, ) } override val data: String get() = dataSource.data override val children: List<TreeEntity> get() = snapshot.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val parentEntity: TreeEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: TreeEntityData?) : ModifiableWorkspaceEntityBase<TreeEntity, TreeEntityData>(result), TreeEntity.Builder { constructor() : this(TreeEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity TreeEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field TreeEntity#data should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field TreeEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field TreeEntity#children should be initialized") } } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field TreeEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field TreeEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as TreeEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { val parentEntityNew = parents.filterIsInstance<TreeEntity>().single() if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) { this.parentEntity = parentEntityNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } // List of non-abstract referenced types var _children: List<TreeEntity>? = emptyList() override var children: List<TreeEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) { // Backref setup before adding to store if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var parentEntity: TreeEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityClass(): Class<TreeEntity> = TreeEntity::class.java } } class TreeEntityData : WorkspaceEntityData<TreeEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<TreeEntity> { val modifiable = TreeEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): TreeEntity { return getCached(snapshot) { val entity = TreeEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return TreeEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return TreeEntity(data, entitySource) { this.parentEntity = parents.filterIsInstance<TreeEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(TreeEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as TreeEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as TreeEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
76ff61825c4f85d243b8f4c478f45d00
38.184375
170
0.661217
5.286256
false
false
false
false
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/kotlinx/Arrays.kt
1
772
@file:Suppress("unused") package me.ycdev.android.lib.common.kotlinx fun BooleanArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun CharArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun ByteArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun ShortArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun IntArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun LongArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun FloatArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() } fun DoubleArray?.isNullOrEmpty(): Boolean { return this == null || this.isEmpty() }
apache-2.0
247427cb386f9292b18c251ca0805e0c
21.057143
44
0.669689
4.063158
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/webrtc/AudioIndicatorView.kt
2
4183
package org.thoughtcrime.securesms.components.webrtc import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout import org.signal.core.util.DimensionUnit import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.events.CallParticipant import org.thoughtcrime.securesms.service.webrtc.WebRtcActionProcessor import org.thoughtcrime.securesms.util.visible /** * An indicator shown for each participant in a call which shows the state of their audio. */ class AudioIndicatorView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) { companion object { private const val SIDE_BAR_SHRINK_FACTOR = 0.75f } private val barPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL color = Color.WHITE } private val barRect = RectF() private val barWidth = DimensionUnit.DP.toPixels(4f) private val barRadius = DimensionUnit.DP.toPixels(32f) private val barPadding = DimensionUnit.DP.toPixels(4f) private var middleBarAnimation: ValueAnimator? = null private var sideBarAnimation: ValueAnimator? = null private var showAudioLevel = false private var lastAudioLevel: CallParticipant.AudioLevel? = null init { inflate(context, R.layout.audio_indicator_view, this) setWillNotDraw(false) } private val micMuted: View = findViewById(R.id.mic_muted) fun bind(microphoneEnabled: Boolean, level: CallParticipant.AudioLevel?) { micMuted.visible = !microphoneEnabled val wasShowingAudioLevel = showAudioLevel showAudioLevel = microphoneEnabled && level != null if (showAudioLevel) { val scaleFactor = when (level!!) { CallParticipant.AudioLevel.LOWEST -> 0.2f CallParticipant.AudioLevel.LOW -> 0.4f CallParticipant.AudioLevel.MEDIUM -> 0.6f CallParticipant.AudioLevel.HIGH -> 0.8f CallParticipant.AudioLevel.HIGHEST -> 1.0f } middleBarAnimation?.end() middleBarAnimation = createAnimation(middleBarAnimation, height * scaleFactor) middleBarAnimation?.start() sideBarAnimation?.end() var finalHeight = height * scaleFactor if (level != CallParticipant.AudioLevel.LOWEST) { finalHeight *= SIDE_BAR_SHRINK_FACTOR } sideBarAnimation = createAnimation(sideBarAnimation, finalHeight) sideBarAnimation?.start() } if (showAudioLevel != wasShowingAudioLevel || level != lastAudioLevel) { invalidate() } lastAudioLevel = level } private fun createAnimation(current: ValueAnimator?, finalHeight: Float): ValueAnimator { val currentHeight = current?.animatedValue as? Float ?: 0f return ValueAnimator.ofFloat(currentHeight, finalHeight).apply { duration = WebRtcActionProcessor.AUDIO_LEVELS_INTERVAL.toLong() interpolator = DecelerateInterpolator() } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val middleBarHeight = middleBarAnimation?.animatedValue as? Float val sideBarHeight = sideBarAnimation?.animatedValue as? Float if (showAudioLevel && middleBarHeight != null && sideBarHeight != null) { val audioLevelWidth = 3 * barWidth + 2 * barPadding val xOffsetBase = (width - audioLevelWidth) / 2 canvas.drawBar( xOffset = xOffsetBase, size = sideBarHeight ) canvas.drawBar( xOffset = barPadding + barWidth + xOffsetBase, size = middleBarHeight ) canvas.drawBar( xOffset = 2 * (barPadding + barWidth) + xOffsetBase, size = sideBarHeight ) if (middleBarAnimation?.isRunning == true || sideBarAnimation?.isRunning == true) { invalidate() } } } private fun Canvas.drawBar(xOffset: Float, size: Float) { val yOffset = (height - size) / 2 barRect.set(xOffset, yOffset, xOffset + barWidth, height - yOffset) drawRoundRect(barRect, barRadius, barRadius, barPaint) } }
gpl-3.0
1a19d75e6bf55baee9c19b764be3e11d
30.689394
95
0.71934
4.316821
false
false
false
false
jk1/intellij-community
plugins/stats-collector/test/com/intellij/completion/contributors/TestContributor.kt
4
1908
/* * 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.completion.contributors import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder class TestContributor : CompletionContributor() { companion object { var isEnabled = false } override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (!isEnabled) return val type = parameters.completionType val prefix = "EC_$type" val invocationCount = parameters.invocationCount if (invocationCount >= 0) { result.consume(LookupElementBuilder.create("${prefix}_COUNT_0")) } if (invocationCount >= 1) { result.consume(LookupElementBuilder.create("${prefix}_COUNT_1")) } if (invocationCount >= 2) { result.consume(LookupElementBuilder.create("${prefix}_COUNT_2")) } if (invocationCount >= 3) { result.consume(LookupElementBuilder.create("${prefix}_COUNT_3")) } if (invocationCount >= 4) { result.consume(LookupElementBuilder.create("${prefix}_COUNT_4")) } } }
apache-2.0
137488398b76241aba797dbe99d38c55
34.333333
104
0.694444
4.806045
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpConfig.kt
1
1722
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.okhttp import io.ktor.client.engine.* import okhttp3.* /** * A configuration for the [OkHttp] client engine. */ public class OkHttpConfig : HttpClientEngineConfig() { internal var config: OkHttpClient.Builder.() -> Unit = { followRedirects(false) followSslRedirects(false) retryOnConnectionFailure(true) } /** * Allows you to specify a preconfigured [OkHttpClient] instance. */ public var preconfigured: OkHttpClient? = null /** * Specifies the size of cache that keeps recently used [OkHttpClient] instances. * Set this property to `0` to disable caching. */ public var clientCacheSize: Int = 10 /** * Specifies the [WebSocket.Factory] used to create a [WebSocket] instance. * Otherwise, [OkHttpClient] is used directly. */ public var webSocketFactory: WebSocket.Factory? = null /** * Configures [OkHttpClient] using [OkHttpClient.Builder]. */ public fun config(block: OkHttpClient.Builder.() -> Unit) { val oldConfig = config config = { oldConfig() block() } } /** * Adds an [Interceptor] to the [OkHttp] client. */ public fun addInterceptor(interceptor: Interceptor) { config { addInterceptor(interceptor) } } /** * Adds a network [Interceptor] to the [OkHttp] client. */ public fun addNetworkInterceptor(interceptor: Interceptor) { config { addNetworkInterceptor(interceptor) } } }
apache-2.0
fbb5c82b1bfdd7e295a03b8088f83637
24.701493
119
0.626016
4.616622
false
true
false
false
code-disaster/lwjgl3
modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMLinker.kt
4
1059
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package llvm.templates import llvm.* import org.lwjgl.generator.* val LLVMLinker = "LLVMLinker".nativeClass( Module.LLVM, prefixConstant = "LLVM", prefixMethod = "LLVM", binding = LLVM_BINDING_DELEGATE ) { documentation = "" EnumConstant( """ This enum is provided for backwards-compatibility only. It has no effect. ({@code LLVMLinkerMode}) """, "LinkerDestroySource".enum("This is the default behavior.", "0"), "LinkerPreserveSource_Removed".enum("This option has been deprecated and should not be used.") ) LLVMBool( "LinkModules2", """ Links the source module into the destination module. The source module is destroyed. The return value is true if an error occurred, false otherwise. Use the diagnostic handler to get any diagnostic message. """, LLVMModuleRef("Dest", ""), LLVMModuleRef("Src", "") ) }
bsd-3-clause
dc38bc90ade0741b781ff341901ecd92
24.853659
152
0.634561
4.644737
false
false
false
false
BoD/SimpleWatchFace2
app/src/main/kotlin/org/jraf/android/simplewatchface2/watchface/SimpleWatchFaceService.kt
1
33998
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([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 org.jraf.android.simplewatchface2.watchface import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.support.wearable.complications.ComplicationData import android.support.wearable.complications.SystemProviders import android.support.wearable.complications.rendering.ComplicationDrawable import android.support.wearable.watchface.CanvasWatchFaceService import android.support.wearable.watchface.WatchFaceService import android.support.wearable.watchface.WatchFaceStyle import android.util.SparseArray import android.view.SurfaceHolder import android.view.WindowInsets import androidx.annotation.ColorInt import androidx.core.util.set import androidx.core.util.valueIterator import androidx.palette.graphics.Palette import org.jraf.android.simplewatchface2.R import org.jraf.android.simplewatchface2.prefs.WatchfacePrefs import org.jraf.android.simplewatchface2.util.getBitmapFromDrawable import org.jraf.android.simplewatchface2.util.saturated import org.jraf.android.simplewatchface2.util.tinted import org.jraf.android.simplewatchface2.util.withShadow import org.jraf.android.util.log.Log import java.util.Calendar import java.util.TimeZone class SimpleWatchFaceService : CanvasWatchFaceService() { companion object { const val COMPLICATION_ID_LEFT = 1 const val COMPLICATION_ID_TOP = 2 const val COMPLICATION_ID_RIGHT = 3 const val COMPLICATION_ID_BOTTOM = 4 const val COMPLICATION_ID_BACKGROUND = 5 private const val TICK_MAJOR_LENGTH_RATIO = 1F / 7F private const val TICK_MINOR_LENGTH_RATIO = 1F / 16F private const val DOT_MAJOR_RADIUS_RATIO = 1F / 18F private const val DOT_MINOR_RADIUS_RATIO = 1F / 24F private const val NUMBER_MAJOR_SIZE_RATIO = 1F / 4F private const val NUMBER_MINOR_SIZE_RATIO = 1F / 6F private const val CENTER_GAP_LENGTH_RATIO = 1F / 32F private const val COMPLICATION_SMALL_WIDTH_RATIO = 1F / 1.8F private const val COMPLICATION_BIG_WIDTH_RATIO = 1.3F private const val COMPLICATION_BIG_HEIGHT_RATIO = 1F / 2.25F private val COMPLICATION_IDS = intArrayOf( COMPLICATION_ID_LEFT, COMPLICATION_ID_TOP, COMPLICATION_ID_RIGHT, COMPLICATION_ID_BOTTOM, COMPLICATION_ID_BACKGROUND ) } private enum class ComplicationSize { SMALL, BIG; companion object { fun fromComplicationType(complicationType: Int) = when (complicationType) { ComplicationData.TYPE_LARGE_IMAGE, ComplicationData.TYPE_LONG_TEXT -> BIG else -> SMALL } } } inner class SimpleWatchFaceEngine : CanvasWatchFaceService.Engine() { private val prefs by lazy { WatchfacePrefs(this@SimpleWatchFaceService) } private val updateTimeHandler = EngineHandler(this) private var calendar: Calendar = Calendar.getInstance() private val timeZoneReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { calendar.timeZone = TimeZone.getDefault() invalidate() } } private var timeZoneReceiverRegistered = false private var width = 0 private var height = 0 private var centerX = 0F private var centerY = 0F private var shadowRadius = 0F private var digitsMarginVertical = 0F private var tickMinorLength = 0F private var tickMajorLength = 0F private var dotMinorRadius = 0F private var dotMajorRadius = 0F private var numberMinorSize = 0F private var numberMajorSize = 0F private var centerGapLength = 0F private var complicationSmallWidth = 0F private var complicationBigWidth = 0F private var complicationBigHeight = 0F private var dialRadius = 0F @ColorInt private var colorBackground = 0 @ColorInt private var colorHandHour = 0 @ColorInt private var colorHandMinute = 0 @ColorInt private var colorHandSecond = 0 @ColorInt private var colorDial = 0 @ColorInt private var colorShadow = 0 @ColorInt private var colorComplicationsBase = 0 @ColorInt private var colorComplicationsHighlight = 0 private var dialStyle: WatchfacePrefs.DialStyle = WatchfacePrefs.DialStyle.valueOf(WatchfacePrefs.DEFAULT_DIAL_STYLE) private val paintHour = Paint() private val paintMinute = Paint() private val paintSecond = Paint() private val paintTick = Paint() private var ambient = false private var lowBitAmbient = false private var burnInProtection = false private var chinHeight = 0 private val complicationDrawableById = SparseArray<ComplicationDrawable>(COMPLICATION_IDS.size) private val complicationSizeById = SparseArray<ComplicationSize>(COMPLICATION_IDS.size) private var hasBackgroundComplication = false private lateinit var handHourAmbientBitmap: Bitmap private lateinit var handHourActiveBitmap: Bitmap private val handHourBitmap inline get() = if (ambient) handHourAmbientBitmap else handHourActiveBitmap private lateinit var handMinuteAmbientBitmap: Bitmap private lateinit var handMinuteActiveBitmap: Bitmap private val handMinuteBitmap inline get() = if (ambient) handMinuteAmbientBitmap else handMinuteActiveBitmap private lateinit var handSecondBitmap: Bitmap private val shouldTimerBeRunning get() = isVisible && !ambient private val handHourSourceBitmap by lazy { getBitmapFromDrawable(this@SimpleWatchFaceService, R.drawable.hand_hour, width, height) } private val handMinuteSourceBitmap by lazy { getBitmapFromDrawable(this@SimpleWatchFaceService, R.drawable.hand_minute, width, height) } private val handSecondSourceBitmap by lazy { getBitmapFromDrawable(this@SimpleWatchFaceService, R.drawable.hand_second, width, height) } // TODO: Reset this if the font changes private val numberTextBounds: Map<String, Rect> by lazy { val res = mutableMapOf<String, Rect>() for (numberIndex in 0..23) { val textSize = if (numberIndex % 3 == 0) numberMajorSize else numberMinorSize paintTick.textSize = textSize val textBounds = Rect() val text = numberIndex.toString() paintTick.getTextBounds(text, 0, text.length, textBounds) res[text] = textBounds } res } private var useBackgroundPalette: Boolean = true private var backgroundPalette: Palette? = null override fun onCreate(holder: SurfaceHolder?) { super.onCreate(holder) setWatchFaceStyle( WatchFaceStyle.Builder(this@SimpleWatchFaceService) .setAcceptsTapEvents(true) .setHideNotificationIndicator(true) .setHideStatusBar(true) .build() ) loadPrefs() colorShadow = 0x80000000.toInt() shadowRadius = resources.getDimensionPixelSize(R.dimen.shadow_radius).toFloat() digitsMarginVertical = resources.getDimensionPixelSize(R.dimen.digits_margin_vertical).toFloat() paintHour.isFilterBitmap = true paintMinute.isFilterBitmap = true paintSecond.isFilterBitmap = true paintTick.strokeWidth = resources.getDimensionPixelSize(R.dimen.tick_width).toFloat() paintTick.textAlign = Paint.Align.CENTER paintTick.typeface = Typeface.createFromAsset(assets, "fonts/Oswald-Medium.ttf") initComplications() updateComplicationDrawableColors() prefs.sharedPreferences.registerOnSharedPreferenceChangeListener(onPrefsChanged) } override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { super.onSurfaceChanged(holder, format, width, height) this.width = width this.height = height centerX = width / 2F centerY = height / 2F tickMinorLength = centerX * TICK_MINOR_LENGTH_RATIO tickMajorLength = centerX * TICK_MAJOR_LENGTH_RATIO dotMinorRadius = centerX * DOT_MINOR_RADIUS_RATIO dotMajorRadius = centerX * DOT_MAJOR_RADIUS_RATIO numberMinorSize = centerX * NUMBER_MINOR_SIZE_RATIO numberMajorSize = centerX * NUMBER_MAJOR_SIZE_RATIO centerGapLength = centerX * CENTER_GAP_LENGTH_RATIO complicationSmallWidth = centerX * COMPLICATION_SMALL_WIDTH_RATIO complicationBigWidth = centerX * COMPLICATION_BIG_WIDTH_RATIO complicationBigHeight = centerY * COMPLICATION_BIG_HEIGHT_RATIO // Complications updateComplicationDrawableBounds() updatePaints() initAmbientBitmaps() updateBitmaps() } override fun onApplyWindowInsets(insets: WindowInsets) { super.onApplyWindowInsets(insets) chinHeight = insets.systemWindowInsetBottom } override fun onPropertiesChanged(properties: Bundle) { super.onPropertiesChanged(properties) lowBitAmbient = properties.getBoolean(WatchFaceService.PROPERTY_LOW_BIT_AMBIENT, false) burnInProtection = properties.getBoolean(WatchFaceService.PROPERTY_BURN_IN_PROTECTION, false) // Complications for (complicationDrawable in complicationDrawableById.valueIterator()) { complicationDrawable.setLowBitAmbient(lowBitAmbient) complicationDrawable.setBurnInProtection(burnInProtection) } updatePaints() } override fun onVisibilityChanged(visible: Boolean) { super.onVisibilityChanged(visible) if (visible) { registerReceiver() calendar.timeZone = TimeZone.getDefault() invalidate() } else { unregisterReceiver() } updateTimer() } override fun onAmbientModeChanged(inAmbientMode: Boolean) { super.onAmbientModeChanged(inAmbientMode) ambient = inAmbientMode updatePaints() // Complications for (complicationDrawable in complicationDrawableById.valueIterator()) { complicationDrawable.setInAmbientMode(inAmbientMode) } updateTimer() } override fun onTimeTick() { super.onTimeTick() invalidate() } override fun onDestroy() { updateTimeHandler.removeCallbacksAndMessages(null) prefs.sharedPreferences.unregisterOnSharedPreferenceChangeListener(onPrefsChanged) super.onDestroy() } private fun updateComplicationDrawableColors() { for (complicationId in COMPLICATION_IDS.filterNot { it == COMPLICATION_ID_BACKGROUND }) { val complicationDrawable = complicationDrawableById[complicationId] val complicationSize = complicationSizeById[complicationId] // Active mode complicationDrawable.setBorderColorActive(if (complicationSize == ComplicationSize.SMALL) colorComplicationsHighlight else Color.TRANSPARENT) complicationDrawable.setRangedValuePrimaryColorActive(colorComplicationsHighlight) complicationDrawable.setTextColorActive(colorComplicationsBase) complicationDrawable.setTitleColorActive(colorComplicationsBase) complicationDrawable.setIconColorActive(colorComplicationsBase) complicationDrawable.setTextSizeActive(resources.getDimensionPixelSize(R.dimen.complication_textSize)) complicationDrawable.setTitleSizeActive(resources.getDimensionPixelSize(R.dimen.complication_titleSize)) complicationDrawable.setBackgroundColorActive(resources.getColor(R.color.complication_background, null)) // Ambient mode complicationDrawable.setBorderColorAmbient(Color.TRANSPARENT) complicationDrawable.setRangedValuePrimaryColorAmbient(Color.WHITE) complicationDrawable.setTextColorAmbient(Color.WHITE) complicationDrawable.setTitleColorAmbient(Color.WHITE) complicationDrawable.setIconColorAmbient(Color.WHITE) complicationDrawable.setTextSizeAmbient(resources.getDimensionPixelSize(R.dimen.complication_textSize)) complicationDrawable.setTitleSizeAmbient(resources.getDimensionPixelSize(R.dimen.complication_titleSize)) complicationDrawable.setBackgroundColorAmbient(Color.TRANSPARENT) } } private fun loadPrefs() { colorBackground = prefs.colorBackground colorHandHour = prefs.colorHandHour colorHandMinute = prefs.colorHandMinute colorHandSecond = prefs.colorHandSecond colorDial = prefs.colorDial colorComplicationsBase = prefs.colorComplicationsBase colorComplicationsHighlight = prefs.colorComplicationsHighlight dialStyle = WatchfacePrefs.DialStyle.valueOf(prefs.dialStyle) useBackgroundPalette = prefs.colorAuto } private fun updatePaints() { if (!ambient) { // Active mode paintTick.color = colorDial paintHour.isAntiAlias = true paintMinute.isAntiAlias = true paintSecond.isAntiAlias = true paintTick.isAntiAlias = true paintTick.setShadowLayer(shadowRadius, 0F, 0F, colorShadow) } else { // Ambient mode // paintTick.color = colorDial.grayScale() paintTick.color = colorDial paintHour.isAntiAlias = !lowBitAmbient paintMinute.isAntiAlias = !lowBitAmbient paintTick.isAntiAlias = !lowBitAmbient paintTick.clearShadowLayer() } } private fun initAmbientBitmaps() { handHourAmbientBitmap = handHourSourceBitmap .tinted(Color.WHITE) .withShadow(shadowRadius, colorShadow) handMinuteAmbientBitmap = handMinuteSourceBitmap .tinted(Color.WHITE) .withShadow(shadowRadius, colorShadow) } private fun updateBitmaps() { handHourActiveBitmap = handHourSourceBitmap .tinted(colorHandHour) .withShadow(shadowRadius, colorShadow) handMinuteActiveBitmap = handMinuteSourceBitmap .tinted(colorHandMinute) .withShadow(shadowRadius, colorShadow) handSecondBitmap = handSecondSourceBitmap .tinted(colorHandSecond) .withShadow(shadowRadius, colorShadow) } private fun updateColorsWithPalette() { val backgroundPalette = backgroundPalette if (useBackgroundPalette && backgroundPalette != null) { val saturatedDominantColor = backgroundPalette.getDominantColor(Color.RED).saturated() colorHandHour = Color.WHITE colorHandMinute = Color.WHITE colorHandSecond = saturatedDominantColor colorDial = saturatedDominantColor colorComplicationsBase = Color.WHITE colorComplicationsHighlight = saturatedDominantColor } } private fun initComplications() { val topComplicationDrawable = ComplicationDrawable(this@SimpleWatchFaceService).apply { setNoDataText("--") } complicationDrawableById[COMPLICATION_ID_TOP] = topComplicationDrawable complicationSizeById[COMPLICATION_ID_TOP] = ComplicationSize.SMALL setDefaultSystemComplicationProvider(COMPLICATION_ID_TOP, SystemProviders.NEXT_EVENT, ComplicationData.TYPE_LONG_TEXT) val rightComplicationDrawable = ComplicationDrawable(this@SimpleWatchFaceService).apply { setNoDataText("--") } complicationDrawableById[COMPLICATION_ID_RIGHT] = rightComplicationDrawable complicationSizeById[COMPLICATION_ID_RIGHT] = ComplicationSize.SMALL setDefaultSystemComplicationProvider(COMPLICATION_ID_RIGHT, SystemProviders.STEP_COUNT, ComplicationData.TYPE_SHORT_TEXT) val bottomComplicationDrawable = ComplicationDrawable(this@SimpleWatchFaceService).apply { setNoDataText("--") } complicationDrawableById[COMPLICATION_ID_BOTTOM] = bottomComplicationDrawable complicationSizeById[COMPLICATION_ID_BOTTOM] = ComplicationSize.SMALL setDefaultSystemComplicationProvider(COMPLICATION_ID_BOTTOM, SystemProviders.DATE, ComplicationData.TYPE_LONG_TEXT) val leftComplicationDrawable = ComplicationDrawable(this@SimpleWatchFaceService).apply { setNoDataText("--") } complicationDrawableById[COMPLICATION_ID_LEFT] = leftComplicationDrawable complicationSizeById[COMPLICATION_ID_LEFT] = ComplicationSize.SMALL setDefaultSystemComplicationProvider(COMPLICATION_ID_LEFT, SystemProviders.DAY_OF_WEEK, ComplicationData.TYPE_SHORT_TEXT) val backgroundComplicationDrawable = ComplicationDrawable(this@SimpleWatchFaceService).apply { setNoDataText("--") } backgroundComplicationDrawable.setBorderWidthActive(0) backgroundComplicationDrawable.setBorderWidthAmbient(0) complicationDrawableById[COMPLICATION_ID_BACKGROUND] = backgroundComplicationDrawable setActiveComplications(*COMPLICATION_IDS) } private fun updateComplicationDrawableBounds() { val horizMargin = Math.max(numberTextBounds.getValue("3").width(), numberTextBounds.getValue("9").width()) val vertMargin = Math.max(numberTextBounds.getValue("0").height(), numberTextBounds.getValue("6").height()) // Left val leftCmplWidth = complicationSmallWidth val leftCmplLeft = horizMargin / 2 + centerX / 2 - leftCmplWidth / 2 val leftCmplTop = centerY - leftCmplWidth / 2 val leftCmplBounds = Rect( leftCmplLeft.toInt(), leftCmplTop.toInt(), (leftCmplLeft + leftCmplWidth).toInt(), (leftCmplTop + leftCmplWidth).toInt() ) complicationDrawableById[COMPLICATION_ID_LEFT].bounds = leftCmplBounds // Right val rightCmplWidth = complicationSmallWidth val rightCmplLeft = centerX * 2 - rightCmplWidth - leftCmplLeft val rightCmplTop = centerY - rightCmplWidth / 2 val rightCmplBounds = Rect( rightCmplLeft.toInt(), rightCmplTop.toInt(), (rightCmplLeft + rightCmplWidth).toInt(), (rightCmplTop + rightCmplWidth).toInt() ) complicationDrawableById[COMPLICATION_ID_RIGHT].bounds = rightCmplBounds // Top val topCmplIsSmall = complicationSizeById[COMPLICATION_ID_TOP] == ComplicationSize.SMALL val topCmplWidth = if (topCmplIsSmall) complicationSmallWidth else complicationBigWidth val topCmplHeight = if (topCmplIsSmall) complicationSmallWidth else complicationBigHeight val topCmplLeft = centerX - topCmplWidth / 2 val topCmplTop = if (topCmplIsSmall) vertMargin / 2 + centerY / 2 - topCmplHeight / 2 else vertMargin / 2 + rightCmplTop / 2 - topCmplHeight / 2 val topCmplBounds = Rect( topCmplLeft.toInt(), topCmplTop.toInt(), (topCmplLeft + topCmplWidth).toInt(), (topCmplTop + topCmplHeight).toInt() ) complicationDrawableById[COMPLICATION_ID_TOP].bounds = topCmplBounds // Bottom val bottomCmplIsSmall = complicationSizeById[COMPLICATION_ID_BOTTOM] == ComplicationSize.SMALL val bottomCmplWidth = if (bottomCmplIsSmall) complicationSmallWidth else complicationBigWidth val bottomCmplHeight = if (bottomCmplIsSmall) complicationSmallWidth else complicationBigHeight val bottomCmplLeft = centerX - bottomCmplWidth / 2 val bottomCmplTop = centerY * 2 - (if (bottomCmplIsSmall) vertMargin / 2 + centerY / 2 - bottomCmplHeight / 2 else vertMargin / 2 + rightCmplTop / 2 - bottomCmplHeight / 2) - bottomCmplHeight val bottomCmplBounds = Rect( bottomCmplLeft.toInt(), bottomCmplTop.toInt(), (bottomCmplLeft + bottomCmplWidth).toInt(), (bottomCmplTop + bottomCmplHeight).toInt() ) complicationDrawableById[COMPLICATION_ID_BOTTOM].bounds = bottomCmplBounds // Background complicationDrawableById[COMPLICATION_ID_BACKGROUND].bounds = Rect( 0, 0, width, height ) } override fun onComplicationDataUpdate(complicationId: Int, complicationData: ComplicationData) { complicationDrawableById[complicationId].setComplicationData(complicationData) complicationSizeById[complicationId] = ComplicationSize.fromComplicationType(complicationData.type) updateComplicationDrawableBounds() updateComplicationDrawableColors() if (complicationId == COMPLICATION_ID_BACKGROUND) { Log.d("Received background complication type=${complicationData.type} size=${complicationSizeById[complicationId]}") hasBackgroundComplication = complicationData.type !in intArrayOf( ComplicationData.TYPE_EMPTY, ComplicationData.TYPE_NO_PERMISSION, ComplicationData.TYPE_NO_DATA ) if (hasBackgroundComplication) { val drawable = complicationData.largeImage.loadDrawable(this@SimpleWatchFaceService) if (drawable is BitmapDrawable) { backgroundPalette = Palette.from(drawable.bitmap).generate() updateColorsWithPalette() updatePaints() updateBitmaps() updateComplicationDrawableColors() updateTimer() } } } invalidate() } override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { when (tapType) { WatchFaceService.TAP_TYPE_TAP -> { // Exclude the background complication for (complicationId in COMPLICATION_IDS.filterNot { it == COMPLICATION_ID_BACKGROUND }) { val complicationDrawable = complicationDrawableById.get(complicationId) val successfulTap = complicationDrawable.onTap(x, y) if (successfulTap) return } } } invalidate() } override fun onDraw(canvas: Canvas, bounds: Rect) { val now = System.currentTimeMillis() calendar.timeInMillis = now - now % 1000 // Background / background complication drawBackground(canvas, now) // Dial when (dialStyle) { WatchfacePrefs.DialStyle.DOTS_4 -> drawDots(canvas, 4) WatchfacePrefs.DialStyle.DOTS_12 -> drawDots(canvas, 12) WatchfacePrefs.DialStyle.TICKS_4 -> drawTicks(canvas, 4) WatchfacePrefs.DialStyle.TICKS_12 -> drawTicks(canvas, 12) WatchfacePrefs.DialStyle.NUMBERS_4 -> drawNumbers(canvas, 4) WatchfacePrefs.DialStyle.NUMBERS_12 -> drawNumbers(canvas, 12) WatchfacePrefs.DialStyle.NOTHING -> { // Do nothing } } // Other complications drawOtherComplications(canvas, now) // Hands drawHands(canvas) } @Suppress("NOTHING_TO_INLINE") private inline fun drawBackground(canvas: Canvas, currentTimeMillis: Long) { if (!ambient) { if (hasBackgroundComplication) { // Complication val complicationDrawable = complicationDrawableById.get(COMPLICATION_ID_BACKGROUND) complicationDrawable.draw(canvas, currentTimeMillis) } else { // Color canvas.drawColor(colorBackground) } } else { canvas.drawColor(Color.BLACK) } } @Suppress("NOTHING_TO_INLINE") private inline fun drawDots(canvas: Canvas, num: Int) { for (dotIndex in 0 until num) { val rotation = (dotIndex.toDouble() * Math.PI * 2.0 / num).toFloat() val dotRadius = if (num > 4 && dotIndex % 3 == 0) dotMajorRadius else dotMinorRadius val cx = Math.sin(rotation.toDouble()).toFloat() * (centerX - dotMajorRadius) + centerX val cy = (-Math.cos(rotation.toDouble())).toFloat() * (centerX - dotMajorRadius) + centerY canvas.drawCircle( cx, cy, dotRadius, paintTick ) } } @Suppress("NOTHING_TO_INLINE") private inline fun drawTicks(canvas: Canvas, num: Int) { val innerMinorTickRadius = centerX - tickMinorLength val innerMajorTickRadius = centerX - tickMajorLength val outerTickRadius = centerX for (tickIndex in 0 until num) { val rotation = (tickIndex.toDouble() * Math.PI * 2.0 / num).toFloat() val innerTickRadius = if (num > 4 && tickIndex % 3 == 0) innerMajorTickRadius else innerMinorTickRadius val innerX = Math.sin(rotation.toDouble()).toFloat() * innerTickRadius val innerY = (-Math.cos(rotation.toDouble())).toFloat() * innerTickRadius val outerX = Math.sin(rotation.toDouble()).toFloat() * outerTickRadius val outerY = (-Math.cos(rotation.toDouble())).toFloat() * outerTickRadius canvas.drawLine( centerX + innerX, centerY + innerY, centerX + outerX, centerY + outerY, paintTick ) } } @Suppress("NOTHING_TO_INLINE") private inline fun drawNumbers(canvas: Canvas, num: Int) { for (numberIndex in 0..11) { // Don't draw minor numbers if we only want major ones if (num == 4 && numberIndex % 3 != 0) continue val text = getNumberText(numberIndex) val rotation = (numberIndex.toDouble() * Math.PI * 2.0 / num).toFloat() val textSize = if (numberIndex % 3 == 0) numberMajorSize else numberMinorSize paintTick.textSize = textSize val textHeight = numberTextBounds.getValue(text).height() // Initialize the radius the first time // TODO: Reset this if the font changes if (dialRadius == 0F) { // Calculate the radius using a margin dialRadius = centerX - textHeight / 2 - digitsMarginVertical } val cx = Math.sin(rotation.toDouble()).toFloat() * dialRadius + centerX var cy = (-Math.cos(rotation.toDouble())).toFloat() * dialRadius + centerY val diff = (centerY * 2 - chinHeight) - (cy + textHeight / 2) if (diff < 0) { cy += diff } canvas.drawText( text, cx, cy + textHeight / 2, paintTick ) } } @Suppress("NOTHING_TO_INLINE") private inline fun getNumberText(numberIndex: Int): String { return if (!prefs.smartNumbers) { if (numberIndex == 0) "12" else numberIndex.toString() } else { val curHour = calendar[Calendar.HOUR_OF_DAY] if (curHour < 12) { if (numberIndex < curHour) (numberIndex + 12).toString() else numberIndex.toString() } else { if (numberIndex < curHour - 12) numberIndex.toString() else (numberIndex + 12).toString() } } } @Suppress("NOTHING_TO_INLINE") private inline fun drawOtherComplications(canvas: Canvas, currentTimeMillis: Long) { if (ambient) { // Draw only the top complications val complicationDrawable = complicationDrawableById.get(COMPLICATION_ID_TOP) complicationDrawable.draw(canvas, currentTimeMillis) } else { // Draw all of them, except the background complication for (complicationId in COMPLICATION_IDS.filterNot { it == COMPLICATION_ID_BACKGROUND }) { val complicationDrawable = complicationDrawableById.get(complicationId) complicationDrawable.draw(canvas, currentTimeMillis) } } } @Suppress("NOTHING_TO_INLINE") private inline fun drawHands(canvas: Canvas) { val seconds = calendar[Calendar.SECOND] val secondsRotation = seconds * 6F val minutes = calendar[Calendar.MINUTE] val minutesRotation = minutes * 6F + (seconds / 60F) * 6F val hoursRotation = calendar[Calendar.HOUR] * 30F + (minutes / 60F) * 30F canvas.save() // Hour canvas.rotate(hoursRotation, centerX, centerY) canvas.drawBitmap(handHourBitmap, 0F, 0F, paintHour) // Minute canvas.rotate(minutesRotation - hoursRotation, centerX, centerY) canvas.drawBitmap(handMinuteBitmap, 0F, 0F, paintMinute) // Second if (!ambient) { canvas.rotate(secondsRotation - minutesRotation, centerX, centerY) canvas.drawBitmap(handSecondBitmap, 0F, 0F, paintSecond) } canvas.restore() } private fun registerReceiver() { if (timeZoneReceiverRegistered) return timeZoneReceiverRegistered = true val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED) registerReceiver(timeZoneReceiver, filter) } private fun unregisterReceiver() { if (!timeZoneReceiverRegistered) return timeZoneReceiverRegistered = false unregisterReceiver(timeZoneReceiver) } private fun updateTimer() { updateTimeHandler.removeCallbacksAndMessages(null) updateTimeHandler.sendEmptyMessage(0) } /** * Handle updating the time periodically in interactive mode. */ fun handleUpdateTimeMessage() { invalidate() if (shouldTimerBeRunning) { val now = System.currentTimeMillis() val delay = 1000 - now % 1000 updateTimeHandler.sendEmptyMessageDelayed(0, delay) } } private val onPrefsChanged = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> loadPrefs() updateColorsWithPalette() updatePaints() updateBitmaps() updateComplicationDrawableColors() updateTimer() } } override fun onCreateEngine() = SimpleWatchFaceEngine() }
gpl-3.0
1d5df12c669f7eb5ce03dbb7ca6bab69
41.49875
187
0.62086
5.130999
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/controls/behaviours/MouseDragPlane.kt
2
4618
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2020 SciView developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package graphics.scenery.controls.behaviours import graphics.scenery.BoundingGrid import graphics.scenery.Camera import graphics.scenery.Node import graphics.scenery.utils.LazyLogger import org.joml.Vector3f import org.scijava.ui.behaviour.DragBehaviour import org.scijava.ui.behaviour.ScrollBehaviour import kotlin.reflect.KProperty /** * Drag nodes along the viewplane by mouse. * * @author Kyle Harrington * @author Jan Tiemann */ open class MouseDragPlane( protected val name: String, camera: () -> Camera?, protected val alternativeTargetNode: (() -> Node?)? = null, protected var debugRaycast: Boolean = false, protected var ignoredObjects: List<Class<*>> = listOf<Class<*>>(BoundingGrid::class.java), protected val mouseSpeed: () -> Float = { 0.25f }, protected val fpsSpeedSlow: () -> Float = { 0.05f } ) : DragBehaviour, ScrollBehaviour, WithCameraDelegateBase(camera) { protected val logger by LazyLogger() protected var currentNode: Node? = null private var lastX = 0 private var lastY = 0 /** * This function is called upon mouse down and initializes the camera control * with the current window size. * * x position in window * y position in window */ override fun init(x: Int, y: Int) { if (alternativeTargetNode != null) { currentNode = alternativeTargetNode.invoke() } else { cam?.let { cam -> val matches = cam.getNodesForScreenSpacePosition(x, y, ignoredObjects, debugRaycast) currentNode = matches.matches.firstOrNull()?.node } } lastX = x lastY = y } override fun drag(x: Int, y: Int) { val targetedNode = currentNode cam?.let { if (targetedNode == null || !targetedNode.lock.tryLock()) return targetedNode.ifSpatial { it.right.mul((x - lastX) * fpsSpeedSlow() * mouseSpeed(), dragPosUpdater) position.add(dragPosUpdater) it.up.mul((lastY - y) * fpsSpeedSlow() * mouseSpeed(), dragPosUpdater) position.add(dragPosUpdater) needsUpdate = true } targetedNode.lock.unlock() lastX = x lastY = y } } override fun end(x: Int, y: Int) { // intentionally empty. A new click will overwrite the running variables. } override fun scroll(wheelRotation: Double, isHorizontal: Boolean, x: Int, y: Int) { val targetedNode = currentNode cam?.let { if (targetedNode == null || !targetedNode.lock.tryLock()) return it.forward.mul( wheelRotation.toFloat() * fpsSpeedSlow() * mouseSpeed(), scrollPosUpdater ) targetedNode.ifSpatial { position.add(scrollPosUpdater) needsUpdate = true } targetedNode.lock.unlock() } } //aux vars to prevent from re-creating them over and over private val dragPosUpdater: Vector3f = Vector3f() private val scrollPosUpdater: Vector3f = Vector3f() }
lgpl-3.0
9ea7ec9ba632822f5b9ec603438d411d
34.251908
100
0.658727
4.505366
false
false
false
false
spotify/heroic
heroic-core/src/main/java/com/spotify/heroic/shell/task/parameters/MetadataFetchParameters.kt
1
1459
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.shell.task.parameters import com.spotify.heroic.common.OptionalLimit import org.kohsuke.args4j.Argument import org.kohsuke.args4j.Option import java.util.* internal class MetadataFetchParameters : QueryParamsBase() { @Option(name = "-g", aliases = ["--group"], usage = "Backend group to use", metaVar = "<group>") val group = Optional.empty<String>() @Option(name = "--limit", aliases = ["--limit"], usage = "Limit the number of printed entries") override val limit: OptionalLimit = OptionalLimit.empty() @Argument override val query = ArrayList<String>() }
apache-2.0
795a06818cbefb2359cb737e4ea60eb4
37.394737
100
0.732008
4.168571
false
false
false
false
mikepenz/FastAdapter
app/src/main/java/com/mikepenz/fastadapter/app/EndlessScrollListActivity.kt
1
7905
package com.mikepenz.fastadapter.app import android.graphics.Color import android.os.Bundle import android.os.Handler import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import com.mikepenz.fastadapter.GenericItem import com.mikepenz.fastadapter.adapters.FastItemAdapter import com.mikepenz.fastadapter.adapters.GenericFastItemAdapter import com.mikepenz.fastadapter.adapters.GenericItemAdapter import com.mikepenz.fastadapter.adapters.ItemAdapter.Companion.items import com.mikepenz.fastadapter.app.databinding.ActivitySampleBinding import com.mikepenz.fastadapter.app.items.SimpleItem import com.mikepenz.fastadapter.drag.ItemTouchCallback import com.mikepenz.fastadapter.drag.SimpleDragCallback import com.mikepenz.fastadapter.listeners.ItemFilterListener import com.mikepenz.fastadapter.scroll.EndlessRecyclerOnScrollListener import com.mikepenz.fastadapter.select.getSelectExtension import com.mikepenz.fastadapter.ui.items.ProgressItem import com.mikepenz.fastadapter.utils.DragDropUtil import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.library.materialdesigniconic.MaterialDesignIconic import com.mikepenz.iconics.utils.actionBar import com.mikepenz.iconics.utils.colorInt import java.util.* class EndlessScrollListActivity : AppCompatActivity(), ItemTouchCallback, ItemFilterListener<GenericItem> { private lateinit var binding: ActivitySampleBinding //save our FastAdapter private lateinit var fastItemAdapter: GenericFastItemAdapter private lateinit var footerAdapter: GenericItemAdapter //drag & drop private lateinit var touchCallback: SimpleDragCallback private lateinit var touchHelper: ItemTouchHelper //endless scroll lateinit var endlessRecyclerOnScrollListener: EndlessRecyclerOnScrollListener override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySampleBinding.inflate(layoutInflater).also { setContentView(it.root) } // Handle Toolbar setSupportActionBar(binding.toolbar) //create our FastAdapter which will manage everything fastItemAdapter = FastItemAdapter() val selectExtension = fastItemAdapter.getSelectExtension() selectExtension.isSelectable = true //create our FooterAdapter which will manage the progress items footerAdapter = items() fastItemAdapter.addAdapter(1, footerAdapter) //configure our fastAdapter fastItemAdapter.onClickListener = { v, _, item, _ -> if (v != null && item is SimpleItem) { Toast.makeText(v.context, item.name?.getText(v.context), Toast.LENGTH_LONG).show() } false } //configure the itemAdapter fastItemAdapter.itemFilter.filterPredicate = { item: GenericItem, constraint: CharSequence? -> if (item is SimpleItem) { //return true if we should filter it out item.name?.textString.toString().contains(constraint.toString(), ignoreCase = true) } else { //return false to keep it false } } fastItemAdapter.itemFilter.itemFilterListener = this //get our recyclerView and do basic setup binding.rv.layoutManager = LinearLayoutManager(this) binding.rv.itemAnimator = DefaultItemAnimator() binding.rv.adapter = fastItemAdapter endlessRecyclerOnScrollListener = object : EndlessRecyclerOnScrollListener(footerAdapter) { override fun onLoadMore(currentPage: Int) { footerAdapter.clear() val progressItem = ProgressItem() progressItem.isEnabled = false footerAdapter.add(progressItem) //simulate networking (2 seconds) val handler = Handler() handler.postDelayed({ footerAdapter.clear() for (i in 1..15) { fastItemAdapter.add(fastItemAdapter.adapterItemCount, SimpleItem().withName("Item $i Page $currentPage")) } }, 2000) } } binding.rv.addOnScrollListener(endlessRecyclerOnScrollListener) //fill with some sample data (load the first page here) val items = ArrayList<SimpleItem>() for (i in 1..15) { items.add(SimpleItem().withName("Item $i Page 0")) } fastItemAdapter.add(items) //add drag and drop for item touchCallback = SimpleDragCallback(this) touchHelper = ItemTouchHelper(touchCallback) // Create ItemTouchHelper and pass with parameter the SimpleDragCallback touchHelper.attachToRecyclerView(binding.rv) // Attach ItemTouchHelper to RecyclerView //restore selections (this has to be done after the items were added fastItemAdapter.withSavedInstanceState(savedInstanceState) //set the back arrow in the toolbar supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeButtonEnabled(false) } override fun onSaveInstanceState(outState: Bundle) { var outState = outState //add the values which need to be saved from the adapter to the bundle outState = fastItemAdapter.saveInstanceState(outState) super.onSaveInstanceState(outState) } override fun onOptionsItemSelected(item: MenuItem): Boolean { //handle the click on the back arrow click return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu items for use in the action bar val inflater = menuInflater inflater.inflate(R.menu.search, menu) //search icon menu.findItem(R.id.search).icon = IconicsDrawable(this, MaterialDesignIconic.Icon.gmi_search).apply { colorInt = Color.BLACK; actionBar() } val searchView = menu.findItem(R.id.search).actionView as SearchView searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(s: String): Boolean { touchCallback.setIsDragEnabled(false) fastItemAdapter.filter(s) return true } override fun onQueryTextChange(s: String): Boolean { fastItemAdapter.filter(s) touchCallback.setIsDragEnabled(TextUtils.isEmpty(s)) return true } }) endlessRecyclerOnScrollListener.enable() return super.onCreateOptionsMenu(menu) } override fun itemTouchOnMove(oldPosition: Int, newPosition: Int): Boolean { DragDropUtil.onMove(fastItemAdapter.itemAdapter, oldPosition, newPosition) // change position return true } override fun itemTouchDropped(oldPosition: Int, newPosition: Int) { // save the new item order, i.e. in your database // remove visual highlight to dropped item } override fun itemsFiltered(constraint: CharSequence?, results: List<GenericItem>?) { endlessRecyclerOnScrollListener.disable() Toast.makeText(this@EndlessScrollListActivity, "filtered items count: " + fastItemAdapter.itemCount, Toast.LENGTH_SHORT).show() } override fun onReset() { endlessRecyclerOnScrollListener.enable() } }
apache-2.0
73cdc9d10b60fb37083532f814017acc
39.331633
147
0.69513
5.262983
false
false
false
false
cdietze/klay
tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/ui/HistoryGroupDemo.kt
1
2209
package tripleklay.demo.core.ui import react.UnitSlot import tripleklay.demo.core.DemoScreen import tripleklay.ui.* import tripleklay.ui.layout.AxisLayout import tripleklay.ui.layout.BorderLayout import tripleklay.util.Colors class HistoryGroupDemo : DemoScreen() { override fun name(): String { return "History Group" } override fun title(): String { return "UI: History Group" } override fun createIface(root: Root): Group { val prefix = Field("Love Potion Number ") val add10 = Button("+10") val add100 = Button("+100") val history = HistoryGroup.Labels() val historyBox = SizableGroup(BorderLayout()) historyBox.add(history.setConstraint(BorderLayout.CENTER)) val width = Slider(150f, 25f, 1024f) val top = Group(AxisLayout.horizontal()).add( prefix.setConstraint(AxisLayout.stretched()), add10, add100, width) width.value.connectNotify({ value: Float? -> historyBox.preferredSize.updateWidth(value!!) }) add10.clicked().connect(addSome(history, prefix, 10)) add100.clicked().connect(addSome(history, prefix, 100)) history.setStylesheet(Stylesheet.builder().add(Label::class, Style.BACKGROUND.`is`(Background.composite( Background.blank().inset(0f, 2f), Background.bordered(Colors.WHITE, Colors.BLACK, 1f).inset(10f))), Style.TEXT_WRAP.on, Style.HALIGN.left).create()) history.addStyles(Style.BACKGROUND.`is`(Background.beveled( Colors.CYAN, Colors.brighter(Colors.CYAN), Colors.darker(Colors.CYAN)).inset(5f))) _lastNum = 0 return Group(AxisLayout.vertical()).add( top, historyBox.setConstraint(AxisLayout.stretched())).addStyles( Style.BACKGROUND.`is`(Background.blank().inset(5f))) } protected fun addSome(group: HistoryGroup.Labels, prefix: Field, num: Int): UnitSlot { return { for (ii in 0..num - 1) { group.addItem(prefix.text.get() + (++_lastNum).toString()) } } } protected var _lastNum: Int = 0 }
apache-2.0
dea1584efc20589cbf9e67e0e00940c8
38.446429
98
0.62517
4.105948
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/training/environment/CurrentWeather.kt
1
2465
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets 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. * * MyTargets 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. */ package de.dreier.mytargets.features.training.environment import com.google.gson.annotations.SerializedName import de.dreier.mytargets.features.settings.SettingsManager import de.dreier.mytargets.shared.models.EWeather import de.dreier.mytargets.shared.models.Environment import java.util.* import kotlin.math.pow import kotlin.math.roundToInt class CurrentWeather { @SerializedName("cod") var httpCode: Int? = null @SerializedName("name") var cityName: String = "" @SerializedName("weather") var weather: List<Weather> = ArrayList() @SerializedName("wind") var wind: Wind? = null private fun mpsToKmh(mps: Double): Double { return mps / 0.277777778 } private fun kmhToBeaufort(kmh: Double): Int { return (kmh / 3.01).pow(0.666666666).roundToInt() } fun toEnvironment(): Environment { val code = Integer.parseInt(weather[0].icon?.substring(0, 2) ?: "1") val e = Environment() e.indoor = SettingsManager.indoor e.weather = imageCodeToWeather(code) e.windDirection = 0 e.location = cityName e.windDirection = 0 e.windSpeed = kmhToBeaufort(mpsToKmh(wind?.speed ?: 0.0)) return e } private fun imageCodeToWeather(code: Int): EWeather { return when (code) { 1 -> EWeather.SUNNY 2 -> EWeather.PARTLY_CLOUDY 3, 4 -> EWeather.CLOUDY 9 -> EWeather.RAIN 10 -> EWeather.LIGHT_RAIN else -> EWeather.CLOUDY } } inner class Wind { @SerializedName("speed") var speed: Double? = null } inner class Weather { @SerializedName("id") var id: Int? = null @SerializedName("main") var main: String? = null @SerializedName("description") var description: String? = null @SerializedName("icon") var icon: String? = null } }
gpl-2.0
351f07e5387f31da7dea9b3afaba0c92
27.011364
76
0.645436
4.067657
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/user/User.kt
1
2367
package backend.model.user import backend.model.Blockable import backend.model.Blocker import backend.model.media.Media import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import kotlin.reflect.KClass interface User : Blockable, Blocker { var email: String var passwordHash: String var isBlocked: Boolean var preferredLanguage: Language val account: UserAccount var firstname: String? var lastname: String? var gender: String? var profilePic: Media? var notificationToken: String? var newsletter: Boolean var newEmailToValidate: String? fun <T : UserRole> addRole(clazz: KClass<T>): T fun <T : UserRole> getRole(clazz: KClass<T>): T? fun <T : UserRole> hasRole(clazz: KClass<T>): Boolean fun <T : UserRole> removeRole(clazz: KClass<T>): T? fun <T : UserRole> hasAuthority(clazz: KClass<T>): Boolean companion object { fun create(email: String, password: String, newsletter: Boolean = false): User { val user = UserAccount() user.email = email user.setPassword(password) user.newsletter = newsletter return user } } fun activate(token: String) fun isActivationTokenCorrect(token: String): Boolean fun createActivationToken(): String fun isActivated(): Boolean fun confirmEmailChange(token: String) fun isChangeEmailTokenCorrect(token: String): Boolean fun createChangeEmailToken(): String fun setPasswordViaReset(password: String, token: String) override fun isBlockedBy(userId: Long?): Boolean { return userId.let { account.blockedBy.map { it.id } .contains(it) } } override fun isBlocking(user: User?): Boolean { return user?.isBlockedBy(account.id) ?: false } fun emailDomain(): String /** * Checks if the passed [password] matches the current password hash of this user */ fun isCurrentPassword(password: String?): Boolean { return BCryptPasswordEncoder().matches(password, this.passwordHash) } /** * Sets the password of the user to the hash of the passed [password] */ fun setPassword(password: String?) { this.passwordHash = BCryptPasswordEncoder().encode(password) } } enum class Language { DE, EN }
agpl-3.0
993017e512a736d0db92b742a065031b
27.518072
88
0.666244
4.440901
false
false
false
false
vkurdin/idea-php-lambda-folding
src/ru/vkurdin/idea/php/lambdafolding/TreeUtils.kt
1
772
package ru.vkurdin.idea.php.lambdafolding import com.intellij.psi.PsiElement fun PsiElement.prevSiblings() = elementSeq { it.prevSibling } fun PsiElement.nextSiblings() = elementSeq { it.nextSibling } fun PsiElement.parents() = elementSeq { it.parent } inline private fun <T> T.elementSeq(crossinline elementProvider: (T) -> T?) = object : Sequence<T> { override fun iterator() = object : Iterator<T> { private var next: T? = elementProvider(this@elementSeq) override fun hasNext() = next != null override fun next() : T = next!!.let { val current = it next = elementProvider(current) current } } }
mit
a5a65f70a421acd5669125dbc6175a41
27.592593
77
0.573834
4.337079
false
false
false
false
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/activity/pixels/FlipActivity.kt
1
1953
package com.cv4j.app.activity.pixels import android.content.res.Resources import android.graphics.BitmapFactory import android.os.Bundle import com.cv4j.app.R import com.cv4j.app.app.BaseActivity import com.cv4j.core.datamodel.CV4JImage import com.cv4j.core.pixels.Flip import kotlinx.android.synthetic.main.activity_flip.* /** * * @FileName: * com.cv4j.app.activity.pixels.FlipActivity * @author: Tony Shen * @date: 2020-05-04 13:22 * @version: V1.0 <描述当前版本功能> */ class FlipActivity : BaseActivity() { var title: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_flip) intent.extras?.let { title = it.getString("Title","") }?:{ title = "" }() toolbar.setOnClickListener { finish() } initData() } private fun initData() { toolbar.title = "< $title" val res: Resources = getResources() val bitmap = BitmapFactory.decodeResource(res, R.drawable.pixel_test_1) image.setImageBitmap(bitmap) var cv4jImage = CV4JImage(bitmap) val imageProcessor = cv4jImage.processor Flip.flip(imageProcessor, Flip.FLIP_HORIZONTAL) if (imageProcessor != null) { val resultCV4JImage = CV4JImage(imageProcessor.width, imageProcessor.height, imageProcessor.pixels) result_image1.setImageBitmap(resultCV4JImage.processor.image.toBitmap()) } cv4jImage = CV4JImage(bitmap) val imageProcessor2 = cv4jImage.processor Flip.flip(imageProcessor2, Flip.FLIP_VERTICAL) if (imageProcessor2 != null) { val resultCV4JImage = CV4JImage(imageProcessor2.width, imageProcessor2.height, imageProcessor2.pixels) result_image2.setImageBitmap(resultCV4JImage.processor.image.toBitmap()) } } }
apache-2.0
b72d187f12e14774cf0bf8ce10c068d7
29.761905
114
0.66443
3.874
false
false
false
false
google/intellij-community
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/ExternalModuleImlFileEntitiesSerializer.kt
5
8920
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.impl.ModulePath import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.ExternalSystemModuleOptionsEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleCustomImlDataEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.getOrCreateExternalSystemModuleOptions import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.util.JpsPathUtil import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity private val MODULE_OPTIONS_TO_CHECK = setOf( "externalSystemModuleVersion", "linkedProjectPath", "linkedProjectId", "rootProjectPath", "externalSystemModuleGroup", "externalSystemModuleType" ) internal class ExternalModuleImlFileEntitiesSerializer(modulePath: ModulePath, fileUrl: VirtualFileUrl, virtualFileManager: VirtualFileUrlManager, internalEntitySource: JpsFileEntitySource, internalModuleListSerializer: JpsModuleListSerializer) : ModuleImlFileEntitiesSerializer(modulePath, fileUrl, internalEntitySource, virtualFileManager, internalModuleListSerializer) { override val skipLoadingIfFileDoesNotExist: Boolean get() = true override fun loadEntities(builder: MutableEntityStorage, reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { } override fun acceptsSource(entitySource: EntitySource): Boolean { return entitySource is JpsImportedEntitySource && entitySource.storedExternally } override fun readExternalSystemOptions(reader: JpsFileContentReader, moduleOptions: Map<String?, String?>): Pair<Map<String?, String?>, String?> { val componentTag = reader.loadComponent(fileUrl.url, "ExternalSystem", getBaseDirPath()) ?: return Pair(emptyMap(), null) val options = componentTag.attributes.associateBy({ it.name }, { it.value }) return Pair(options, options["externalSystem"]) } override fun loadExternalSystemOptions(builder: MutableEntityStorage, module: ModuleEntity, reader: JpsFileContentReader, externalSystemOptions: Map<String?, String?>, externalSystemId: String?, entitySource: EntitySource) { if (!shouldCreateExternalSystemModuleOptions(externalSystemId, externalSystemOptions, MODULE_OPTIONS_TO_CHECK)) return val optionsEntity = builder.getOrCreateExternalSystemModuleOptions(module, entitySource) builder.modifyEntity(optionsEntity) { externalSystem = externalSystemId externalSystemModuleVersion = externalSystemOptions["externalSystemModuleVersion"] linkedProjectPath = externalSystemOptions["linkedProjectPath"] linkedProjectId = externalSystemOptions["linkedProjectId"] rootProjectPath = externalSystemOptions["rootProjectPath"] externalSystemModuleGroup = externalSystemOptions["externalSystemModuleGroup"] externalSystemModuleType = externalSystemOptions["externalSystemModuleType"] } } override fun saveModuleOptions(externalSystemOptions: ExternalSystemModuleOptionsEntity?, moduleType: String?, customImlData: ModuleCustomImlDataEntity?, writer: JpsFileContentWriter) { val fileUrlString = fileUrl.url if (FileUtil.extensionEquals(fileUrlString, "iml")) { logger<ExternalModuleImlFileEntitiesSerializer>().error("External serializer should not write to iml files. Path:$fileUrlString") } if (externalSystemOptions != null) { val componentTag = JDomSerializationUtil.createComponentElement("ExternalSystem") fun saveOption(name: String, value: String?) { if (value != null) { componentTag.setAttribute(name, value) } } saveOption("externalSystem", externalSystemOptions.externalSystem) saveOption("externalSystemModuleGroup", externalSystemOptions.externalSystemModuleGroup) saveOption("externalSystemModuleType", externalSystemOptions.externalSystemModuleType) saveOption("externalSystemModuleVersion", externalSystemOptions.externalSystemModuleVersion) saveOption("linkedProjectId", externalSystemOptions.linkedProjectId) saveOption("linkedProjectPath", externalSystemOptions.linkedProjectPath) saveOption("rootProjectPath", externalSystemOptions.rootProjectPath) writer.saveComponent(fileUrlString, "ExternalSystem", componentTag) } if (moduleType != null || !customImlData?.customModuleOptions.isNullOrEmpty()) { val componentTag = JDomSerializationUtil.createComponentElement(DEPRECATED_MODULE_MANAGER_COMPONENT_NAME) if (moduleType != null) { componentTag.addContent(Element("option").setAttribute("key", "type").setAttribute("value", moduleType)) } customImlData?.customModuleOptions?.forEach{ (key, value) -> componentTag.addContent(Element("option").setAttribute("key", key).setAttribute("value", value)) } writer.saveComponent(fileUrlString, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, componentTag) } } override fun createExternalEntitySource(externalSystemId: String) = JpsImportedEntitySource(internalEntitySource, externalSystemId, true) override fun createFacetSerializer(): FacetEntitiesSerializer { return FacetEntitiesSerializer(fileUrl, internalEntitySource, "ExternalFacetManager", getBaseDirPath(), true) } override fun getBaseDirPath(): String { return modulePath.path } override fun toString(): String = "ExternalModuleImlFileEntitiesSerializer($fileUrl)" } internal class ExternalModuleListSerializer(private val externalStorageRoot: VirtualFileUrl, private val virtualFileManager: VirtualFileUrlManager) : ModuleListSerializerImpl(externalStorageRoot.append("project/modules.xml").url, virtualFileManager) { override val isExternalStorage: Boolean get() = true override val componentName: String get() = "ExternalProjectModuleManager" override val entitySourceFilter: (EntitySource) -> Boolean get() = { it is JpsImportedEntitySource && it.storedExternally } override fun getSourceToSave(module: ModuleEntity): JpsFileEntitySource.FileInDirectory? { return (module.entitySource as? JpsImportedEntitySource)?.internalFile as? JpsFileEntitySource.FileInDirectory } override fun getFileName(entity: ModuleEntity): String { return "${entity.name}.xml" } override fun createSerializer(internalSource: JpsFileEntitySource, fileUrl: VirtualFileUrl, moduleGroup: String?): JpsFileEntitiesSerializer<ModuleEntity> { val fileName = PathUtil.getFileName(fileUrl.url) val actualFileUrl = if (PathUtil.getFileExtension(fileName) == "iml") { externalStorageRoot.append("modules/${fileName.substringBeforeLast('.')}.xml") } else { fileUrl } val filePath = JpsPathUtil.urlToPath(fileUrl.url) return ExternalModuleImlFileEntitiesSerializer(ModulePath(filePath, moduleGroup), actualFileUrl, virtualFileManager, internalSource, this) } // Component DeprecatedModuleOptionManager removed by ModuleStateStorageManager.beforeElementSaved from .iml files override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { super.deleteObsoleteFile(fileUrl, writer) if (FileUtil.extensionEquals(fileUrl, "xml")) { writer.saveComponent(fileUrl, "ExternalSystem", null) writer.saveComponent(fileUrl, "ExternalFacetManager", null) writer.saveComponent(fileUrl, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null) } } override fun toString(): String = "ExternalModuleListSerializer($fileUrl)" }
apache-2.0
56e4b3a3a38af96b0f2c0cc25a2737e4
52.413174
158
0.73565
6.242127
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/AddElseBranchFix.kt
1
4638
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.CodeInsightUtilCore import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.util.elementType import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinPsiOnlyQuickFixAction import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.PsiElementSuitabilityCheckers import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory import org.jetbrains.kotlin.idea.util.executeEnterHandler import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class AddElseBranchFix<T : KtExpression>(element: T) : KotlinPsiOnlyQuickFixAction<T>(element) { override fun getFamilyName() = KotlinBundle.message("fix.add.else.branch.when") override fun getText() = familyName abstract override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean abstract override fun invoke(project: Project, editor: Editor?, file: KtFile) } class AddWhenElseBranchFix(element: KtWhenExpression) : AddElseBranchFix<KtWhenExpression>(element) { override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element?.closeBrace != null override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val whenCloseBrace = element.closeBrace ?: return val entry = KtPsiFactory(project).createWhenEntry("else -> {}") CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(element.addBefore(entry, whenCloseBrace))?.endOffset?.let { offset -> editor?.caretModel?.moveToOffset(offset - 1) } } companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) { override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> { return listOfNotNull(psiElement.getNonStrictParentOfType<KtWhenExpression>()?.let(::AddWhenElseBranchFix)) } } } class AddIfElseBranchFix(element: KtIfExpression) : AddElseBranchFix<KtIfExpression>(element) { override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val ktIfExpression = element ?: return false return ktIfExpression.`else` == null && ktIfExpression.condition != null && ktIfExpression.children.firstOrNull { it.elementType == KtNodeTypes.THEN }?.firstChild !is PsiErrorElement } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val withBraces = element.then is KtBlockExpression val psiFactory = KtPsiFactory(project) val newIf = psiFactory.createExpression( if (withBraces) { "if (true) {} else {}" } else { "if (true) 2 else TODO()" } ) as KtIfExpression element.addRange(newIf.then?.parent?.nextSibling, newIf.`else`?.parent) editor?.caretModel?.currentCaret?.let { caret -> if (withBraces) { caret.moveToOffset(element.endOffset - 1) val documentManager = PsiDocumentManager.getInstance(project) documentManager.getDocument(element.containingFile)?.let { doc -> documentManager.doPostponedOperationsAndUnblockDocument(doc) editor.executeEnterHandler() } } else { element.`else`?.textRange?.let { caret.moveToOffset(it.startOffset) caret.setSelection(it.startOffset, it.endOffset) } } } } companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) { override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> { return listOfNotNull(psiElement.parent?.safeAs<KtIfExpression>()?.let(::AddIfElseBranchFix)) } } }
apache-2.0
da67ef781a3a790b6c50ec1f1da9e030
47.821053
134
0.712592
5.003236
false
false
false
false
rhwolniewicz/playerscore
step4/playerscore/src/test/kotlin/com/wolniewicz/playerscore/PlayerScoreTestWithFongo.kt
2
1222
package com.wolniewicz.playerscore import com.github.fakemongo.junit.FongoRule import com.wolniewicz.playerscore.model.Player import com.wolniewicz.playerscore.repository.PlayerRepository import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @SpringBootTest abstract class PlayerScoreTestWithFongo(val initializeTestData: Boolean = true) { @get:Rule val fongoRule = FongoRule() @Autowired lateinit var playerRepository: PlayerRepository @Before fun setupTestDatabase() { if (initializeTestData) { playerRepository.save(TEST_PLAYER_1) playerRepository.save(TEST_PLAYER_2) playerRepository.save(TEST_PLAYER_3) playerRepository.save(TEST_PLAYER_4) playerRepository.save(TEST_PLAYER_5) } } companion object { val TEST_PLAYER_1 = Player("alice", 20) val TEST_PLAYER_2 = Player("bob", 15) val TEST_PLAYER_3 = Player("charlie", 25) val TEST_PLAYER_4 = Player("dawn", 30) val TEST_PLAYER_5 = Player("ed", 10) } }
mit
dd7a4befb6bcc1fbc14c8c17d780b6bf
29.55
81
0.757774
3.748466
false
true
false
false
aporter/coursera-android
ExamplesKotlin/FragmentStaticLayout/app/src/main/java/course/examples/fragments/staticlayout/QuotesFragment.kt
1
3223
package course.examples.fragments.staticlayout import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import android.widget.TextView //Several Activity and Fragment lifecycle methods are instrumented to emit LogCat output //so you can follow the class' lifecycle class QuotesFragment : Fragment() { companion object { private const val TAG = "QuotesFragment" } private lateinit var mQuoteView: TextView var mCurrIdx = ListView.INVALID_POSITION private var mQuoteArrayLen: Int = 0 // Show the Quote string at position newIndex fun showQuoteAtIndex(index: Int) { if (index in 0 until mQuoteArrayLen) { mQuoteView.text = QuoteViewerActivity.mQuoteArray[index] mCurrIdx = index } else { mQuoteView.text = QuoteViewerActivity.mNoQuoteSelectedString } } override fun onAttach(context: Context) { Log.i(TAG, "${javaClass.simpleName}: entered onAttach()") super.onAttach(context) } override fun onCreate(savedInstanceState: Bundle?) { Log.i(TAG, "${javaClass.simpleName}: entered onCreate()") super.onCreate(savedInstanceState) } // Called to create the content view for this Fragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.i(TAG, "${javaClass.simpleName}: entered onCreateView()") // Inflate the layout defined in quote_fragment.xml // The last parameter is false because the returned view does not need to be attached to the container ViewGroup return inflater.inflate(R.layout.quote_fragment, container, false) } // Set up some information about the mQuoteView TextView override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Log.i(TAG, "${javaClass.simpleName}: entered onActivityCreated()") mQuoteView = activity!!.findViewById(R.id.quoteView) mQuoteArrayLen = QuoteViewerActivity.mQuoteArray.size showQuoteAtIndex(mCurrIdx) } override fun onStart() { Log.i(TAG, "${javaClass.simpleName}: entered onStart()") super.onStart() } override fun onResume() { Log.i(TAG, "${javaClass.simpleName}: entered onResume()") super.onResume() } override fun onPause() { Log.i(TAG, "${javaClass.simpleName}: entered onPause()") super.onPause() } override fun onStop() { Log.i(TAG, "${javaClass.simpleName}: entered onStop()") super.onStop() } override fun onDetach() { Log.i(TAG, "${javaClass.simpleName}: entered onDetach()") super.onDetach() } override fun onDestroy() { Log.i(TAG, "${javaClass.simpleName}: entered onDestroy()") super.onDestroy() } override fun onDestroyView() { Log.i(TAG, "${javaClass.simpleName}: entered onDestroyView()") super.onDestroyView() } }
mit
bc889b6260d729544151055fadf0b93d
29.40566
120
0.670183
4.664255
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/data/model/BluetoothConnectorImpl.kt
1
12459
package com.glodanif.bluetoothchat.data.model import android.bluetooth.BluetoothDevice import android.content.ComponentName import android.content.Context import android.content.ServiceConnection import android.os.IBinder import com.glodanif.bluetoothchat.BuildConfig import com.glodanif.bluetoothchat.data.entity.ChatMessage import com.glodanif.bluetoothchat.data.entity.Conversation import com.glodanif.bluetoothchat.data.internal.AutoresponderProxy import com.glodanif.bluetoothchat.data.internal.CommunicationProxy import com.glodanif.bluetoothchat.data.internal.EmptyProxy import com.glodanif.bluetoothchat.data.service.BluetoothConnectionService import com.glodanif.bluetoothchat.data.service.message.Contract import com.glodanif.bluetoothchat.data.service.message.PayloadType import com.glodanif.bluetoothchat.utils.safeRemove import java.io.File class BluetoothConnectorImpl(private val context: Context) : BluetoothConnector { private val monitor = Any() private var prepareListeners = LinkedHashSet<OnPrepareListener>() private var connectListeners = LinkedHashSet<OnConnectionListener>() private var messageListeners = LinkedHashSet<OnMessageListener>() private var fileListeners = LinkedHashSet<OnFileListener>() private var proxy: CommunicationProxy? = null private var service: BluetoothConnectionService? = null private var bound = false private var isPreparing = false private val connection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, binder: IBinder) { service = (binder as BluetoothConnectionService.ConnectionBinder).getService().apply { setConnectionListener(connectionListenerInner) setMessageListener(messageListenerInner) setFileListener(fileListenerInner) } proxy = if (BuildConfig.AUTORESPONDER) AutoresponderProxy(service) else EmptyProxy() bound = true isPreparing = false synchronized(monitor) { prepareListeners.forEach { it.onPrepared() } } } override fun onServiceDisconnected(className: ComponentName) { service?.setConnectionListener(null) service?.setMessageListener(null) service?.setFileListener(null) service = null proxy = null isPreparing = false bound = false synchronized(monitor) { prepareListeners.forEach { it.onError() } } } } private val connectionListenerInner = object : OnConnectionListener { override fun onConnected(device: BluetoothDevice) { proxy?.onConnected(device) synchronized(monitor) { connectListeners.forEach { it.onConnected(device) } } } override fun onConnectionWithdrawn() { proxy?.onConnectionWithdrawn() synchronized(monitor) { connectListeners.forEach { it.onConnectionWithdrawn() } } } override fun onConnectionAccepted() { proxy?.onConnectionAccepted() synchronized(monitor) { connectListeners.forEach { it.onConnectionAccepted() } } } override fun onConnectionRejected() { proxy?.onConnectionRejected() synchronized(monitor) { connectListeners.forEach { it.onConnectionRejected() } } } override fun onConnecting() { proxy?.onConnecting() synchronized(monitor) { connectListeners.forEach { it.onConnecting() } } } override fun onConnectedIn(conversation: Conversation) { proxy?.onConnectedIn(conversation) synchronized(monitor) { connectListeners.forEach { it.onConnectedIn(conversation) } } } override fun onConnectedOut(conversation: Conversation) { proxy?.onConnectedOut(conversation) synchronized(monitor) { connectListeners.forEach { it.onConnectedOut(conversation) } } } override fun onConnectionLost() { proxy?.onConnectionLost() synchronized(monitor) { connectListeners.forEach { it.onConnectionLost() } } } override fun onConnectionFailed() { proxy?.onConnectionFailed() synchronized(monitor) { connectListeners.forEach { it.onConnectionFailed() } } } override fun onDisconnected() { proxy?.onDisconnected() synchronized(monitor) { connectListeners.forEach { it.onDisconnected() } } } override fun onConnectionDestroyed() { proxy?.onConnectionDestroyed() synchronized(monitor) { connectListeners.forEach { it.onConnectionDestroyed() } } release() } } private val messageListenerInner = object : OnMessageListener { override fun onMessageReceived(message: ChatMessage) { proxy?.onMessageReceived(message) synchronized(monitor) { messageListeners.forEach { it.onMessageReceived(message) } } } override fun onMessageSent(message: ChatMessage) { proxy?.onMessageSent(message) synchronized(monitor) { messageListeners.forEach { it.onMessageSent(message) } } } override fun onMessageSendingFailed() { proxy?.onMessageSendingFailed() synchronized(monitor) { messageListeners.forEach { it.onMessageSendingFailed() } } } override fun onMessageDelivered(id: Long) { proxy?.onMessageDelivered(id) synchronized(monitor) { messageListeners.forEach { it.onMessageDelivered(id) } } } override fun onMessageNotDelivered(id: Long) { proxy?.onMessageNotDelivered(id) synchronized(monitor) { messageListeners.forEach { it.onMessageNotDelivered(id) } } } override fun onMessageSeen(id: Long) { proxy?.onMessageSeen(id) synchronized(monitor) { messageListeners.forEach { it.onMessageSeen(id) } } } } private val fileListenerInner = object : OnFileListener { override fun onFileSendingStarted(fileAddress: String?, fileSize: Long) { proxy?.onFileSendingStarted(fileAddress, fileSize) synchronized(monitor) { fileListeners.forEach { it.onFileSendingStarted(fileAddress, fileSize) } } } override fun onFileSendingProgress(sentBytes: Long, totalBytes: Long) { proxy?.onFileSendingProgress(sentBytes, totalBytes) synchronized(monitor) { fileListeners.forEach { it.onFileSendingProgress(sentBytes, totalBytes) } } } override fun onFileSendingFinished() { proxy?.onFileSendingFinished() synchronized(monitor) { fileListeners.forEach { it.onFileSendingFinished() } } } override fun onFileSendingFailed() { proxy?.onFileSendingFailed() synchronized(monitor) { fileListeners.forEach { it.onFileSendingFailed() } } } override fun onFileReceivingStarted(fileSize: Long) { proxy?.onFileReceivingStarted(fileSize) synchronized(monitor) { fileListeners.forEach { it.onFileReceivingStarted(fileSize) } } } override fun onFileReceivingProgress(sentBytes: Long, totalBytes: Long) { proxy?.onFileReceivingProgress(sentBytes, totalBytes) synchronized(monitor) { fileListeners.forEach { it.onFileReceivingProgress(sentBytes, totalBytes) } } } override fun onFileReceivingFinished() { proxy?.onFileReceivingFinished() synchronized(monitor) { fileListeners.forEach { it.onFileReceivingFinished() } } } override fun onFileReceivingFailed() { proxy?.onFileReceivingFailed() synchronized(monitor) { fileListeners.forEach { it.onFileReceivingFailed() } } } override fun onFileTransferCanceled(byPartner: Boolean) { proxy?.onFileTransferCanceled(byPartner) synchronized(monitor) { fileListeners.forEach { it.onFileTransferCanceled(byPartner) } } } } override fun prepare() { if (isPreparing) return isPreparing = true bound = false if (!BluetoothConnectionService.isRunning) { BluetoothConnectionService.start(context) } BluetoothConnectionService.bind(context, connection) } override fun release() { if (bound) { context.unbindService(connection) } bound = false service = null proxy = null synchronized(monitor) { connectListeners = LinkedHashSet() prepareListeners = LinkedHashSet() messageListeners = LinkedHashSet() fileListeners = LinkedHashSet() } } override fun isConnectionPrepared() = bound override fun addOnPrepareListener(listener: OnPrepareListener) { synchronized(monitor) { prepareListeners.add(listener) } } override fun addOnConnectListener(listener: OnConnectionListener) { synchronized(monitor) { connectListeners.add(listener) } } override fun addOnMessageListener(listener: OnMessageListener) { synchronized(monitor) { messageListeners.add(listener) } } override fun addOnFileListener(listener: OnFileListener) { synchronized(monitor) { fileListeners.add(listener) } } override fun removeOnPrepareListener(listener: OnPrepareListener) { synchronized(monitor) { prepareListeners.safeRemove(listener) } } override fun removeOnConnectListener(listener: OnConnectionListener) { synchronized(monitor) { connectListeners.safeRemove(listener) } } override fun removeOnMessageListener(listener: OnMessageListener) { synchronized(monitor) { messageListeners.safeRemove(listener) } } override fun removeOnFileListener(listener: OnFileListener) { synchronized(monitor) { fileListeners.safeRemove(listener) } } override fun connect(device: BluetoothDevice) { service?.connect(device) } override fun stop() { service?.stop() } override fun sendMessage(messageText: String) { service?.getCurrentContract()?.createChatMessage(messageText)?.let { message -> service?.sendMessage(message) } } override fun sendFile(file: File, type: PayloadType) { service?.sendFile(file, type) } override fun getTransferringFile() = service?.getTransferringFile() override fun cancelFileTransfer() { service?.cancelFileTransfer() } override fun disconnect() { service?.disconnect() } override fun isConnected() = service?.isConnected() ?: false override fun isConnectedOrPending() = service?.isConnectedOrPending() ?: false override fun isPending() = service?.isPending() ?: false override fun getCurrentConversation() = service?.getCurrentConversation() override fun acceptConnection() { service?.approveConnection() } override fun rejectConnection() { service?.rejectConnection() } override fun sendDisconnectRequest() { service?.getCurrentContract()?.createDisconnectMessage()?.let { message -> service?.sendMessage(message) } } override fun isFeatureAvailable(feature: Contract.Feature) = service?.getCurrentContract()?.isFeatureAvailable(feature) ?: true }
apache-2.0
87630bffae925e9d167db8e1e04c99f1
30.462121
98
0.619793
5.537333
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewProcessModelImpl.kt
2
1312
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.ui import com.intellij.util.EventDispatcher import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestPendingReview import org.jetbrains.plugins.github.pullrequest.ui.SimpleEventListener class GHPRReviewProcessModelImpl : GHPRReviewProcessModel { private val changeEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java) override var pendingReview: GHPullRequestPendingReview? = null private set override var isActual: Boolean = false private set override fun populatePendingReviewData(review: GHPullRequestPendingReview?) { pendingReview = review isActual = true changeEventDispatcher.multicaster.eventOccurred() } override fun clearPendingReviewData() { pendingReview = null isActual = false changeEventDispatcher.multicaster.eventOccurred() } override fun addAndInvokeChangesListener(listener: SimpleEventListener) { changeEventDispatcher.addListener(listener) listener.eventOccurred() } override fun removeChangesListener(listener: SimpleEventListener) { changeEventDispatcher.removeListener(listener) } }
apache-2.0
b06f6e96a9587ec306df9e76e8f0edad
34.459459
140
0.801829
5.248
false
false
false
false
allotria/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/impl/SdkLookupTest.kt
2
23438
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.daemon.impl import com.intellij.openapi.Disposable import com.intellij.openapi.application.WriteAction import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.util.ProgressIndicatorBase import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.projectRoots.SimpleJavaSdkType import com.intellij.openapi.projectRoots.impl.UnknownSdkFixAction import com.intellij.openapi.roots.ui.configuration.* import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTask import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTracker import com.intellij.openapi.util.Disposer import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.setSystemPropertyForTest import com.intellij.util.WaitFor import com.intellij.util.io.systemIndependentPath import com.intellij.util.ui.UIUtil import org.junit.Assert import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicReference import kotlin.concurrent.thread class SdkLookupTest : LightPlatformTestCase() { override fun setUp() { super.setUp() setSystemPropertyForTest("intellij.progress.task.ignoreHeadless", "true") } val log = Collections.synchronizedList(mutableListOf<String>()) val sdkType get() = SimpleJavaSdkType.getInstance()!! interface SdkLookupBuilderEx : SdkLookupBuilder { fun onDownloadingSdkDetectedEx(d: SdkLookupDownloadDecision): SdkLookupBuilderEx fun onSdkFixResolved(d: SdkLookupDecision): SdkLookupBuilderEx fun lookupBlocking() } private val lookup: SdkLookupBuilderEx get() { var ourFixDecision = SdkLookupDecision.CONTINUE var ourSdkDownloadDecision = SdkLookupDownloadDecision.WAIT var onSdkResolvedHook : (Sdk?) -> Unit = {} val base = SdkLookup.newLookupBuilder() .withProject(project) .withProgressIndicator(ProgressIndicatorBase()) .withSdkType(sdkType) .onSdkNameResolved { log += "sdk-name: ${it?.name}" } .onSdkResolved { onSdkResolvedHook(it); log += "sdk: ${it?.name}" } .onDownloadingSdkDetected { log += "sdk-downloading: ${it.name}"; ourSdkDownloadDecision } .onSdkFixResolved { log += "fix: ${it.javaClass.simpleName}"; ourFixDecision } return object : SdkLookupBuilder by base, SdkLookupBuilderEx { override fun lookupBlocking() = base.lookupBlocking() override fun onDownloadingSdkDetectedEx(d: SdkLookupDownloadDecision) = apply { ourSdkDownloadDecision = d } override fun onSdkFixResolved(d: SdkLookupDecision) = apply { ourFixDecision = d } override fun onDownloadingSdkDetected(handler: (Sdk) -> SdkLookupDownloadDecision): SdkLookupBuilder = error("Must not call in test") override fun onSdkFixResolved(handler: (UnknownSdkFixAction) -> SdkLookupDecision): SdkLookupBuilder = error("Must not call in test") override fun onSdkNameResolved(handler: (Sdk?) -> Unit): SdkLookupBuilder = error("Must not call in test") override fun onSdkResolved(handler: (Sdk?) -> Unit): SdkLookupBuilder = apply { onSdkResolvedHook = handler } } } fun SdkLookupBuilder.lookupBlocking(): Unit = service<SdkLookup>().lookupBlocking(this as SdkLookupParameters) private fun assertLog(vararg messages: String) { fun List<String>.format() = joinToString("") { "\n $it" } Assert.assertEquals("actual log: " + log.format(), messages.toList().format(), log.format()) } private fun assertLogContains(vararg messages: String) { fun List<String>.format() = joinToString("") { "\n $it" } Assert.assertEquals("actual log: " + log.format(), messages.toList().format(), log.format()) } fun `test no sdk found`() { runInThreadAndPumpMessages { lookup.lookupBlocking() } assertLog( "sdk-name: null", "sdk: null", ) } fun `test find existing by name`() { val sdk = newSdk("temp-1") runInThreadAndPumpMessages { lookup.withSdkName(sdk.name).lookupBlocking() } assertLog( "sdk-name: temp-1", "sdk: temp-1", ) } fun `test find sdk from alternatives`() { val sdk1 = newUnregisteredSdk("temp-3") val sdk2 = newUnregisteredSdk("temp-2") runInThreadAndPumpMessages { lookup .testSuggestedSdksFirst(sequenceOf(null, sdk1, sdk2)) .lookupBlocking() } assertLog( "sdk-name: temp-3", "sdk: temp-3", ) } fun `test find sdk from alternatives and filter`() { val sdk1 = newUnregisteredSdk("temp-3", "1.2.3") val sdk2 = newUnregisteredSdk("temp-2", "2.3.4") runInThreadAndPumpMessages { lookup .testSuggestedSdksFirst(sequenceOf(null, sdk1, sdk2)) .withVersionFilter { it == "2.3.4" } .lookupBlocking() } assertLog( "sdk-name: temp-2", "sdk: temp-2", ) } fun `test find downloading sdk`() { val taskLatch = CountDownLatch(1) val downloadStarted = CountDownLatch(1) Disposer.register(testRootDisposable, Disposable { taskLatch.countDown() }) val eternalTask = object: SdkDownloadTask { val home = createTempDir("planned-home").toPath().systemIndependentPath override fun getPlannedHomeDir() = home override fun getSuggestedSdkName() = "suggested name" override fun getPlannedVersion() = "planned version" override fun doDownload(indicator: ProgressIndicator) { downloadStarted.countDown() taskLatch.await() log += "download-completed" } } val sdk = newSdk("temp-5") threadEx { SdkDownloadTracker.getInstance().downloadSdk(eternalTask, listOf(sdk), ProgressIndicatorBase()) } runInThreadAndPumpMessages { downloadStarted.await() } //download should be running now threadEx { object: WaitFor(1000) { //this event should come from the lookup override fun condition() = log.any { it.startsWith("sdk-name:") } } log += "thread-ex" taskLatch.countDown() } runInThreadAndPumpMessages { //right now it hangs doing async VFS refresh in downloader thread if running from a modal progress. //ProgressManager.getInstance().run(object : Task.Modal(project, "temp", true) { // override fun run(indicator: ProgressIndicator) { lookup .withSdkName("temp-5") .lookupBlocking() //} //}) } assertLog( "sdk-name: temp-5", "sdk-downloading: temp-5", "thread-ex", "download-completed", "sdk: temp-5", ) } fun `test find downloading sdk stop`() { val taskLatch = CountDownLatch(1) val downloadStarted = CountDownLatch(1) Disposer.register(testRootDisposable, Disposable { taskLatch.countDown() }) val eternalTask = object : SdkDownloadTask { val home = createTempDir("planned-home").toPath().systemIndependentPath override fun getPlannedHomeDir() = home override fun getSuggestedSdkName() = "suggested name" override fun getPlannedVersion() = "planned version" override fun doDownload(indicator: ProgressIndicator) { downloadStarted.countDown() log += "download-started" taskLatch.await() log += "download-completed" } } val sdk = newSdk("temp-5") val download = threadEx { SdkDownloadTracker.getInstance().downloadSdk(eternalTask, listOf(sdk), ProgressIndicatorBase()) } runInThreadAndPumpMessages { downloadStarted.await() } //download should be running now val downloadThread = threadEx { object : WaitFor(1000) { //this event should come from the lookup override fun condition() = log.any { it.startsWith("sdk-downloading:") } } log += "thread-ex" taskLatch.countDown() download.join() } runInThreadAndPumpMessages { lookup .onDownloadingSdkDetectedEx(SdkLookupDownloadDecision.STOP) .onSdkResolved { downloadThread.join() } .withSdkName("temp-5") .lookupBlocking() downloadThread.join() } assertLog( "download-started", "sdk-name: temp-5", "sdk-downloading: temp-5", "thread-ex", "download-completed", "sdk: null", ) } fun `test find downloading sdk async`() { val taskLatch = CountDownLatch(1) val downloadStarted = CountDownLatch(1) Disposer.register(testRootDisposable, Disposable { taskLatch.countDown() }) val eternalTask = object: SdkDownloadTask { val home = createTempDir("planned-home").toPath().systemIndependentPath override fun getPlannedHomeDir() = home override fun getSuggestedSdkName() = "suggested name" override fun getPlannedVersion() = "planned version" override fun doDownload(indicator: ProgressIndicator) { downloadStarted.countDown() taskLatch.await() log += "download-completed" } } val sdk = newSdk("temp-5") threadEx { SdkDownloadTracker.getInstance().downloadSdk(eternalTask, listOf(sdk), ProgressIndicatorBase()) } runInThreadAndPumpMessages { downloadStarted.await() } //download should be running now threadEx { object: WaitFor(1000) { //this event should come from the lookup override fun condition() = log.any { it.startsWith("sdk-name:") } } log += "thread-ex" taskLatch.countDown() } val lookupLatch = CountDownLatch(1) lookup .withSdkName("temp-5") .onSdkResolved { lookupLatch.countDown() } .executeLookup() runInThreadAndPumpMessages { lookupLatch.await() } assertLog( "sdk-name: temp-5", "sdk-downloading: temp-5", "thread-ex", "download-completed", "sdk: temp-5", ) } fun `test local fix`() { val auto = object: UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? { if (sdk.sdkName != "xqwr") return null return object : UnknownSdkLocalSdkFix { val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"} override fun getExistingSdkHome() = home.toString() override fun getVersionString() = "1.2.3" override fun getSuggestedSdkName() = sdk.sdkName!! } } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .withSdkName("xqwr") .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixLocal", "configure: xqwr", "sdk-name: xqwr", "sdk: xqwr", ) } fun `test local fix with SDK prototype`() { val prototypeSdk = newSdk("prototype") val auto = object : UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix { val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" } override fun getExistingSdkHome() = home.toString() override fun getVersionString() = "1.2.3" override fun getSuggestedSdkName() = sdk.sdkName!! override fun getRegisteredSdkPrototype() = prototypeSdk } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .lookupBlocking() } assertLog( "sdk-name: prototype", "sdk: prototype", ) } fun `test local fix with unregistered SDK prototype`() { val prototypeSdk = newUnregisteredSdk("prototype") val auto = object : UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix { val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" } override fun getExistingSdkHome() = home.toString() override fun getVersionString() = "1.2.3" override fun getSuggestedSdkName() = "suggested-name" override fun getRegisteredSdkPrototype() = prototypeSdk } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixLocal", "configure: suggested-name", "sdk-name: suggested-name", "sdk: suggested-name", ) } fun `test local fix with stop`() { val prototypeSdk = newUnregisteredSdk("prototype") val auto = object : UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix { val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" } override fun getExistingSdkHome() = home.toString() override fun getVersionString() = "1.2.3" override fun getSuggestedSdkName() = "suggested-name" override fun getRegisteredSdkPrototype() = prototypeSdk } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .onSdkFixResolved(SdkLookupDecision.STOP) .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixLocal", "sdk-name: null", "sdk: null", ) } fun `test local fix should not clash with SDK name`() { val prototypeSdk = newSdk("prototype") val auto = object : UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix { val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" } override fun getExistingSdkHome() = home.toString() override fun getVersionString() = "1.2.3" override fun getSuggestedSdkName() = prototypeSdk.name } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixLocal", "configure: prototype (2)", "sdk-name: prototype (2)", "sdk: prototype (2)", ) } fun `test download fix`() { val auto = object: UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? = null override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? { if (sdk.sdkName != "xqwr") return null return object : UnknownSdkDownloadableSdkFix { override fun getDownloadDescription(): String = "download description" override fun createTask(indicator: ProgressIndicator) = object: SdkDownloadTask { override fun getSuggestedSdkName() = sdk.sdkName!! override fun getPlannedHomeDir() = home.toString() override fun getPlannedVersion() = versionString override fun doDownload(indicator: ProgressIndicator) { log += "download: ${sdk.sdkName}" } } val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"} override fun getVersionString() = "1.2.3" } } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .withSdkName("xqwr") .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixDownload", "sdk-name: xqwr", "download: xqwr", "configure: xqwr", "sdk: xqwr", ) } fun `test download fix stop`() { val auto = object: UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? = null override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? { if (sdk.sdkName != "xqwr") return null return object : UnknownSdkDownloadableSdkFix { override fun getDownloadDescription(): String = "download description" override fun createTask(indicator: ProgressIndicator) = object: SdkDownloadTask { override fun getSuggestedSdkName() = sdk.sdkName!! override fun getPlannedHomeDir() = home.toString() override fun getPlannedVersion() = versionString override fun doDownload(indicator: ProgressIndicator) { log += "download: ${sdk.sdkName}" } } val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"} override fun getVersionString() = "1.2.3" } } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .onSdkFixResolved(SdkLookupDecision.STOP) .withSdkName("xqwr") .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixDownload", "sdk-name: null", "sdk: null", ) } fun `test download fix should not clash SDK name`() { val prototypeSdk = newSdk("prototype") val auto = object: UnknownSdkResolver { override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup { override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? = null override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkDownloadableSdkFix { override fun getDownloadDescription(): String = "download description" override fun createTask(indicator: ProgressIndicator) = object: SdkDownloadTask { override fun getSuggestedSdkName() = prototypeSdk.name override fun getPlannedHomeDir() = home.toString() override fun getPlannedVersion() = versionString override fun doDownload(indicator: ProgressIndicator) { log += "download: ${sdk.sdkName}" } } val home = createTempDir("our home for ${sdk.sdkName}") override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"} override fun getVersionString() = "1.2.3" } } } ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable) runInThreadAndPumpMessages { lookup .lookupBlocking() } assertLog( "fix: UnknownMissingSdkFixDownload", "sdk-name: prototype (2)", "download: null", "configure: prototype (2)", "sdk: prototype (2)", ) } private fun newSdk(sdkName: String, version: String = "1.2.3"): Sdk { return WriteAction.compute<Sdk, Throwable> { val sdk = newUnregisteredSdk(sdkName, version) ProjectJdkTable.getInstance().addJdk(sdk, testRootDisposable) sdk } } private fun newUnregisteredSdk(sdkName: String, version: String = "1.2.3"): Sdk { val sdk = ProjectJdkTable.getInstance().createSdk(sdkName, sdkType) sdk.sdkModificator.also { it.versionString = version }.commitChanges() if (sdk is Disposable) { Disposer.register(testRootDisposable, sdk) } return sdk } private fun <R> runInThreadAndPumpMessages(action: () -> R) : R { val result = AtomicReference<Result<R>>(null) val th = threadEx { result.set(runCatching { action() }) } while (th.isAlive) { ProgressManager.checkCanceled() UIUtil.dispatchAllInvocationEvents() th.join(100) } return result.get()?.getOrThrow() ?: error("No result was set") } private fun threadEx(task: () -> Unit): Thread { val thread = thread(block = task) Disposer.register(testRootDisposable, Disposable { thread.interrupt(); thread.join(500) }) return thread } }
apache-2.0
8278d19b0bd79db6902bc25536b7404c
36.621188
142
0.672882
5.054561
false
true
false
false
alibaba/transmittable-thread-local
ttl2-compatible/src/test/java/com/alibaba/ttl/testmodel/FooTask.kt
1
1203
package com.alibaba.ttl.testmodel import com.alibaba.CHILD_CREATE import com.alibaba.PARENT_CREATE_MODIFIED_IN_CHILD import com.alibaba.copyTtlValues import com.alibaba.ttl.TransmittableThreadLocal import mu.KotlinLogging import java.util.concurrent.ConcurrentMap /** * @author Jerry Lee (oldratlee at gmail dot com) */ class FooTask( private val value: String, private val ttlInstances: ConcurrentMap<String, TransmittableThreadLocal<FooPojo>> ) : Runnable { private val logger = KotlinLogging.logger {} @Volatile lateinit var copied: Map<String, FooPojo> override fun run() { try { // Add new val child = DeepCopyFooTransmittableThreadLocal() child.set(FooPojo(CHILD_CREATE + value, 3)) ttlInstances[CHILD_CREATE + value] = child // modify the parent key ttlInstances[PARENT_CREATE_MODIFIED_IN_CHILD]!!.get()!!.name = ttlInstances[PARENT_CREATE_MODIFIED_IN_CHILD]!!.get()!!.name + value copied = copyTtlValues(ttlInstances) logger.info { "Task $value finished!" } } catch (e: Throwable) { e.printStackTrace() } } }
apache-2.0
e5eeb01f155c041ef80e94fda92c22c3
28.341463
86
0.65586
4.191638
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/fromFinalJavaToKotlin/delegateToKotlinExtentionProperty.kt
12
1451
val JavaClass.propertyFromKotlin: Int get() = 42 fun a() { JavaClass().field JavaClass().field.let(::println) val d = JavaClass() d.field d.let { it.field } d.also { it.field } with(d) { field } with(d) out@{ with(4) { [email protected] } } } fun a2() { val d: JavaClass? = null d?.field d?.field?.let(::println) d?.let { it.field } d?.also { it.field } d?.also { it.field.let(::println) } with(d) { this?.field } with(d) out@{ with(4) { this@out?.field } } } fun a3() { val d: JavaClass? = null val a1 = d?.field val a2 = d?.let { it.field } val a3 = d?.also { it.field } val a4 = with(d) { this?.field } val a5 = with(d) out@{ with(4) { this@out?.field } } } fun a4() { val d: JavaClass? = null d?.field?.dec() val a2 = d?.let { it.field } a2?.toLong() d?.also { it.field }?.field?.and(4) val a4 = with(d) { this?.field } val a5 = with(d) out@{ with(4) { this@out?.field } } val a6 = a4?.let { out -> a5?.let { out + it } } } fun JavaClass.b(): Int? = field fun JavaClass.c(): Int = this.field fun d(d: JavaClass) = d.field
apache-2.0
a89decdba46517f36a1bb97325b5b7d7
12.435185
52
0.423156
3.154348
false
false
false
false
smmribeiro/intellij-community
platform/core-ui/src/ui/ScalingDeferredSquareImageIcon.kt
9
1333
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui import com.intellij.ui.scale.ScaleContext import com.intellij.util.IconUtil import com.intellij.util.ui.ImageUtil import java.awt.Component import java.awt.Graphics import java.awt.Image import javax.swing.Icon class ScalingDeferredSquareImageIcon<K : Any>(size: Int, defaultIcon: Icon, private val key: K, imageLoader: (K) -> Image?) : Icon { private val baseIcon = IconUtil.resizeSquared(defaultIcon, size) private val scaledIconCache = ScaleContext.Cache { scaleCtx -> IconDeferrer.getInstance().defer(baseIcon, key) { try { imageLoader(it)?.let { image -> val resizedImage = ImageUtil.resize(image, size, scaleCtx) IconUtil.createImageIcon(resizedImage) } ?: baseIcon } catch (e: Exception) { baseIcon } } } override fun getIconHeight() = baseIcon.iconHeight override fun getIconWidth() = baseIcon.iconWidth override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) { scaledIconCache.getOrProvide(ScaleContext.create(c))?.paintIcon(c, g, x, y) } }
apache-2.0
cae7b3f37b7b89cd07332367f8720aed
35.054054
158
0.663916
4.231746
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/debugger/evaluate/AbstractCodeFragmentHighlightingTest.kt
2
2297
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.openapi.util.io.FileUtil import org.jetbrains.kotlin.checkers.AbstractKotlinHighlightVisitorTest import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.InTextDirectivesUtils import java.io.File abstract class AbstractCodeFragmentHighlightingTest : AbstractKotlinHighlightVisitorTest() { override fun doTest(filePath: String) { myFixture.configureByCodeFragment(filePath) checkHighlighting(filePath) } fun doTestWithImport(filePath: String) { myFixture.configureByCodeFragment(filePath) project.executeWriteCommand("Imports insertion") { val fileText = FileUtil.loadFile(File(filePath), true) val file = myFixture.file as KtFile InTextDirectivesUtils.findListWithPrefixes(fileText, "// IMPORT: ").forEach { val descriptor = file.resolveImportReference(FqName(it)).singleOrNull() ?: error("Could not resolve descriptor to import: $it") ImportInsertHelper.getInstance(project).importDescriptor(file, descriptor) } } checkHighlighting(filePath) } private fun checkHighlighting(filePath: String) { val inspectionName = InTextDirectivesUtils.findStringWithPrefixes(File(filePath).readText(), "// INSPECTION_CLASS: ") if (inspectionName != null) { val inspection = Class.forName(inspectionName).newInstance() as InspectionProfileEntry myFixture.enableInspections(inspection) try { myFixture.checkHighlighting(true, false, false) } finally { myFixture.disableInspections(inspection) } return } myFixture.checkHighlighting(true, false, false) } }
apache-2.0
d663597faadf8245de4dc4649ab079fd
42.358491
158
0.717458
5.292627
false
true
false
false
google/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/EditorTabPreview.kt
5
9292
// 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 import com.intellij.diff.DiffDialogHints import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.chains.SimpleDiffRequestChain import com.intellij.diff.editor.DiffEditorEscapeAction import com.intellij.diff.editor.DiffEditorTabFilesManager import com.intellij.diff.editor.DiffVirtualFileBase import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.diff.tools.external.ExternalDiffTool import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Disposer.isDisposed import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent import com.intellij.util.IJSwingUtilities import com.intellij.util.Processor import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import org.jetbrains.annotations.Nls import java.awt.event.KeyEvent import java.awt.event.MouseEvent import javax.swing.JComponent abstract class EditorTabPreview(protected val diffProcessor: DiffRequestProcessor) : EditorTabPreviewBase(diffProcessor.project!!, diffProcessor) { override val previewFile: VirtualFile = EditorTabDiffPreviewVirtualFile(diffProcessor, ::getCurrentName) override val updatePreviewProcessor: DiffPreviewUpdateProcessor get() = diffProcessor as DiffPreviewUpdateProcessor } abstract class EditorTabPreviewBase(protected val project: Project, protected val parentDisposable: Disposable) : DiffPreview { private val updatePreviewQueue = MergingUpdateQueue("updatePreviewQueue", 100, true, null, parentDisposable).apply { setRestartTimerOnAdd(true) } protected abstract val updatePreviewProcessor: DiffPreviewUpdateProcessor protected abstract val previewFile: VirtualFile var escapeHandler: Runnable? = null fun installListeners(tree: ChangesTree, isOpenEditorDiffPreviewWithSingleClick: Boolean) { installDoubleClickHandler(tree) installEnterKeyHandler(tree) if (isOpenEditorDiffPreviewWithSingleClick) { //do not open file aggressively on start up, do it later DumbService.getInstance(project).smartInvokeLater { if (isDisposed(updatePreviewQueue)) return@smartInvokeLater installSelectionHandler(tree, true) } } else { installSelectionHandler(tree, false) } } fun installSelectionHandler(tree: ChangesTree, isOpenEditorDiffPreviewWithSingleClick: Boolean) { installSelectionChangedHandler(tree) { if (isOpenEditorDiffPreviewWithSingleClick) { if (!openPreview(false)) closePreview() // auto-close editor tab if nothing to preview } else { updatePreview(false) } } } fun installNextDiffActionOn(component: JComponent) { DumbAwareAction.create { openPreview(true) }.apply { copyShortcutFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_NEXT_DIFF)) registerCustomShortcutSet(component, parentDisposable) } } protected open fun isPreviewOnDoubleClickAllowed(): Boolean = true protected open fun isPreviewOnEnterAllowed(): Boolean = true private fun installDoubleClickHandler(tree: ChangesTree) { val oldDoubleClickHandler = tree.doubleClickHandler val newDoubleClickHandler = Processor<MouseEvent> { e -> if (isToggleEvent(tree, e)) return@Processor false isPreviewOnDoubleClickAllowed() && performDiffAction() || oldDoubleClickHandler?.process(e) == true } tree.doubleClickHandler = newDoubleClickHandler Disposer.register(parentDisposable, Disposable { tree.doubleClickHandler = oldDoubleClickHandler }) } private fun installEnterKeyHandler(tree: ChangesTree) { val oldEnterKeyHandler = tree.enterKeyHandler val newEnterKeyHandler = Processor<KeyEvent> { e -> isPreviewOnEnterAllowed() && performDiffAction() || oldEnterKeyHandler?.process(e) == true } tree.enterKeyHandler = newEnterKeyHandler Disposer.register(parentDisposable, Disposable { tree.enterKeyHandler = oldEnterKeyHandler }) } private fun installSelectionChangedHandler(tree: ChangesTree, handler: () -> Unit) = tree.addSelectionListener( Runnable { updatePreviewQueue.queue(DisposableUpdate.createDisposable(updatePreviewQueue, this) { if (!skipPreviewUpdate()) handler() }) }, updatePreviewQueue ) protected abstract fun getCurrentName(): String? protected abstract fun hasContent(): Boolean protected open fun skipPreviewUpdate(): Boolean = ToolWindowManager.getInstance(project).isEditorComponentActive override fun updatePreview(fromModelRefresh: Boolean) { if (isPreviewOpen()) { updatePreviewProcessor.refresh(false) } else { updatePreviewProcessor.clear() } } protected fun isPreviewOpen(): Boolean = FileEditorManager.getInstance(project).isFileOpenWithRemotes(previewFile) override fun closePreview() { FileEditorManager.getInstance(project).closeFile(previewFile) updatePreviewProcessor.clear() } override fun openPreview(requestFocus: Boolean): Boolean { if (!ensureHasContent()) return false return openPreviewEditor(requestFocus) } private fun ensureHasContent(): Boolean { updatePreviewProcessor.refresh(false) return hasContent() } private fun openPreviewEditor(requestFocus: Boolean): Boolean { escapeHandler?.let { handler -> registerEscapeHandler(previewFile, handler) } openPreview(project, previewFile, requestFocus) return true } override fun performDiffAction(): Boolean { if (!ensureHasContent()) return false if (ExternalDiffTool.isEnabled()) { val processorWithProducers = updatePreviewProcessor as? DiffRequestProcessorWithProducers if (processorWithProducers != null ) { var diffProducers = processorWithProducers.collectDiffProducers(true) if (diffProducers != null && diffProducers.isEmpty) { diffProducers = processorWithProducers.collectDiffProducers(false)?.list?.firstOrNull() ?.let { ListSelection.createSingleton(it) } } if (showExternalToolIfNeeded(project, diffProducers)) { return true } } } return openPreviewEditor(true) } internal class EditorTabDiffPreviewVirtualFile(diffProcessor: DiffRequestProcessor, tabNameProvider: () -> String?) : PreviewDiffVirtualFile(EditorTabDiffPreviewProvider(diffProcessor, tabNameProvider)) { init { // EditorTabDiffPreviewProvider does not create new processor, so general assumptions of DiffVirtualFile are violated diffProcessor.putContextUserData(DiffUserDataKeysEx.DIFF_IN_EDITOR_WITH_EXPLICIT_DISPOSABLE, true) } } companion object { fun openPreview(project: Project, file: VirtualFile, focusEditor: Boolean): Array<out FileEditor> { return DiffEditorTabFilesManager.getInstance(project).showDiffFile(file, focusEditor) } fun registerEscapeHandler(file: VirtualFile, handler: Runnable) { file.putUserData(DiffVirtualFileBase.ESCAPE_HANDLER, EditorTabPreviewEscapeAction(handler)) } fun showExternalToolIfNeeded(project: Project?, diffProducers: ListSelection<out DiffRequestProducer>?): Boolean { if (diffProducers == null || diffProducers.isEmpty) return false val producers = diffProducers.explicitSelection return ExternalDiffTool.showIfNeeded(project, producers, DiffDialogHints.DEFAULT) } } } internal class EditorTabPreviewEscapeAction(private val escapeHandler: Runnable) : DumbAwareAction(), DiffEditorEscapeAction { override fun actionPerformed(e: AnActionEvent) = escapeHandler.run() } private class EditorTabDiffPreviewProvider( private val diffProcessor: DiffRequestProcessor, private val tabNameProvider: () -> String? ) : ChainBackedDiffPreviewProvider { override fun createDiffRequestProcessor(): DiffRequestProcessor { IJSwingUtilities.updateComponentTreeUI(diffProcessor.component) return diffProcessor } override fun getOwner(): Any = this override fun getEditorTabName(processor: DiffRequestProcessor?): @Nls String = tabNameProvider().orEmpty() override fun createDiffRequestChain(): DiffRequestChain? { if (diffProcessor is DiffRequestProcessorWithProducers) { val producers = diffProcessor.collectDiffProducers(false) ?: return null return SimpleDiffRequestChain.fromProducers(producers) } return null } }
apache-2.0
ec48dbf72ea2a5dc258cb0545daa4c5e
38.540426
126
0.773461
4.966328
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/stable/MountDetailRecyclerFragment.kt
1
4806
package com.habitrpg.android.habitica.ui.fragments.inventory.stable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.OwnedMount import com.habitrpg.android.habitica.ui.adapter.inventory.MountDetailRecyclerAdapter import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.helpers.MarginDecoration import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator import com.habitrpg.android.habitica.ui.helpers.bindView import io.reactivex.functions.Consumer import javax.inject.Inject class MountDetailRecyclerFragment : BaseMainFragment() { @Inject internal lateinit var inventoryRepository: InventoryRepository private val recyclerView: androidx.recyclerview.widget.RecyclerView by bindView(R.id.recyclerView) var adapter: MountDetailRecyclerAdapter? = null var animalType: String? = null var animalGroup: String? = null var animalColor: String? = null internal var layoutManager: androidx.recyclerview.widget.GridLayoutManager? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { this.usesTabLayout = false super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_recyclerview, container, false) } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val args = MountDetailRecyclerFragmentArgs.fromBundle(it) animalGroup = args.group animalType = args.type animalColor = args.color } layoutManager = androidx.recyclerview.widget.GridLayoutManager(activity, 2) recyclerView.layoutManager = layoutManager recyclerView.addItemDecoration(MarginDecoration(activity)) adapter = recyclerView.adapter as? MountDetailRecyclerAdapter if (adapter == null) { adapter = MountDetailRecyclerAdapter(null, true) adapter?.itemType = this.animalType adapter?.context = context recyclerView.adapter = adapter recyclerView.itemAnimator = SafeDefaultItemAnimator() this.loadItems() adapter?.getEquipFlowable()?.flatMap { key -> inventoryRepository.equip(user, "mount", key) } ?.subscribe(Consumer { }, RxErrorHandler.handleEmptyError())?.let { compositeSubscription.add(it) } } if (savedInstanceState != null) { this.animalType = savedInstanceState.getString(ANIMAL_TYPE_KEY, "") } view.post { setGridSpanCount(view.width) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(ANIMAL_TYPE_KEY, this.animalType) } private fun setGridSpanCount(width: Int) { var spanCount = 0 context?.resources?.let { resources val itemWidth: Float = resources.getDimension(R.dimen.pet_width) spanCount = (width / itemWidth).toInt() } if (spanCount == 0) { spanCount = 1 } layoutManager?.spanCount = spanCount layoutManager?.requestLayout() } private fun loadItems() { if (animalType != null && animalGroup != null) { compositeSubscription.add(inventoryRepository.getOwnedMounts().firstElement() .map { ownedMounts -> val mountMap = mutableMapOf<String, OwnedMount>() ownedMounts.forEach { mountMap[it.key ?: ""] = it } return@map mountMap } .subscribe(Consumer { adapter?.setOwnedMounts(it) }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(inventoryRepository.getMounts(animalType!!, animalGroup!!, animalColor).firstElement().subscribe(Consumer { adapter?.updateData(it) }, RxErrorHandler.handleEmptyError())) } } companion object { private const val ANIMAL_TYPE_KEY = "ANIMAL_TYPE_KEY" } }
gpl-3.0
32ab6e48e17dbdbd0b78b6311cf61efe
38.386555
208
0.672701
5.123667
false
false
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/ops/dependencies/common/UpdatePlugins.kt
1
3049
package flank.scripts.ops.dependencies import flank.scripts.ops.dependencies.common.Dependency import flank.scripts.ops.dependencies.common.DependencyUpdate import flank.scripts.ops.dependencies.common.outDatedDependencies import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Collectors internal fun File.updatePlugins(pluginsFile: File, versionsFile: File, buildGradleDirectory: String = "") { versionsFile.updateVersions( dependencies = getDependenciesUpdate(findPluginsValNames(pluginsFile), buildGradleDirectory) ) } private fun getDependenciesUpdate( pluginsValNames: List<Pair<Dependency, String>>, buildGradleDirectory: String ) = findBuildGradleFiles(buildGradleDirectory) .getPluginsBlock() .fold(setOf<DependencyUpdate>()) { currentSet, pluginsBlock -> currentSet + pluginsBlock.findVersionsValNameFor(pluginsValNames).flatten().mapNotNull { it } } .toList() private fun findBuildGradleFiles(buildGradleDirectory: String) = Files.walk(Paths.get(buildGradleDirectory)) .filter { it.fileName.toString() == BUILD_GRADLE_FILE_NAME } .map { it.toFile() } .collect(Collectors.toList()) private fun List<File>.getPluginsBlock() = mapNotNull { pluginsBlockRegex.find(it.readText()) } .map { it.value } private fun File.findPluginsValNames(pluginsFile: File) = outDatedDependencies() .filter { it.name?.contains("gradle.plugin") ?: false } .map { dependency -> dependency to dependency.group.findPluginValNames(pluginsFile) } .filter { (_, pluginVal) -> pluginVal.isNotEmpty() } private fun String.findPluginValNames(pluginsFile: File) = pluginsFile.readLines() .find { line -> line.contains(this) } ?.pluginValName .orEmpty() private fun String.findVersionsValNameFor(pluginValNames: List<Pair<Dependency, String>>) = split("\n") .map { line -> pluginValNames.getDependenciesUpdateFor(line) } private fun List<Pair<Dependency, String>>.getDependenciesUpdateFor(line: String) = map { it.getDependencyUpdateIfPresent(line) } private fun Pair<Dependency, String>.getDependencyUpdateIfPresent(line: String): DependencyUpdate? { val (dependency, pluginVal) = this return line.getDependencyValOrNull(pluginVal)?.let { DependencyUpdate( name = dependency.group, valName = it, oldVersion = dependency.version, newVersion = dependency.versionToUpdate ) } } private fun String.getDependencyValOrNull(pluginVal: String) = takeIf { contains(pluginVal) }?.let { findValName() } private fun String.findValName() = variableNameRegex.find(trim())?.value?.split(".")?.last() private val String.pluginValName get() = trim().replace("const val ", "").split(" ").first() private val pluginsBlockRegex = "plugins \\{(\\n)(\\s*.*\\n)*?}".toRegex() private val variableNameRegex = ("Versions\\..+".toRegex()) private const val BUILD_GRADLE_FILE_NAME = "build.gradle.kts"
apache-2.0
57d644ed7e40a026cccd8f1a12f35971
38.597403
116
0.716628
4.12027
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/foldInitializerAndIfToElvis/ExplicitVarType.kt
4
141
// WITH_RUNTIME fun foo(): String? = null fun bar() { var v: String? = foo() <caret>if (v == null) throw Exception() v = null }
apache-2.0
93cd1148d2143834de0392b16e898f13
14.777778
43
0.546099
3
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/settings/CodeVisionGroupDefaultSettingModel.kt
1
3647
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.codeVision.settings import com.intellij.codeInsight.codeVision.CodeVisionAnchorKind import com.intellij.codeInsight.codeVision.CodeVisionBundle import com.intellij.codeInsight.codeVision.CodeVisionHost import com.intellij.codeInsight.codeVision.CodeVisionProvider import com.intellij.codeInsight.hints.codeVision.CodeVisionPass import com.intellij.codeInsight.hints.codeVision.CodeVisionProviderAdapter import com.intellij.lang.Language import com.intellij.openapi.editor.Editor import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.util.Key import com.intellij.psi.PsiFile import com.intellij.ui.dsl.builder.panel import com.intellij.util.ResourceUtil import javax.swing.JComponent open class CodeVisionGroupDefaultSettingModel(override val name: String, groupId: String, override val description: String?, isEnabled: Boolean, val providers: List<CodeVisionProvider<*>>) : CodeVisionGroupSettingModel(isEnabled, id = groupId) { companion object { private val CODE_VISION_PREVIEW_ENABLED = Key<Boolean>("code.vision.preview.data") internal fun isEnabledInPreview(editor: Editor) : Boolean? { return editor.getUserData(CODE_VISION_PREVIEW_ENABLED) } } private val settings = CodeVisionSettings.instance() private lateinit var positionComboBox: ComboBox<CodeVisionAnchorKind> override fun collectData(editor: Editor, file: PsiFile): Runnable { for (provider in providers) { provider.preparePreview(editor, file) } val daemonBoundProviders = providers.filterIsInstance<CodeVisionProviderAdapter>().map { it.delegate } val codeVisionData = CodeVisionPass.collectData(editor, file, daemonBoundProviders) return Runnable { editor.putUserData(CODE_VISION_PREVIEW_ENABLED, isEnabled) val project = editor.project ?: return@Runnable codeVisionData.applyTo(editor, project) CodeVisionHost.getInstance(project).invalidateProviderSignal .fire(CodeVisionHost.LensInvalidateSignal(editor)) } } override val component: JComponent = panel { row { label(CodeVisionBundle.message("CodeVisionConfigurable.column.name.position")) positionComboBox = comboBox(CodeVisionGlobalSettingsProvider.supportedAnchors).component } } override val previewText: String? get() = getCasePreview() override val previewLanguage: Language? get() = Language.findLanguageByID("JAVA") override fun isModified(): Boolean { return (isEnabled != (settings.isProviderEnabled(id) && settings.codeVisionEnabled) || positionComboBox.item != (settings.getPositionForGroup(id) ?: settings.defaultPosition)) } override fun apply() { settings.setProviderEnabled(id, isEnabled) settings.setPositionForGroup(id, positionComboBox.item) } override fun reset() { isEnabled = settings.isProviderEnabled(id) && settings.codeVisionEnabled positionComboBox.item = settings.getPositionForGroup(id) ?: CodeVisionAnchorKind.Default } private fun getCasePreview(): String? { val path = "codeVisionProviders/" + id + "/preview." + previewLanguage?.associatedFileType?.defaultExtension val stream = this.javaClass.classLoader.getResourceAsStream(path) return if (stream != null) ResourceUtil.loadText(stream) else null } }
apache-2.0
ee90966c3db125c6f1677676f47eab02
42.416667
158
0.73677
4.882195
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/main/MainActivityListHostFragment.kt
1
14037
package org.thoughtcrime.securesms.main import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.ActionMenuView import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.children import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.Navigator import androidx.navigation.findNavController import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.recyclerview.widget.RecyclerView import org.signal.core.util.concurrent.SimpleTask import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.MainActivity import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.badges.BadgeImageView import org.thoughtcrime.securesms.components.Material3SearchToolbar import org.thoughtcrime.securesms.components.TooltipPopup import org.thoughtcrime.securesms.components.settings.app.AppSettingsActivity import org.thoughtcrime.securesms.components.settings.app.notifications.manual.NotificationProfileSelectionFragment import org.thoughtcrime.securesms.conversationlist.ConversationListFragment import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.notifications.profiles.NotificationProfile import org.thoughtcrime.securesms.notifications.profiles.NotificationProfiles import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.stories.tabs.ConversationListTab import org.thoughtcrime.securesms.stories.tabs.ConversationListTabsState import org.thoughtcrime.securesms.stories.tabs.ConversationListTabsViewModel import org.thoughtcrime.securesms.util.AvatarUtil import org.thoughtcrime.securesms.util.BottomSheetUtil import org.thoughtcrime.securesms.util.Material3OnScrollHelper import org.thoughtcrime.securesms.util.TopToastPopup import org.thoughtcrime.securesms.util.TopToastPopup.Companion.show import org.thoughtcrime.securesms.util.Util import org.thoughtcrime.securesms.util.runHideAnimation import org.thoughtcrime.securesms.util.runRevealAnimation import org.thoughtcrime.securesms.util.views.Stub import org.thoughtcrime.securesms.util.visible import org.whispersystems.signalservice.api.websocket.WebSocketConnectionState class MainActivityListHostFragment : Fragment(R.layout.main_activity_list_host_fragment), ConversationListFragment.Callback, Material3OnScrollHelperBinder { companion object { private val TAG = Log.tag(MainActivityListHostFragment::class.java) } private val conversationListTabsViewModel: ConversationListTabsViewModel by viewModels(ownerProducer = { requireActivity() }) private lateinit var _toolbarBackground: View private lateinit var _toolbar: Toolbar private lateinit var _basicToolbar: Stub<Toolbar> private lateinit var notificationProfileStatus: ImageView private lateinit var proxyStatus: ImageView private lateinit var _searchToolbar: Stub<Material3SearchToolbar> private lateinit var _searchAction: ImageView private lateinit var _unreadPaymentsDot: View private var previousTopToastPopup: TopToastPopup? = null private val destinationChangedListener = DestinationChangedListener() private val openSettings = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == MainActivity.RESULT_CONFIG_CHANGED) { requireActivity().recreate() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { _toolbarBackground = view.findViewById(R.id.toolbar_background) _toolbar = view.findViewById(R.id.toolbar) _basicToolbar = Stub(view.findViewById(R.id.toolbar_basic_stub)) notificationProfileStatus = view.findViewById(R.id.conversation_list_notification_profile_status) proxyStatus = view.findViewById(R.id.conversation_list_proxy_status) _searchAction = view.findViewById(R.id.search_action) _searchToolbar = Stub(view.findViewById(R.id.search_toolbar)) _unreadPaymentsDot = view.findViewById(R.id.unread_payments_indicator) notificationProfileStatus.setOnClickListener { handleNotificationProfile() } proxyStatus.setOnClickListener { onProxyStatusClicked() } initializeSettingsTouchTarget() (requireActivity() as AppCompatActivity).setSupportActionBar(_toolbar) conversationListTabsViewModel.state.observe(viewLifecycleOwner) { state -> val controller: NavController = requireView().findViewById<View>(R.id.fragment_container).findNavController() when (controller.currentDestination?.id) { R.id.conversationListFragment -> goToStateFromConversationList(state, controller) R.id.conversationListArchiveFragment -> Unit R.id.storiesLandingFragment -> goToStateFromStories(state, controller) } } } private fun goToStateFromConversationList(state: ConversationListTabsState, navController: NavController) { if (state.tab == ConversationListTab.CHATS) { return } else { val cameraFab = requireView().findViewById<View>(R.id.camera_fab) val newConvoFab = requireView().findViewById<View>(R.id.fab) ViewCompat.setTransitionName(cameraFab, "camera_fab") ViewCompat.setTransitionName(newConvoFab, "new_convo_fab") val extras: Navigator.Extras? = if (cameraFab == null || newConvoFab == null) { null } else { FragmentNavigatorExtras( cameraFab to "camera_fab", newConvoFab to "new_convo_fab" ) } navController.navigate( R.id.action_conversationListFragment_to_storiesLandingFragment, null, null, extras ) } } private fun goToStateFromStories(state: ConversationListTabsState, navController: NavController) { if (state.tab == ConversationListTab.STORIES) { return } else { navController.popBackStack() } } override fun onResume() { super.onResume() SimpleTask.run(viewLifecycleOwner.lifecycle, { Recipient.self() }, ::initializeProfileIcon) requireView() .findViewById<View>(R.id.fragment_container) .findNavController() .addOnDestinationChangedListener(destinationChangedListener) } override fun onPause() { super.onPause() requireView() .findViewById<View>(R.id.fragment_container) .findNavController() .removeOnDestinationChangedListener(destinationChangedListener) } private fun presentToolbarForConversationListFragment() { if (_basicToolbar.resolved() && _basicToolbar.get().visible) { _toolbar.runRevealAnimation(R.anim.slide_from_start) } _toolbar.visible = true _searchAction.visible = true if (_basicToolbar.resolved() && _basicToolbar.get().visible) { _basicToolbar.get().runHideAnimation(R.anim.slide_to_end) } } private fun presentToolbarForConversationListArchiveFragment() { _toolbar.runHideAnimation(R.anim.slide_to_start) _basicToolbar.get().runRevealAnimation(R.anim.slide_from_end) } private fun presentToolbarForStoriesLandingFragment() { _toolbar.visible = true _searchAction.visible = true if (_basicToolbar.resolved()) { _basicToolbar.get().visible = false } } private fun presentToolbarForMultiselect() { _toolbar.visible = false if (_basicToolbar.resolved()) { _basicToolbar.get().visible = false } } override fun onDestroyView() { previousTopToastPopup = null super.onDestroyView() } override fun getToolbar(): Toolbar { return _toolbar } override fun getSearchAction(): ImageView { return _searchAction } override fun getSearchToolbar(): Stub<Material3SearchToolbar> { return _searchToolbar } override fun getUnreadPaymentsDot(): View { return _unreadPaymentsDot } override fun getBasicToolbar(): Stub<Toolbar> { return _basicToolbar } override fun onSearchOpened() { conversationListTabsViewModel.onSearchOpened() _searchToolbar.get().clearText() _searchToolbar.get().display(_searchAction.x + (_searchAction.width / 2.0f), _searchAction.y + (_searchAction.height / 2.0f)) } override fun onSearchClosed() { conversationListTabsViewModel.onSearchClosed() } override fun onMultiSelectStarted() { presentToolbarForMultiselect() conversationListTabsViewModel.onMultiSelectStarted() } override fun onMultiSelectFinished() { val currentDestination: NavDestination? = requireView().findViewById<View>(R.id.fragment_container).findNavController().currentDestination if (currentDestination != null) { presentToolbarForDestination(currentDestination) } conversationListTabsViewModel.onMultiSelectFinished() } private fun initializeProfileIcon(recipient: Recipient) { Log.d(TAG, "Initializing profile icon") val icon = requireView().findViewById<ImageView>(R.id.toolbar_icon) val imageView: BadgeImageView = requireView().findViewById(R.id.toolbar_badge) imageView.setBadgeFromRecipient(recipient) AvatarUtil.loadIconIntoImageView(recipient, icon, resources.getDimensionPixelSize(R.dimen.toolbar_avatar_size)) } private fun initializeSettingsTouchTarget() { val touchArea = requireView().findViewById<View>(R.id.toolbar_settings_touch_area) touchArea.setOnClickListener { openSettings.launch(AppSettingsActivity.home(requireContext())) } } private fun handleNotificationProfile() { NotificationProfileSelectionFragment.show(parentFragmentManager) } private fun onProxyStatusClicked() { startActivity(AppSettingsActivity.proxy(requireContext())) } override fun updateProxyStatus(state: WebSocketConnectionState) { if (SignalStore.proxy().isProxyEnabled) { proxyStatus.visibility = View.VISIBLE when (state) { WebSocketConnectionState.CONNECTING, WebSocketConnectionState.DISCONNECTING, WebSocketConnectionState.DISCONNECTED -> proxyStatus.setImageResource(R.drawable.ic_proxy_connecting_24) WebSocketConnectionState.CONNECTED -> proxyStatus.setImageResource(R.drawable.ic_proxy_connected_24) WebSocketConnectionState.AUTHENTICATION_FAILED, WebSocketConnectionState.FAILED -> proxyStatus.setImageResource(R.drawable.ic_proxy_failed_24) else -> proxyStatus.visibility = View.GONE } } else { proxyStatus.visibility = View.GONE } } override fun updateNotificationProfileStatus(notificationProfiles: List<NotificationProfile>) { val activeProfile = NotificationProfiles.getActiveProfile(notificationProfiles) if (activeProfile != null) { if (activeProfile.id != SignalStore.notificationProfileValues().lastProfilePopup) { requireView().postDelayed({ SignalStore.notificationProfileValues().lastProfilePopup = activeProfile.id SignalStore.notificationProfileValues().lastProfilePopupTime = System.currentTimeMillis() if (previousTopToastPopup?.isShowing == true) { previousTopToastPopup?.dismiss() } var view = requireView() as ViewGroup val fragment = parentFragmentManager.findFragmentByTag(BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG) if (fragment != null && fragment.isAdded && fragment.view != null) { view = fragment.requireView() as ViewGroup } try { previousTopToastPopup = show(view, R.drawable.ic_moon_16, getString(R.string.ConversationListFragment__s_on, activeProfile.name)) } catch (e: Exception) { Log.w(TAG, "Unable to show toast popup", e) } }, 500L) } notificationProfileStatus.visibility = View.VISIBLE } else { notificationProfileStatus.visibility = View.GONE } if (!SignalStore.notificationProfileValues().hasSeenTooltip && Util.hasItems(notificationProfiles)) { val target: View? = findOverflowMenuButton(_toolbar) if (target != null) { TooltipPopup.forTarget(target) .setText(R.string.ConversationListFragment__turn_your_notification_profile_on_or_off_here) .setBackgroundTint(ContextCompat.getColor(requireContext(), R.color.signal_button_primary)) .setTextColor(ContextCompat.getColor(requireContext(), R.color.signal_button_primary_text)) .setOnDismissListener { SignalStore.notificationProfileValues().hasSeenTooltip = true } .show(TooltipPopup.POSITION_BELOW) } else { Log.w(TAG, "Unable to find overflow menu to show Notification Profile tooltip") } } } private fun findOverflowMenuButton(viewGroup: Toolbar): View? { return viewGroup.children.find { it is ActionMenuView } } private fun presentToolbarForDestination(destination: NavDestination) { when (destination.id) { R.id.conversationListFragment -> { conversationListTabsViewModel.isShowingArchived(false) presentToolbarForConversationListFragment() } R.id.conversationListArchiveFragment -> { conversationListTabsViewModel.isShowingArchived(true) presentToolbarForConversationListArchiveFragment() } R.id.storiesLandingFragment -> { conversationListTabsViewModel.isShowingArchived(false) presentToolbarForStoriesLandingFragment() } } } private inner class DestinationChangedListener : NavController.OnDestinationChangedListener { override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) { presentToolbarForDestination(destination) } } override fun bindScrollHelper(recyclerView: RecyclerView) { Material3OnScrollHelper( requireActivity(), listOf(_toolbarBackground), listOf(_searchToolbar) ).attach(recyclerView) } }
gpl-3.0
1e86925e01926be23b767653a8ef8349
38.991453
189
0.758923
4.724672
false
false
false
false
scenerygraphics/SciView
src/main/kotlin/sc/iview/commands/demo/animation/GameOfLife3D.kt
1
11386
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2021 SciView developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package sc.iview.commands.demo.animation import graphics.scenery.BoundingGrid import graphics.scenery.volumes.Volume import ij.gui.GenericDialog import net.imglib2.IterableInterval import net.imglib2.RandomAccess import net.imglib2.RandomAccessibleInterval import net.imglib2.Sampler import net.imglib2.img.Img import net.imglib2.img.array.ArrayImgs import net.imglib2.type.numeric.integer.UnsignedByteType import org.joml.Vector3f import org.scijava.command.* import org.scijava.event.EventHandler import org.scijava.module.Module import org.scijava.plugin.Menu import org.scijava.plugin.Parameter import org.scijava.plugin.Plugin import org.scijava.widget.Button import org.scijava.widget.NumberWidget import sc.iview.SciView import sc.iview.commands.MenuWeights import sc.iview.event.NodeRemovedEvent import sc.iview.ui.CustomPropertyUI import java.util.* /** * Conway's Game of Life in 3D! * * @author Curtis Rueden * @author Kyle Harrington * @author Ulrik Guenther */ @Plugin(type = Command::class, menuRoot = "SciView", menu = [Menu(label = "Demo", weight = MenuWeights.DEMO), Menu(label = "Animation", weight = MenuWeights.DEMO_ANIMATION), Menu(label = "Game of Life 3D", weight = MenuWeights.DEMO_ANIMATION_GOL3D)]) class GameOfLife3D : InteractiveCommand() { @Parameter private lateinit var sciView: SciView @Volatile @Parameter(label = "Starvation threshold", min = "0", max = "26", persist = false, style = "group:Game of Life") private var starvation = 5 @Volatile @Parameter(label = "Birth threshold", min = "0", max = "26", persist = false, style = "group:Game of Life") private var birth = 6 @Volatile @Parameter(label = "Suffocation threshold", min = "0", max = "26", persist = false, style = "group:Game of Life") private var suffocation = 9 @Volatile @Parameter(label = "Connectedness", choices = [SIX, EIGHTEEN, TWENTY_SIX], persist = false, style = "group:Game of Life") private var connectedness = TWENTY_SIX @Volatile @Parameter(label = "Initial saturation % when randomizing", min = "1", max = "99", style = NumberWidget.SCROLL_BAR_STYLE, persist = false) private var saturation = 10 @Volatile @Parameter(label = "Play speed", min = "1", max="100", style = NumberWidget.SCROLL_BAR_STYLE + ",group:Game of Life", persist = false) private var playSpeed: Int = 10 @Parameter(callback = "iterate") private lateinit var iterate: Button @Parameter(callback = "randomize") private lateinit var randomize: Button @Parameter(callback = "play", style = "group:Game of Life") private lateinit var play: Button @Parameter(callback = "pause", style = "group:Game of Life") private lateinit var pause: Button @Parameter(label = "Activate roflcopter", style = "group:Game of Life") private var roflcopter: Boolean = false private val w = 64 private val h = 64 private val d = 64 /** * Returns the current Img */ var img: Img<UnsignedByteType>? = null private set private var name: String = "Life Simulation" private var voxelDims: FloatArray = floatArrayOf(1.0f, 1.0f, 1.0f) /** * Returns the scenery volume node. */ var volume: Volume? = null private set /** Temporary buffer for use while recomputing the image. */ private val bits = BooleanArray(w * h * d) private var dialog: GenericDialog? = null /** Repeatedly iterates the simulation until stopped */ fun play() { sciView.animate(playSpeed) { iterate() } } /** Stops the simulation */ fun pause() { sciView.stopAnimation() } /** Randomizes a new bit field. */ fun randomize() { if( img == null ) img = ArrayImgs.unsignedBytes(w.toLong(), h.toLong(), d.toLong()) val cursor = img!!.localizingCursor() val chance = saturation / 100.0 while (cursor.hasNext()) { val alive = Math.random() <= chance cursor.next().set(if (alive) ALIVE else DEAD) } updateVolume() } /** Performs one iteration of the game. */ fun iterate() { val connected = when (connectedness) { SIX -> 6 EIGHTEEN -> 18 else -> 26 } // compute the new image field val access = img!!.randomAccess() for (z in 0 until d) { for (y in 0 until h) { for (x in 0 until w) { val i = z * w * h + y * w + x val n = neighbors(access, x, y, z, connected) access.setPosition(x, 0) access.setPosition(y, 1) access.setPosition(y, 2) if (alive(access)) { // Living cell stays alive within (starvation, suffocation). bits[i] = n in (starvation + 1) until suffocation } else { // New cell forms within [birth, suffocation). bits[i] = n in birth until suffocation } } } } // write the new bit field into the image val cursor = img!!.localizingCursor() while (cursor.hasNext()) { cursor.fwd() val x = cursor.getIntPosition(0) val y = cursor.getIntPosition(1) val z = cursor.getIntPosition(2) val alive = bits[z * w * h + y * w + x] cursor.get().set(if (alive) ALIVE else DEAD) } updateVolume() } override fun run() { randomize() } // -- Helper methods -- private fun neighbors(access: RandomAccess<UnsignedByteType>, x: Int, y: Int, z: Int, connected: Int): Int { var n = 0 // six-connected n += value(access, x - 1, y, z) n += value(access, x + 1, y, z) n += value(access, x, y - 1, z) n += value(access, x, y + 1, z) n += value(access, x, y, z - 1) n += value(access, x, y, z + 1) // eighteen-connected if (connected >= 18) { n += value(access, x - 1, y - 1, z) n += value(access, x + 1, y - 1, z) n += value(access, x - 1, y + 1, z) n += value(access, x + 1, y + 1, z) n += value(access, x - 1, y, z - 1) n += value(access, x + 1, y, z - 1) n += value(access, x - 1, y, z + 1) n += value(access, x + 1, y, z + 1) n += value(access, x, y - 1, z - 1) n += value(access, x, y + 1, z - 1) n += value(access, x, y - 1, z + 1) n += value(access, x, y + 1, z + 1) } // twenty-six-connected if (connected == 26) { n += value(access, x - 1, y - 1, z - 1) n += value(access, x + 1, y - 1, z - 1) n += value(access, x - 1, y + 1, z - 1) n += value(access, x + 1, y + 1, z - 1) n += value(access, x - 1, y - 1, z + 1) n += value(access, x + 1, y - 1, z + 1) n += value(access, x - 1, y + 1, z + 1) n += value(access, x + 1, y + 1, z + 1) } return n } private fun value(access: RandomAccess<UnsignedByteType>, x: Int, y: Int, z: Int): Int { if (x < 0 || x >= w || y < 0 || y >= h || z < 0 || z >= d) return 0 access.setPosition(x, 0) access.setPosition(y, 1) access.setPosition(z, 2) return if (alive(access)) 1 else 0 } private fun alive(access: Sampler<UnsignedByteType>): Boolean { return access.get().get() == ALIVE } private var tick: Long = 0 private fun updateVolume() { if (volume == null) { name = "Life Simulation" voxelDims = floatArrayOf(1f, 1f, 1f) volume = sciView.addVolume(img as RandomAccessibleInterval<UnsignedByteType>, name, *voxelDims) { val bg = BoundingGrid() bg.node = this transferFunction.addControlPoint(0.0f, 0.0f) transferFunction.addControlPoint(0.4f, 0.3f) this.spatialOrNull()?.scale = Vector3f(10.0f, 10.0f, 10.0f) name = "Game of Life 3D" sciView.centerOnNode(this) } // NB: Create dynamic metadata lazily. sciView.attachCustomPropertyUIToNode(volume!!, CustomPropertyUI( this, listOf( "starvation", "suffocation", "birth", "connectedness", "playSpeed", "play", "pause", "roflcopter" ) )) } else { // NB: Name must be unique each time. sciView.updateVolume(img as IterableInterval<UnsignedByteType>, name + "-" + ++tick, voxelDims, volume!!) } } /** * Stops the animation when the volume node is removed. * @param event */ @EventHandler private fun onNodeRemoved(event: NodeRemovedEvent) { if (event.node === volume) { sciView.stopAnimation() } } companion object { private const val ALIVE = 255 private const val DEAD = 16 private const val SIX = "6-connected" private const val EIGHTEEN = "18-connected" private const val TWENTY_SIX = "26-connected" @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val sv = SciView.create() val command = sv.scijavaContext!!.getService(CommandService::class.java) val argmap = HashMap<String, Any>() command.run(GameOfLife3D::class.java, true, argmap) } } }
bsd-2-clause
ce778875eea6f82f04bb5fce9bd2a15b
35.49359
152
0.57518
3.95622
false
false
false
false
androidx/androidx
compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/collection/IdentityArrayIntMap.kt
3
6882
/* * 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.compose.runtime.collection import androidx.compose.runtime.identityHashCode import kotlin.contracts.ExperimentalContracts @OptIn(ExperimentalContracts::class) internal class IdentityArrayIntMap { @PublishedApi internal var size = 0 @PublishedApi internal var keys: Array<Any?> = arrayOfNulls(4) @PublishedApi internal var values: IntArray = IntArray(4) operator fun get(key: Any): Int { val index = find(key) return if (index >= 0) values[index] else error("Key not found") } /** * Add [value] to the map and return `-1` if it was added or previous value if it already existed. */ fun add(key: Any, value: Int): Int { val index: Int if (size > 0) { index = find(key) if (index >= 0) { val previousValue = values[index] values[index] = value return previousValue } } else { index = -1 } val insertIndex = -(index + 1) if (size == keys.size) { val newKeys = arrayOfNulls<Any>(keys.size * 2) val newValues = IntArray(keys.size * 2) keys.copyInto( destination = newKeys, destinationOffset = insertIndex + 1, startIndex = insertIndex, endIndex = size ) values.copyInto( destination = newValues, destinationOffset = insertIndex + 1, startIndex = insertIndex, endIndex = size ) keys.copyInto( destination = newKeys, endIndex = insertIndex ) values.copyInto( destination = newValues, endIndex = insertIndex ) keys = newKeys values = newValues } else { keys.copyInto( destination = keys, destinationOffset = insertIndex + 1, startIndex = insertIndex, endIndex = size ) values.copyInto( destination = values, destinationOffset = insertIndex + 1, startIndex = insertIndex, endIndex = size ) } keys[insertIndex] = key values[insertIndex] = value size++ return -1 } /** * Remove [key] from the map. */ fun remove(key: Any): Boolean { val index = find(key) if (index >= 0) { if (index < size - 1) { keys.copyInto( destination = keys, destinationOffset = index, startIndex = index + 1, endIndex = size ) values.copyInto( destination = values, destinationOffset = index, startIndex = index + 1, endIndex = size ) } size-- keys[size] = null return true } return false } /** * Removes all values that match [predicate]. */ inline fun removeValueIf(predicate: (Any, Int) -> Boolean) { var destinationIndex = 0 for (i in 0 until size) { @Suppress("UNCHECKED_CAST") val key = keys[i] as Any val value = values[i] if (!predicate(key, value)) { if (destinationIndex != i) { keys[destinationIndex] = key values[destinationIndex] = value } destinationIndex++ } } for (i in destinationIndex until size) { keys[i] = null } size = destinationIndex } inline fun any(predicate: (Any, Int) -> Boolean): Boolean { for (i in 0 until size) { if (predicate(keys[i] as Any, values[i])) return true } return false } inline fun forEach(block: (Any, Int) -> Unit) { for (i in 0 until size) { block(keys[i] as Any, values[i]) } } /** * Returns the index of [key] in the set or the negative index - 1 of the location where * it would have been if it had been in the set. */ private fun find(key: Any?): Int { var low = 0 var high = size - 1 val valueIdentity = identityHashCode(key) while (low <= high) { val mid = (low + high).ushr(1) val midVal = keys[mid] val midIdentity = identityHashCode(midVal) when { midIdentity < valueIdentity -> low = mid + 1 midIdentity > valueIdentity -> high = mid - 1 midVal === key -> return mid else -> return findExactIndex(mid, key, valueIdentity) } } return -(low + 1) } /** * When multiple items share the same [identityHashCode], then we must find the specific * index of the target item. This method assumes that [midIndex] has already been checked * for an exact match for [value], but will look at nearby values to find the exact item index. * If no match is found, the negative index - 1 of the position in which it would be will * be returned, which is always after the last item with the same [identityHashCode]. */ private fun findExactIndex(midIndex: Int, value: Any?, valueHash: Int): Int { // hunt down first for (i in midIndex - 1 downTo 0) { val v = keys[i] if (v === value) { return i } if (identityHashCode(v) != valueHash) { break // we've gone too far } } for (i in midIndex + 1 until size) { val v = keys[i] if (v === value) { return i } if (identityHashCode(v) != valueHash) { // We've gone too far. We should insert here. return -(i + 1) } } // We should insert at the end return -(size + 1) } }
apache-2.0
7802931eb2129d0186483467f0a54409
30.286364
102
0.513078
4.789144
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/XProcessingStep.kt
3
3180
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing /** * Processing step to simplify processing a set of annotations. */ interface XProcessingStep { /** * The implementation of processing logic for the step. It is guaranteed that the keys in * [elementsByAnnotation] will be a subset of the set returned by [annotations]. * * @return the elements (a subset of the values of [elementsByAnnotation]) that this step * is unable to process, possibly until a later processing round. These elements will be * passed back to this step at the next round of processing. */ @Deprecated( message = "We're combining processOver() and this process() overload.", replaceWith = ReplaceWith( "process(XProcessingEnv, Map<String, Set<XElement>>, Boolean)"), level = DeprecationLevel.WARNING ) fun process( env: XProcessingEnv, elementsByAnnotation: Map<String, Set<XElement>> ): Set<XElement> = emptySet() /** * The implementation of processing logic for the step. It is guaranteed that the keys in * [elementsByAnnotation] will be a subset of the set returned by [annotations]. * * @return the elements (a subset of the values of [elementsByAnnotation]) that this step * is unable to process, possibly until a later processing round. These elements will be * passed back to this step at the next round of processing. */ @Suppress("deprecation") fun process( env: XProcessingEnv, elementsByAnnotation: Map<String, Set<XElement>>, isLastRound: Boolean ): Set<XElement> = if (isLastRound) { processOver(env, elementsByAnnotation) emptySet() } else { process(env, elementsByAnnotation) } /** * An optional hook for logic to be executed in the last round of processing. * * Unlike [process], the elements in [elementsByAnnotation] are not validated and are those * that have been kept being deferred. * * @see [XRoundEnv.isProcessingOver] */ @Deprecated( message = "We're combining processOver() and the original process().", replaceWith = ReplaceWith( "process(XProcessingEnv, Map<String, Set<XElement>>, Boolean)"), level = DeprecationLevel.WARNING ) fun processOver(env: XProcessingEnv, elementsByAnnotation: Map<String, Set<XElement>>) { } /** * The set of annotation qualified names processed by this step. */ fun annotations(): Set<String> }
apache-2.0
226022dd05d3b44af16353ac5df7d40c
37.780488
96
0.676101
4.697194
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/KotlinQualifiedNameProvider.kt
4
1635
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions import com.intellij.ide.actions.JavaQualifiedNameProvider import com.intellij.ide.actions.QualifiedNameProvider import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty class KotlinQualifiedNameProvider : QualifiedNameProvider { override fun adjustElementToCopy(element: PsiElement) = null override fun getQualifiedName(element: PsiElement) = when (element) { is KtClassOrObject -> element.fqName?.asString() is KtNamedFunction -> getJavaQualifiedName(LightClassUtil.getLightClassMethod(element)) is KtProperty -> { val lightClassPropertyMethods = LightClassUtil.getLightClassPropertyMethods(element) val lightElement: PsiElement? = lightClassPropertyMethods.getter ?: lightClassPropertyMethods.backingField getJavaQualifiedName(lightElement) } else -> null } private fun getJavaQualifiedName(element: PsiElement?) = element?.let { JavaQualifiedNameProvider().getQualifiedName(element) } override fun qualifiedNameToElement(fqn: String, project: Project) = null override fun insertQualifiedName(fqn: String, element: PsiElement, editor: Editor, project: Project) { } }
apache-2.0
e32bd52e992ff9bdf599d1c9c03f12f2
44.416667
158
0.77737
4.969605
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/declarationsSearch/overridersSearchUtils.kt
1
8365
// 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.search.declarationsSearch import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.util.Processor import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.isOverridable import org.jetbrains.kotlin.idea.caches.lightClasses.KtFakeLightMethod import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.core.getDirectlyOverriddenDeclarations import org.jetbrains.kotlin.idea.refactoring.resolveToExpectedDescriptorIfPossible import org.jetbrains.kotlin.idea.search.excludeKotlinSources import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor import org.jetbrains.kotlin.util.findCallableMemberBySignature fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean { val baseClassDescriptor = runReadAction { ktClass.unsafeResolveToDescriptor() as ClassDescriptor } val baseDescriptors = runReadAction { members.mapNotNull { it.unsafeResolveToDescriptor() as? CallableMemberDescriptor }.filter { it.isOverridable } } if (baseDescriptors.isEmpty()) return true HierarchySearchRequest(ktClass, scope, searchDeeply).searchInheritors().forEach(Processor { psiClass -> val inheritor = psiClass.unwrapped as? KtClassOrObject ?: return@Processor true runReadAction { val inheritorDescriptor = inheritor.unsafeResolveToDescriptor() as ClassDescriptor val substitutor = getTypeSubstitutor(baseClassDescriptor.defaultType, inheritorDescriptor.defaultType) ?: return@runReadAction true baseDescriptors.forEach { val superMember = it.source.getPsi()!! val overridingDescriptor = (it.substitute(substitutor) as? CallableMemberDescriptor)?.let { memberDescriptor -> inheritorDescriptor.findCallableMemberBySignature(memberDescriptor) } val overridingMember = overridingDescriptor?.source?.getPsi() if (overridingMember != null) { if (!processor(superMember, overridingMember)) return@runReadAction false } } true } }) return true } fun PsiMethod.forEachOverridingMethod( scope: SearchScope = runReadAction { useScope }, processor: (PsiMethod) -> Boolean ): Boolean { if (this !is KtFakeLightMethod) { if (!OverridingMethodsSearch.search(this, scope.excludeKotlinSources(), true).forEach(Processor { processor(it) })) return false } val ktMember = this.unwrapped as? KtNamedDeclaration ?: return true val ktClass = runReadAction { ktMember.containingClassOrObject as? KtClass } ?: return true return forEachKotlinOverride(ktClass, listOf(ktMember), scope, searchDeeply = true) { _, overrider -> val lightMethods = runReadAction { overrider.toPossiblyFakeLightMethods().distinctBy { it.unwrapped } } lightMethods.all { processor(it) } } } fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> { return when (val element = method.unwrapped) { is PsiMethod -> element.findDeepestSuperMethods().toList() is KtCallableDeclaration -> { val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptyList() descriptor.getDeepestSuperDeclarations(false).mapNotNull { it.source.getPsi() ?: DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it) } } else -> emptyList() } } fun findSuperDescriptors(declaration: KtDeclaration, descriptor: DeclarationDescriptor): Sequence<DeclarationDescriptor> { val sequenceOfExpectedDescriptor = declaration.takeIf { it.hasActualModifier() } ?.resolveToExpectedDescriptorIfPossible() ?.let { sequenceOf(it) } .orEmpty() val superDescriptors = findSuperDescriptors(descriptor) return if (superDescriptors == null) sequenceOfExpectedDescriptor else superDescriptors + sequenceOfExpectedDescriptor } private fun findSuperDescriptors(descriptor: DeclarationDescriptor): Sequence<DeclarationDescriptor>? { val superDescriptors: Collection<DeclarationDescriptor> = when (descriptor) { is ClassDescriptor -> { val supertypes = descriptor.typeConstructor.supertypes val superclasses = supertypes.mapNotNull { type -> type.constructor.declarationDescriptor as? ClassDescriptor } ContainerUtil.removeDuplicates(superclasses) superclasses } is CallableMemberDescriptor -> descriptor.getDirectlyOverriddenDeclarations() else -> return null } return superDescriptors.asSequence().filterNot { it is ClassDescriptor && KotlinBuiltIns.isAny(it) } } fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> { return when (val element = method.unwrapped) { is PsiMethod -> element.findSuperMethods().toList() is KtCallableDeclaration -> { val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptyList() descriptor.getDirectlyOverriddenDeclarations().mapNotNull { it.source.getPsi() ?: DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it) } } else -> emptyList() } } fun findOverridingMethodsInKotlin( parentClass: PsiClass, baseElement: PsiNamedElement, parameters: OverridingMethodsSearch.SearchParameters, consumer: Processor<in PsiMethod>, ): Boolean = ClassInheritorsSearch.search(parentClass, parameters.scope, true).forEach(Processor { inheritor: PsiClass -> val found = runReadAction { findOverridingMethod(inheritor, baseElement) } found == null || (consumer.process(found) && parameters.isCheckDeep) }) private fun findOverridingMethod(inheritor: PsiClass, baseElement: PsiNamedElement): PsiMethod? { // Leave Java classes search to JavaOverridingMethodsSearcher if (inheritor !is KtLightClass) return null val name = baseElement.name val methodsByName = inheritor.findMethodsByName(name, false) for (lightMethodCandidate in methodsByName) { val candidateDescriptor = (lightMethodCandidate as? KtLightMethod)?.kotlinOrigin?.unsafeResolveToDescriptor() ?: continue if (candidateDescriptor !is CallableMemberDescriptor) continue val overriddenDescriptors = candidateDescriptor.getDirectlyOverriddenDeclarations() for (candidateSuper in overriddenDescriptors) { val candidateDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(candidateSuper) if (candidateDeclaration == baseElement) { return lightMethodCandidate } } } return null }
apache-2.0
e672e3922659bbc1a31a3fc35a3f018a
46.259887
158
0.748117
5.648211
false
false
false
false
vovagrechka/fucking-everything
pieces/pieces-100/src/main/java/pieces100/Spaghetti.kt
1
8589
package pieces100 import vgrechka.* import kotlin.reflect.KClass import kotlin.reflect.full.cast import kotlin.reflect.full.isSubclassOf // TODO:vgrechka Dynamic flow of taint class Spaghetti { val noisy = false val dishStack = mutableListOf<Dish>() fun dumpDishCreationStacks() { for ((index, dish) in dishStack.withIndex()) { clog() clog("**************************************************************") clog("DISH $index OF ${dishStack.size}") clog("**************************************************************") dish.creationStackCapture.printStackTrace(System.out) } } fun topDish() = when { dishStack.isEmpty() -> null else -> dishStack.last() } fun <T : Any> maybePluck(type: KClass<T>): T? { for (i in dishStack.lastIndex downTo 0) { dishStack[i].maybePluck(type)?.let { return it } } return null } fun <T : Any> maybePluckWithTag(type: KClass<T>, tag: String): T? { for (i in dishStack.lastIndex downTo 0) { dishStack[i].maybePluckWithTag(type, tag)?.let { return it } } return null } fun <T : Any> get_checkingSingleInThatDish(type: KClass<T>, tag: String? = null): T = bang(maybeGet_checkingSingleInThatDish(type, tag)) fun <T : Any> get_checkingSingleInWholeStack(type: KClass<T>, tag: String? = null): T = bang(maybeGet_checkingSingleInWholeStack(type, tag)) fun <T : Any> maybeGet_checkingSingleInWholeStack(type: KClass<T>, tag: String? = null): T? { var foundShit: T? = null for (i in dishStack.lastIndex downTo 0) { val shit = when { tag == null -> dishStack[i].maybeGet_checkingSingle(type) else -> dishStack[i].maybeGetWithTag_checkingSingle(type, tag) } if (shit != null) { if (foundShit != null) bitch("No more than single piece of that shit in the stack, please") foundShit = shit } } return foundShit } fun <T : Any> maybeGetFirst(type: KClass<T>): T? { for (i in dishStack.lastIndex downTo 0) { dishStack[i].maybeGetFirst(type)?.let { return it } } return null } fun <T : Any> maybeGet_checkingSingleInThatDish(type: KClass<T>, tag: String? = null): T? { for (i in dishStack.lastIndex downTo 0) { val shit = when { tag == null -> dishStack[i].maybeGet_checkingSingle(type) else -> dishStack[i].maybeGetWithTag_checkingSingle(type, tag) } shit?.let { return it } } return null } fun <T : Any> maybeGetFirstWithTag(type: KClass<T>, tag: String): T? { for (i in dishStack.lastIndex downTo 0) { dishStack[i].maybeGetFirstWithTag(type, tag)?.let { return it } } return null } class Dish : WithDebugId { override val debugId = Debug.nextDebugId(this) val creationStackCapture = StackCaptureException("Creating ${simpleClassName(this)}") val content = mutableListOf<TaintedShit>() fun <T : Any> getSingle(type: KClass<T>): T = getSingle(type, {true}, "any") fun <T : Any> getSingleWithTag(type: KClass<T>, tag: String): T = getSingle(type, {it.tag == tag}, "tag = $tag") fun <T : Any> maybeGet_checkingSingle(type: KClass<T>): T? = maybeGet_checkingSingle(type, {true}, "any") fun <T : Any> maybeGetFirst(type: KClass<T>): T? = maybeGetFirst(type, {true}, "any") fun <T : Any> maybeGetWithTag_checkingSingle(type: KClass<T>, tag: String): T? = maybeGet_checkingSingle(type, {it.tag == tag}, "tag = $tag") fun <T : Any> maybeGetFirstWithTag(type: KClass<T>, tag: String): T? = maybeGetFirst(type, {it.tag == tag}, "tag = $tag") fun <T : Any> getAll(type: KClass<T>, predicate: (TaintedShit) -> Boolean): List<T> = content .filter {type.java.isAssignableFrom(it.shit::class.java) && predicate(it)} .map {it.shit.cast(type)} fun <T : Any> getSingle(type: KClass<T>, predicate: (TaintedShit) -> Boolean, english: String): T { val xs = getAll(type, predicate) if (xs.isEmpty()) bitch("No such shit in our dish: type = ${type.java.name}; $english") if (xs.size > 1) bitch("Too many shit in our dish (expected 1, got ${xs.size}): type = ${type.java.name}; $english") return xs.first() } fun <T : Any> maybeGet_checkingSingle(type: KClass<T>, predicate: (TaintedShit) -> Boolean, english: String): T? { val xs = getAll(type, predicate) if (xs.isEmpty()) return null if (xs.size > 1) bitch("Too many shit in our dish (expected 1, got ${xs.size}): type = ${type.java.name}; $english") return xs.first() } fun <T : Any> maybeGetFirst(type: KClass<T>, predicate: (TaintedShit) -> Boolean, english: String): T? { val xs = getAll(type, predicate) if (xs.isEmpty()) return null return xs.first() } fun <T : Any> maybePluck(type: KClass<T>): T? { val index = content.indexOfFirstOrNull {it.shit::class.isSubclassOf(type)} ?: return null return type.cast(content.removeAt(index).shit) } fun <T : Any> maybePluckWithTag(type: KClass<T>, tag: String): T? { val index = content.indexOfFirstOrNull {it.shit::class.isSubclassOf(type) && it.tag == tag} ?: return null return type.cast(content.removeAt(index).shit) } } object Tag { val namedLeafOf_prefix by myName() } companion object { val the by requestOrThreadScoped {Spaghetti()} } } class TaintedShit( val shit: Any, val tag: String? ) fun <T : Any> spaghetto(shit: T, tag: String? = null) = shit.putIntoSpaghetti_ifDishExists(tag) fun <T : Any> T.putIntoSpaghetti_ifDishExists(tag: String? = null): T { val dish = Spaghetti.the.topDish() ?: return this dish.content += TaintedShit(this, tag) return this } fun <T : Any> T.putIntoSpaghetti_ifDishExists_taggingFrom(other: Any): T { val dish = Spaghetti.the.topDish() ?: return this dish.content.filter {it.shit === other}.forEach { this.putIntoSpaghetti_ifDishExists(it.tag) } return this } fun <T : Any> T.putIntoSpaghetti_requiringNotAlreadyInStack(tag: String? = null): T { val dish = Spaghetti.the.topDish() ?: bitch("I want a spaghetti dish") val existing = when { tag == null -> Spaghetti.the.maybeGetFirst(this::class) else -> Spaghetti.the.maybeGetFirstWithTag(this::class, tag) } if (existing != null) bitch("Shit is already in a dish") dish.content += TaintedShit(this, tag) return this } fun <T : Any> T.putIntoSpaghetti_requiringNotAlreadyInDish(tag: String? = null): T { val dish = Spaghetti.the.topDish() ?: bitch("I want a spaghetti dish") val existing = when { tag == null -> dish.maybeGetFirst(this::class) else -> dish.maybeGetFirstWithTag(this::class, tag) } if (existing != null) bitch("Shit is already in a dish") dish.content += TaintedShit(this, tag) return this } fun <T> withNewSpaghettiDish(main: () -> T, before: () -> Unit = {}, tieKnots: (Spaghetti.Dish) -> Unit = {}): T { val dish = beginSpaghettiDish() try { before() val res = main() tieKnots(dish) return res } finally { endSpaghettiDish() } } fun beginSpaghettiDish(): Spaghetti.Dish { val dish = Spaghetti.Dish() Spaghetti.the.dishStack.add(dish) if (Spaghetti.the.noisy) { clogStackTrace(dish.creationStackCapture, "***** Put ${dish.debugId} onto stack") } return dish } fun endSpaghettiDish() { Spaghetti.the.dishStack.let { it.removeAt(it.lastIndex) } } fun beginSpaghettiDishWithNamedLeafPrefix(clazz: KClass<out Any>) { beginSpaghettiDish() "${clazz.simpleName}__".putIntoSpaghetti_ifDishExists(Spaghetti.Tag.namedLeafOf_prefix) }
apache-2.0
be8268aed2a94c1e09602c6d2fb2ad82
29.895683
122
0.564559
3.586221
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/content/custom/options/PersistentContentCustomLayoutOptions.kt
2
2980
package com.intellij.ui.content.custom.options import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.util.NlsSafe import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import java.util.* abstract class PersistentContentCustomLayoutOptions(private val content: Content, private val selectedOptionKey: String) : CustomContentLayoutOptions { companion object { const val HIDE_OPTION_KEY = "Hidden" //TODO check that none of the options have the same key } override fun select(option: CustomContentLayoutOption) { option as? PersistentContentCustomLayoutOption ?: throw IllegalStateException( "Option is not a ${PersistentContentCustomLayoutOption::class.java.name}") doSelect(option) saveOption(option.getOptionKey()) } override fun isSelected(option: CustomContentLayoutOption): Boolean = option.isSelected override fun restore() { val defaultOption = getDefaultOption() if (!defaultOption.isSelected) { select(defaultOption) } } fun isContentVisible(): Boolean { return content.isValid && (content.manager?.getIndexOfContent(content) ?: -1) != -1 } fun getCurrentOption(): PersistentContentCustomLayoutOption? { val currentOptionKey = getCurrentOptionKey() if (currentOptionKey == HIDE_OPTION_KEY) { return null } return getPersistentOptions().first { it.getOptionKey() == getCurrentOptionKey() } } protected abstract fun doSelect(option: CustomContentLayoutOption) protected abstract fun getDefaultOptionKey(): String private fun getCurrentOptionKey() = PropertiesComponent.getInstance().getValue(selectedOptionKey) ?: getDefaultOptionKey() private fun getDefaultOption() = getPersistentOptions().first { it.getOptionKey() == getDefaultOptionKey() } private fun saveOption(optionKey: @NlsSafe String) { PropertiesComponent.getInstance().setValue(selectedOptionKey, optionKey) } private fun getPersistentOptions() = availableOptions.filterIsInstance<PersistentContentCustomLayoutOption>() override fun onHide() { saveOption(HIDE_OPTION_KEY) } override fun getDisplayName(): String = content.displayName override fun isHidden(): Boolean = getCurrentOption() == null override fun isHideOptionVisible(): Boolean { if (isHidden) { return true } val contentManager: ContentManager = content.manager ?: return false return contentManager.contents.size > 1 } } abstract class PersistentContentCustomLayoutOption(private val options: PersistentContentCustomLayoutOptions) : CustomContentLayoutOption { override fun isEnabled(): Boolean = true override fun isSelected(): Boolean = options.isContentVisible() && isThisOptionSelected() override fun select() = options.select(this) abstract fun getOptionKey(): @NlsSafe String private fun isThisOptionSelected(): Boolean = this == options.getCurrentOption() }
apache-2.0
f9033c60fed008ba5a9e7ed17dcd3ced
33.662791
139
0.748322
4.933775
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/configuration/klib/KotlinNativeLibraryNameUtilTest.kt
1
3799
// 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.configuration.klib import junit.framework.TestCase import org.jetbrains.kotlin.idea.gradle.configuration.klib.* import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.isGradleLibraryName import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.parseIDELibraryName import org.jetbrains.kotlin.idea.gradleJava.configuration.klib.ideName import java.io.File class KotlinNativeLibraryNameUtilTest : TestCase() { fun testBuildIDELibraryName() { assertEquals( "Kotlin/Native 1.5.20 - foo | [(a, b)]", KlibInfo( path = File(""), sourcePaths = emptyList(), libraryName = "foo", isCommonized = true, isStdlib = false, isFromNativeDistribution = true, targets = KlibInfo.NativeTargets.CommonizerIdentity("(a, b)") ).ideName("1.5.20") ) assertEquals( "foo | [(a, b)]", KlibInfo( path = File(""), sourcePaths = emptyList(), libraryName = "foo", isCommonized = true, isStdlib = false, isFromNativeDistribution = false, targets = KlibInfo.NativeTargets.CommonizerIdentity("(a, b)") ).ideName(null) ) assertEquals( "Kotlin/Native 1.5.20 - foo", KlibInfo( path = File(""), sourcePaths = emptyList(), libraryName = "foo", isCommonized = false, isStdlib = true, isFromNativeDistribution = true, targets = KlibInfo.NativeTargets.CommonizerIdentity("(a, b)") ).ideName("1.5.20") ) assertEquals( "Kotlin/Native foo", KlibInfo( path = File(""), sourcePaths = emptyList(), libraryName = "foo", isCommonized = true, isStdlib = false, isFromNativeDistribution = true, targets = null ).ideName(null) ) } fun testParseIDELibraryName() { assertEquals( Triple("1.3.60", "stdlib", null), parseIDELibraryName("Kotlin/Native 1.3.60 - stdlib") ) assertEquals( Triple("1.3.60-eap-23", "Accelerate", "macos_x64"), parseIDELibraryName("Kotlin/Native 1.3.60-eap-23 - Accelerate [macos_x64]") ) assertEquals( Triple("1.3.60-eap-23", "Accelerate", "ios_arm32, ios_arm64, ios_x64"), parseIDELibraryName("Kotlin/Native 1.3.60-eap-23 - Accelerate [ios_arm32, ios_arm64, ios_x64]") ) assertEquals( Triple("1.3.60-eap-23", "Accelerate", "ios_arm32, ios_arm64(*), ios_x64"), parseIDELibraryName("Kotlin/Native 1.3.60-eap-23 - Accelerate [ios_arm32, ios_arm64(*), ios_x64]") ) assertNull(parseIDELibraryName("Kotlin/Native - something unexpected")) assertNull(parseIDELibraryName("foo.klib")) assertNull(parseIDELibraryName("Gradle: some:third-party-library:1.2")) } fun testIsGradleLibraryName() { assertFalse(isGradleLibraryName("Kotlin/Native 1.3.60 - stdlib")) assertFalse(isGradleLibraryName("Kotlin/Native 1.3.60-eap-23 - Accelerate [macos_x64]")) assertFalse(isGradleLibraryName("foo.klib")) assertTrue(isGradleLibraryName("Gradle: some:third-party-library:1.2")) } }
apache-2.0
ecc736a24abb6c76d41ef8fa2a164caf
34.839623
158
0.575415
4.453693
false
true
false
false