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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ingokegel/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageSnapshotImpl.kt | 1 | 28593 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.trace
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.ExceptionUtil
import com.intellij.util.ObjectUtils
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.containers.getDiff
import com.intellij.workspaceModel.storage.impl.exceptions.AddDiffException
import com.intellij.workspaceModel.storage.impl.exceptions.PersistentIdAlreadyExistsException
import com.intellij.workspaceModel.storage.impl.external.EmptyExternalEntityMapping
import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl
import com.intellij.workspaceModel.storage.impl.external.MutableExternalEntityMappingImpl
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex.MutableVirtualFileIndex.Companion.VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY
import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex
import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
internal data class EntityReferenceImpl<E : WorkspaceEntity>(private val id: EntityId) : EntityReference<E>() {
override fun resolve(storage: EntityStorage): E? {
@Suppress("UNCHECKED_CAST")
return (storage as AbstractEntityStorage).entityDataById(id)?.createEntity(storage) as? E
}
}
internal class EntityStorageSnapshotImpl constructor(
override val entitiesByType: ImmutableEntitiesBarrel,
override val refs: RefsTable,
override val indexes: StorageIndexes
) : EntityStorageSnapshot, AbstractEntityStorage() {
// This cache should not be transferred to other versions of storage
private val persistentIdCache = ConcurrentHashMap<PersistentEntityId<*>, WorkspaceEntity>()
@Suppress("UNCHECKED_CAST")
override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? {
val entity = persistentIdCache.getOrPut(id) { super.resolve(id) ?: NULL_ENTITY }
return if (entity !== NULL_ENTITY) entity as E else null
}
override fun toSnapshot(): EntityStorageSnapshot = this
companion object {
private val NULL_ENTITY = ObjectUtils.sentinel("null entity", WorkspaceEntity::class.java)
val EMPTY = EntityStorageSnapshotImpl(ImmutableEntitiesBarrel.EMPTY, RefsTable(), StorageIndexes.EMPTY)
}
}
internal class MutableEntityStorageImpl(
override val entitiesByType: MutableEntitiesBarrel,
override val refs: MutableRefsTable,
override val indexes: MutableStorageIndexes,
@Volatile
private var trackStackTrace: Boolean = false
) : MutableEntityStorage, AbstractEntityStorage() {
internal val changeLog = WorkspaceBuilderChangeLog()
// Temporal solution for accessing error in deft project.
internal var throwExceptionOnError = false
internal fun incModificationCount() {
this.changeLog.modificationCount++
}
override val modificationCount: Long
get() = this.changeLog.modificationCount
private val writingFlag = AtomicBoolean()
@Volatile
private var stackTrace: String? = null
@Volatile
private var threadId: Long? = null
@Volatile
private var threadName: String? = null
// --------------- Replace By Source stuff -----------
internal var useNewRbs = Registry.`is`("ide.workspace.model.rbs.as.tree", true)
@TestOnly
internal var keepLastRbsEngine = false
internal var engine: ReplaceBySourceOperation? = null
@set:TestOnly
internal var upgradeEngine: ((ReplaceBySourceOperation) -> Unit)? = null
// --------------- Replace By Source stuff -----------
override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> {
@Suppress("UNCHECKED_CAST")
return entitiesByType[entityClass.toClassId()]?.all()?.map { it.wrapAsModifiable(this) } as? Sequence<E> ?: emptySequence()
}
override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>,
entityClass: Class<R>): Sequence<R> {
val classId = entityClass.toClassId()
@Suppress("UNCHECKED_CAST")
return indexes.softLinks.getIdsByEntry(id).asSequence()
.filter { it.clazz == classId }
.map { entityDataByIdOrDie(it).wrapAsModifiable(this) as R }
}
override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? {
val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null
val entityData: WorkspaceEntityData<WorkspaceEntity> = entityDataById(entityIds) as? WorkspaceEntityData<WorkspaceEntity> ?: return null
@Suppress("UNCHECKED_CAST")
return entityData.wrapAsModifiable(this) as E?
}
// Do not remove cast to Class<out TypedEntity>. kotlin fails without it
@Suppress("USELESS_CAST")
override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> {
return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source ->
indexes.entitySourceIndex
.getIdsByEntry(source)!!.map {
val entityDataById: WorkspaceEntityData<WorkspaceEntity> = this.entityDataById(it) as? WorkspaceEntityData<WorkspaceEntity>
?: run {
reportErrorAndAttachStorage("Cannot find an entity by id $it",
this@MutableEntityStorageImpl)
error("Cannot find an entity by id $it")
}
entityDataById.wrapAsModifiable(this)
}
.groupBy { (it as WorkspaceEntityBase).getEntityInterface() }
}
}
override fun <T : WorkspaceEntity> addEntity(entity: T) {
try {
lockWrite()
entity as ModifiableWorkspaceEntityBase<T>
entity.applyToBuilder(this)
}
finally {
unlockWrite()
}
}
// This should be removed or not extracted into the interface
fun <T : WorkspaceEntity, D: ModifiableWorkspaceEntityBase<T>> putEntity(entity: D) {
try {
lockWrite()
val newEntityData = entity.getEntityData()
// Check for persistent id uniqueness
assertUniquePersistentId(newEntityData)
entitiesByType.add(newEntityData, entity.getEntityClass().toClassId())
// Add the change to changelog
createAddEvent(newEntityData)
// Update indexes
indexes.entityAdded(newEntityData)
}
finally {
unlockWrite()
}
}
private fun <T : WorkspaceEntity> assertUniquePersistentId(pEntityData: WorkspaceEntityData<T>) {
pEntityData.persistentId()?.let { persistentId ->
val ids = indexes.persistentIdIndex.getIdsByEntry(persistentId)
if (ids != null) {
// Oh, oh. This persistent id exists already
// Fallback strategy: remove existing entity with all it's references
val existingEntityData = entityDataByIdOrDie(ids)
val existingEntity = existingEntityData.createEntity(this)
removeEntity(existingEntity)
LOG.error(
"""
addEntity: persistent id already exists. Replacing entity with the new one.
Persistent id: $persistentId
Existing entity data: $existingEntityData
New entity data: $pEntityData
Broken consistency: $brokenConsistency
""".trimIndent(), PersistentIdAlreadyExistsException(persistentId)
)
if (throwExceptionOnError) {
throw PersistentIdAlreadyExistsException(persistentId)
}
}
}
}
@Suppress("UNCHECKED_CAST")
override fun <M : ModifiableWorkspaceEntity<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T {
try {
lockWrite()
val entityId = (e as WorkspaceEntityBase).id
val originalEntityData = this.getOriginalEntityData(entityId) as WorkspaceEntityData<T>
// Get entity data that will be modified
val copiedData = entitiesByType.getEntityDataForModification(entityId) as WorkspaceEntityData<T>
val modifiableEntity = copiedData.wrapAsModifiable(this) as M
val beforePersistentId = if (e is WorkspaceEntityWithPersistentId) e.persistentId else null
val originalParents = this.getOriginalParents(entityId.asChild())
val beforeParents = this.refs.getParentRefsOfChild(entityId.asChild())
val beforeChildren = this.refs.getChildrenRefsOfParentBy(entityId.asParent()).flatMap { (key, value) -> value.map { key to it } }
// Execute modification code
(modifiableEntity as ModifiableWorkspaceEntityBase<*>).allowModifications {
modifiableEntity.change()
}
// Check for persistent id uniqueness
if (beforePersistentId != null) {
val newPersistentId = copiedData.persistentId()
if (newPersistentId != null) {
val ids = indexes.persistentIdIndex.getIdsByEntry(newPersistentId)
if (beforePersistentId != newPersistentId && ids != null) {
// Oh, oh. This persistent id exists already.
// Remove an existing entity and replace it with the new one.
val existingEntityData = entityDataByIdOrDie(ids)
val existingEntity = existingEntityData.createEntity(this)
removeEntity(existingEntity)
LOG.error("""
modifyEntity: persistent id already exists. Replacing entity with the new one.
Old entity: $existingEntityData
Persistent id: $copiedData
Broken consistency: $brokenConsistency
""".trimIndent(), PersistentIdAlreadyExistsException(newPersistentId))
if (throwExceptionOnError) {
throw PersistentIdAlreadyExistsException(newPersistentId)
}
}
}
else {
LOG.error("Persistent id expected for entity: $copiedData")
}
}
if (!modifiableEntity.changedProperty.contains("entitySource") || modifiableEntity.changedProperty.size > 1) {
// Add an entry to changelog
addReplaceEvent(this, entityId, beforeChildren, beforeParents, copiedData, originalEntityData, originalParents)
}
if (modifiableEntity.changedProperty.contains("entitySource")) {
updateEntitySource(entityId, originalEntityData, copiedData)
}
val updatedEntity = copiedData.createEntity(this)
this.indexes.updatePersistentIdIndexes(this, updatedEntity, beforePersistentId, copiedData, modifiableEntity)
return updatedEntity
}
finally {
unlockWrite()
}
}
private fun <T : WorkspaceEntity> updateEntitySource(entityId: EntityId, originalEntityData: WorkspaceEntityData<T>,
copiedEntityData: WorkspaceEntityData<T>) {
val newSource = copiedEntityData.entitySource
val originalSource = this.getOriginalSourceFromChangelog(entityId) ?: originalEntityData.entitySource
this.changeLog.addChangeSourceEvent(entityId, copiedEntityData, originalSource)
indexes.entitySourceIndex.index(entityId, newSource)
newSource.virtualFileUrl?.let { indexes.virtualFileIndex.index(entityId, VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY, it) }
}
override fun removeEntity(e: WorkspaceEntity): Boolean {
try {
lockWrite()
LOG.debug { "Removing ${e.javaClass}..." }
e as WorkspaceEntityBase
return removeEntityByEntityId(e.id)
// NB: This method is called from `createEntity` inside persistent id checking. It's possible that after the method execution
// the store is in inconsistent state, so we can't call assertConsistency here.
}
finally {
unlockWrite()
}
}
private fun getRbsEngine(): ReplaceBySourceOperation {
if (useNewRbs) {
return ReplaceBySourceAsTree()
}
else {
return ReplaceBySourceAsGraph()
}
}
/**
* TODO Spacial cases: when source filter returns true for all entity sources.
*/
override fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: EntityStorage) {
try {
lockWrite()
replaceWith as AbstractEntityStorage
val rbsEngine = getRbsEngine()
if (keepLastRbsEngine) {
engine = rbsEngine
}
upgradeEngine?.let { it(rbsEngine) }
rbsEngine.replace(this, replaceWith, sourceFilter)
}
finally {
unlockWrite()
}
}
override fun collectChanges(original: EntityStorage): Map<Class<*>, List<EntityChange<*>>> {
try {
lockWrite()
val originalImpl = original as AbstractEntityStorage
val res = HashMap<Class<*>, MutableList<EntityChange<*>>>()
for ((entityId, change) in this.changeLog.changeLog) {
when (change) {
is ChangeEntry.AddEntity -> {
val addedEntity = change.entityData.createEntity(this) as WorkspaceEntityBase
res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Added(addedEntity))
}
is ChangeEntry.RemoveEntity -> {
val removedData = originalImpl.entityDataById(change.id) ?: continue
val removedEntity = removedData.createEntity(originalImpl) as WorkspaceEntityBase
res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Removed(removedEntity))
}
is ChangeEntry.ReplaceEntity -> {
@Suppress("DuplicatedCode")
val oldData = originalImpl.entityDataById(entityId) ?: continue
val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase
val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase
res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }
.add(EntityChange.Replaced(replacedData, replaceToData))
}
is ChangeEntry.ChangeEntitySource -> {
val oldData = originalImpl.entityDataById(entityId) ?: continue
val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase
val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase
res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }
.add(EntityChange.Replaced(replacedData, replaceToData))
}
is ChangeEntry.ReplaceAndChangeSource -> {
val oldData = originalImpl.entityDataById(entityId) ?: continue
val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase
val replaceToData = change.dataChange.newData.createEntity(this) as WorkspaceEntityBase
res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }
.add(EntityChange.Replaced(replacedData, replaceToData))
}
}
}
return res
}
finally {
unlockWrite()
}
}
override fun toSnapshot(): EntityStorageSnapshot {
val newEntities = entitiesByType.toImmutable()
val newRefs = refs.toImmutable()
val newIndexes = indexes.toImmutable()
return EntityStorageSnapshotImpl(newEntities, newRefs, newIndexes)
}
override fun isEmpty(): Boolean = this.changeLog.changeLog.isEmpty()
override fun addDiff(diff: MutableEntityStorage) {
try {
lockWrite()
diff as MutableEntityStorageImpl
applyDiffProtection(diff, "addDiff")
AddDiffOperation(this, diff).addDiff()
}
finally {
unlockWrite()
}
}
@Suppress("UNCHECKED_CAST")
override fun <T> getMutableExternalMapping(identifier: String): MutableExternalEntityMapping<T> {
try {
lockWrite()
val mapping = indexes.externalMappings.computeIfAbsent(
identifier) { MutableExternalEntityMappingImpl<T>() } as MutableExternalEntityMappingImpl<T>
mapping.setTypedEntityStorage(this)
return mapping
}
finally {
unlockWrite()
}
}
override fun getMutableVirtualFileUrlIndex(): MutableVirtualFileUrlIndex {
try {
lockWrite()
val virtualFileIndex = indexes.virtualFileIndex
virtualFileIndex.setTypedEntityStorage(this)
return virtualFileIndex
}
finally {
unlockWrite()
}
}
internal fun addDiffAndReport(message: String, left: EntityStorage?, right: EntityStorage) {
reportConsistencyIssue(message, AddDiffException(message), null, left, right, this)
}
private fun applyDiffProtection(diff: AbstractEntityStorage, method: String) {
LOG.trace { "Applying $method. Builder: $diff" }
if (diff.storageIsAlreadyApplied) {
LOG.error("Builder is already applied.\n Info: \n${diff.applyInfo}")
}
else {
diff.storageIsAlreadyApplied = true
var info = "Applying builder using $method. Previous stack trace >>>>\n"
if (LOG.isTraceEnabled) {
val currentStackTrace = ExceptionUtil.currentStackTrace()
info += "\n$currentStackTrace"
}
info += "<<<<"
diff.applyInfo = info
}
}
// modificationCount is not incremented
internal fun removeEntityByEntityId(idx: EntityId, entityFilter: (EntityId) -> Boolean = { true }): Boolean {
val accumulator: MutableSet<EntityId> = mutableSetOf(idx)
if (!entitiesByType.exists(idx)) {
return false
}
accumulateEntitiesToRemove(idx, accumulator, entityFilter)
val originals = accumulator.associateWith {
this.getOriginalEntityData(it) as WorkspaceEntityData<WorkspaceEntity> to this.getOriginalParents(it.asChild())
}
for (id in accumulator) {
val entityData = entityDataById(id)
if (entityData is SoftLinkable) indexes.removeFromSoftLinksIndex(entityData)
entitiesByType.remove(id.arrayId, id.clazz)
}
// Update index
// Please don't join it with the previous loop
for (id in accumulator) indexes.entityRemoved(id)
accumulator.forEach {
LOG.debug { "Cascade removing: ${ClassToIntConverter.INSTANCE.getClassOrDie(it.clazz)}-${it.arrayId}" }
this.changeLog.addRemoveEvent(it, originals[it]!!.first, originals[it]!!.second)
}
return true
}
private fun lockWrite() {
val currentThread = Thread.currentThread()
if (writingFlag.getAndSet(true)) {
if (threadId != null && threadId != currentThread.id) {
LOG.error("""
Concurrent write to builder from the following threads
First Thread: $threadName
Second Thread: ${currentThread.name}
Previous stack trace: $stackTrace
""".trimIndent())
trackStackTrace = true
}
}
if (trackStackTrace || LOG.isTraceEnabled) {
stackTrace = ExceptionUtil.currentStackTrace()
}
threadId = currentThread.id
threadName = currentThread.name
}
private fun unlockWrite() {
writingFlag.set(false)
stackTrace = null
threadId = null
threadName = null
}
internal fun <T : WorkspaceEntity> createAddEvent(pEntityData: WorkspaceEntityData<T>) {
val entityId = pEntityData.createEntityId()
this.changeLog.addAddEvent(entityId, pEntityData)
}
/**
* Cleanup references and accumulate hard linked entities in [accumulator]
*/
private fun accumulateEntitiesToRemove(id: EntityId, accumulator: MutableSet<EntityId>, entityFilter: (EntityId) -> Boolean) {
val children = refs.getChildrenRefsOfParentBy(id.asParent())
for ((connectionId, childrenIds) in children) {
for (childId in childrenIds) {
if (childId.id in accumulator) continue
if (!entityFilter(childId.id)) continue
accumulator.add(childId.id)
accumulateEntitiesToRemove(childId.id, accumulator, entityFilter)
refs.removeRefsByParent(connectionId, id.asParent())
}
}
val parents = refs.getParentRefsOfChild(id.asChild())
for ((connectionId, parent) in parents) {
refs.removeParentToChildRef(connectionId, parent, id.asChild())
}
}
companion object {
private val LOG = logger<MutableEntityStorageImpl>()
fun create(): MutableEntityStorageImpl {
return from(EntityStorageSnapshotImpl.EMPTY)
}
fun from(storage: EntityStorage): MutableEntityStorageImpl {
storage as AbstractEntityStorage
val newBuilder = when (storage) {
is EntityStorageSnapshotImpl -> {
val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType)
val copiedRefs = MutableRefsTable.from(storage.refs)
val copiedIndex = storage.indexes.toMutable()
MutableEntityStorageImpl(copiedBarrel, copiedRefs, copiedIndex)
}
is MutableEntityStorageImpl -> {
val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType.toImmutable())
val copiedRefs = MutableRefsTable.from(storage.refs.toImmutable())
val copiedIndexes = storage.indexes.toMutable()
MutableEntityStorageImpl(copiedBarrel, copiedRefs, copiedIndexes, storage.trackStackTrace)
}
}
LOG.trace { "Create new builder $newBuilder from $storage.\n${currentStackTrace(10)}" }
return newBuilder
}
internal fun addReplaceEvent(
builder: MutableEntityStorageImpl,
entityId: EntityId,
beforeChildren: List<Pair<ConnectionId, ChildEntityId>>,
beforeParents: Map<ConnectionId, ParentEntityId>,
copiedData: WorkspaceEntityData<out WorkspaceEntity>,
originalEntity: WorkspaceEntityData<out WorkspaceEntity>,
originalParents: Map<ConnectionId, ParentEntityId>,
) {
val parents = builder.refs.getParentRefsOfChild(entityId.asChild())
val unmappedChildren = builder.refs.getChildrenRefsOfParentBy(entityId.asParent())
val children = unmappedChildren.flatMap { (key, value) -> value.map { key to it } }
// Collect children changes
val beforeChildrenSet = beforeChildren.toMutableSet()
val (removedChildren, addedChildren) = getDiff(beforeChildrenSet, children)
// Collect parent changes
val parentsMapRes: MutableMap<ConnectionId, ParentEntityId?> = beforeParents.toMutableMap()
for ((connectionId, parentId) in parents) {
val existingParent = parentsMapRes[connectionId]
if (existingParent != null) {
if (existingParent == parentId) {
parentsMapRes.remove(connectionId, parentId)
}
else {
parentsMapRes[connectionId] = parentId
}
}
else {
parentsMapRes[connectionId] = parentId
}
}
val removedKeys = beforeParents.keys - parents.keys
removedKeys.forEach { parentsMapRes[it] = null }
builder.changeLog.addReplaceEvent(entityId, copiedData, originalEntity, originalParents, addedChildren, removedChildren, parentsMapRes)
}
}
}
internal sealed class AbstractEntityStorage : EntityStorage {
internal abstract val entitiesByType: EntitiesBarrel
internal abstract val refs: AbstractRefsTable
internal abstract val indexes: StorageIndexes
internal var brokenConsistency: Boolean = false
internal var storageIsAlreadyApplied = false
internal var applyInfo: String? = null
override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> {
@Suppress("UNCHECKED_CAST")
return entitiesByType[entityClass.toClassId()]?.all()?.map { it.createEntity(this) } as? Sequence<E> ?: emptySequence()
}
override fun <E : WorkspaceEntity> entitiesAmount(entityClass: Class<E>): Int {
return entitiesByType[entityClass.toClassId()]?.size() ?: 0
}
internal fun entityDataById(id: EntityId): WorkspaceEntityData<out WorkspaceEntity>? = entitiesByType[id.clazz]?.get(id.arrayId)
internal fun entityDataByIdOrDie(id: EntityId): WorkspaceEntityData<out WorkspaceEntity> {
val entityFamily = entitiesByType[id.clazz] ?: error(
"Entity family doesn't exist or has no entities: ${id.clazz.findWorkspaceEntity()}")
return entityFamily.get(id.arrayId) ?: error("Cannot find an entity by id $id")
}
override fun <E : WorkspaceEntity, R : WorkspaceEntity> referrers(e: E, entityClass: KClass<R>,
property: KProperty1<R, EntityReference<E>>): Sequence<R> {
TODO()
//return entities(entityClass.java).filter { property.get(it).resolve(this) == e }
}
override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>,
entityClass: Class<R>): Sequence<R> {
val classId = entityClass.toClassId()
@Suppress("UNCHECKED_CAST")
return indexes.softLinks.getIdsByEntry(id).asSequence()
.filter { it.clazz == classId }
.map { entityDataByIdOrDie(it).createEntity(this) as R }
}
override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? {
val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null
@Suppress("UNCHECKED_CAST")
return entityDataById(entityIds)?.createEntity(this) as E?
}
// Do not remove cast to Class<out TypedEntity>. kotlin fails without it
@Suppress("USELESS_CAST")
override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> {
return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source ->
indexes.entitySourceIndex
.getIdsByEntry(source)!!.map {
this.entityDataById(it)?.createEntity(this) ?: run {
reportErrorAndAttachStorage("Cannot find an entity by id $it", this@AbstractEntityStorage)
error("Cannot find an entity by id $it")
}
}
.groupBy { (it as WorkspaceEntityBase).getEntityInterface() }
}
}
@Suppress("UNCHECKED_CAST")
override fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T> {
val index = indexes.externalMappings[identifier] as? ExternalEntityMappingImpl<T>
if (index == null) return EmptyExternalEntityMapping as ExternalEntityMapping<T>
index.setTypedEntityStorage(this)
return index
}
override fun getVirtualFileUrlIndex(): VirtualFileUrlIndex {
indexes.virtualFileIndex.setTypedEntityStorage(this)
return indexes.virtualFileIndex
}
override fun <E : WorkspaceEntity> createReference(e: E): EntityReference<E> = EntityReferenceImpl((e as WorkspaceEntityBase).id)
internal fun assertConsistencyInStrictMode(message: String,
sourceFilter: ((EntitySource) -> Boolean)?,
left: EntityStorage?,
right: EntityStorage?) {
if (ConsistencyCheckingMode.current != ConsistencyCheckingMode.DISABLED) {
try {
this.assertConsistency()
}
catch (e: Throwable) {
brokenConsistency = true
val storage = if (this is MutableEntityStorage) this.toSnapshot() as AbstractEntityStorage else this
val report = { reportConsistencyIssue(message, e, sourceFilter, left, right, storage) }
if (ConsistencyCheckingMode.current == ConsistencyCheckingMode.ASYNCHRONOUS) {
consistencyChecker.execute(report)
}
else {
report()
}
}
}
}
companion object {
val LOG = logger<AbstractEntityStorage>()
private val consistencyChecker = AppExecutorUtil.createBoundedApplicationPoolExecutor("Check workspace model consistency", 1)
}
}
/** This function exposes `brokenConsistency` property to the outside and should be removed along with the property itself */
val EntityStorage.isConsistent: Boolean
get() = !(this as AbstractEntityStorage).brokenConsistency
| apache-2.0 | 58ccc06bfe7d991b37318b362c21613a | 39.271831 | 149 | 0.687511 | 5.071479 | false | false | false | false |
mdaniel/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/ThreadRunInspection.kt | 9 | 1596 | // 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.codeInspection
import com.intellij.psi.PsiElementVisitor
import com.intellij.uast.UastHintedVisitorAdapter
import com.siyeh.InspectionGadgetsBundle
import com.siyeh.ig.callMatcher.CallMatcher
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.USuperExpression
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
class ThreadRunInspection : AbstractBaseUastLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = UastHintedVisitorAdapter.create(
holder.file.language, ThreadRunVisitor(holder), arrayOf(UCallExpression::class.java), true)
override fun getID(): String = "CallToThreadRun"
inner class ThreadRunVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
if (!THREAD_RUN.uCallMatches(node)) return true
if (node.receiver is USuperExpression) return true
val toHighlight = node.methodIdentifier?.sourcePsi ?: return true
val message = InspectionGadgetsBundle.message("thread.run.problem.descriptor")
holder.registerProblem(toHighlight, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceMethodCallFix("start"))
return true
}
}
companion object {
private val THREAD_RUN = CallMatcher.instanceCall("java.lang.Thread", "run").parameterCount(0)
}
} | apache-2.0 | 59173f48d0e7ae5e6863221d03d51565 | 48.90625 | 158 | 0.795739 | 4.851064 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notificationslist/notification/NotificationsListFragment.kt | 1 | 2862 | package io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification
import android.os.Bundle
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.adapters.NotificationsListAdapter
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.BaseNotificationsListFragment
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi
import kotlinx.android.synthetic.main.activity_notifications_list.*
import javax.inject.Inject
class NotificationsListFragment : BaseNotificationsListFragment() {
companion object {
const val DATA_FRAGMENT_TAG = "NOTIFICATIONS_LIST_ACTIVITY"
fun newInstance() = NotificationsListFragment()
}
@Inject override lateinit var linkHandler: WykopLinkHandlerApi
@Inject override lateinit var notificationAdapter: NotificationsListAdapter
@Inject lateinit var presenter: NotificationsListPresenter
private lateinit var entryFragmentData: DataFragment<PagedDataModel<List<Notification>>>
override fun loadMore() = presenter.loadData(false)
override fun onRefresh() = presenter.loadData(true)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
presenter.subscribe(this)
super.onCreate(savedInstanceState)
entryFragmentData = supportFragmentManager.getDataFragmentInstance(DATA_FRAGMENT_TAG)
if (entryFragmentData.data != null && entryFragmentData.data!!.model.isNotEmpty()) {
loadingView?.isVisible = false
presenter.page = entryFragmentData.data!!.page
notificationAdapter.addData(entryFragmentData.data!!.model, true)
notificationAdapter.disableLoading()
} else {
loadingView?.isVisible = true
onRefresh()
}
}
override fun markAsRead() = presenter.readNotifications()
override fun onDestroy() {
presenter.unsubscribe()
super.onDestroy()
}
override fun onPause() {
super.onPause()
if (isRemoving) supportFragmentManager.removeDataFragment(entryFragmentData)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
entryFragmentData.data = PagedDataModel(presenter.page, notificationAdapter.data)
}
override fun showTooManyNotifications() {
// Do nothing
}
} | mit | 9db2a14fb93b0f3ffc367e4b16ccb800 | 39.9 | 102 | 0.7645 | 5.461832 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/entity/Order.kt | 1 | 11474 | package alraune.entity
import alraune.*
import aplight.GelFill
import aplight.GelNew
import aplight.GelPropMetaVisitor
import aplight.GelPropValueVisitor
import bolone.ReminderJobParams
import bolone.bucketNameForSite
import bolone.sion
import pieces100.*
import vgrechka.*
import java.sql.Timestamp
@LightEntity(table = "orders") @GelFill @GelPropMetaVisitor
class Order : WithId, WithOptimisticVersion {
init {ver(sion.OrderFields__1)}
init {ver(sion.OrderFileFields__1)}
override var id by notNull<Long>()
override var optimisticVersion by notNull<String>()
var uuid by notNull<String>()
@LeJson(withTypeInfo = true) var data by notNull<Order.Data>()
var state by notNull<Order.State>()
var deadline by notNull<Timestamp>()
object Meta
class R1(val bucket: Order.Bucket, val file: Order.File)
fun maybeBucketAndFileByID(fileID: Long): R1? {
for (bucket in data.buckets)
for (file in bucket.files)
if (file.id == fileID)
return R1(bucket, file)
return null
}
fun bucketAndFileByID(fileID: Long) = maybeBucketAndFileByID(fileID)
?: bitch("No such freaking file: id = $id")
fun fileByID(id: Long) = bucketAndFileByID(id).file
@GelNew class UserBiddingState {
var user by notNull<User>()
var state by notNull<Order.UserBiddingState.State>()
var money by maybeNull<Int>()
var lastMoneyBeforeCancelation by maybeNull<Int>()
enum class State {OnlyCommented, Offered, Canceled}
}
@GelNew class UserNote {
object __version1
var uuid by notNull<String>()
var optimisticVersion by notNull<String>()
var time by notNull<Timestamp>()
var text by notNull<String>()
}
@GelFill @GelPropMetaVisitor
class Data {
var id by notNull<Long>()
var createdAt by notNull<Timestamp>()
var updatedAt by notNull<Timestamp>()
var uuid by notNull<String>()
var buckets by notNull<MutableList<Order.Bucket>>()
var email by notNull<String>()
var contactName by notNull<String>()
var phone by notNull<String>()
var documentType by notNull<Order.DocumentType>()
var documentTitle by notNull<String>()
var documentDetails by notNull<String>()
var documentCategory by notNull<String>()
var numPages by notNull<Int>()
var numSources by notNull<Int>()
var adminNotes by notNull<String>() // TODO:vgrechka Kill
var lastOperationID by notNull<Long>()
var biddingActions by notNull<MutableList<Order.BiddingAction>>()
var lockID by notNull<Long>()
var testCounter: Int = 0
var approvalTaskID: Long? = null
var debugTitleAddendum: String? = null
var lastRejectedByOperationID: Long? = null
var rejectionReason: String? = null
var wasRejectionReason: String? = null
var bidding: Order.Bidding? = null
var assignment: Order.Assignment? = null
var debug_shouldBeDeletedAsPartOfCleaningShitFromPreviousTests: Boolean = false
var lastSentForApprovalByOperationID: Long? = null
}
@GelNew class Bucket {
var name by notNull<String>()
var files by notNull<MutableList<Order.File>>()
var notes by notNull<MutableList<Order.UserNote>>()
fun fileByID(id: Long) = files.find {it.id == id} ?: bitch()
}
@GelNew @GelPropValueVisitor
class Bidding {
var minWriterMoney by place<Int>()
var maxWriterMoney by place<Int>()
var closed: Boolean = false
var workDeadlineShownToWritersDuringBidding by place<Timestamp>()
var closeBiddingReminder by place<ReminderJobParams>()
}
@GelNew @GelPropValueVisitor
class Assignment {
var customerPaysMoney by place<Int>()
var writerReceivesMoney by place<Int>()
var writerPledgeHours by place<Int>()
var customerFacingPledgeHours by place<Int>()
var writer by place<User>()
var nudgePaymentReminder by place<ReminderJobParams>()
}
enum class State(override val title: String) : Titled {
CustomerDraft(t(en = "TOTE", ru = "Черновик")),
LookingForWriters(t(en = "TOTE", ru = "Ищем писателей")),
WaitingPayment(t(en = "TOTE", ru = "Ждем оплату")),
WaitingAdminApproval(t(en = "TOTE", ru = "Ждем одобрение админом")),
ReturnedToCustomerForFixing(t(en = "TOTE", ru = "Заказчик фиксит заявку")),
WorkInProgress(t("TOTE", "Писатель вкалывает"))
}
enum class DocumentType(override val title: String) : Titled {
Abstract(t(en = "TOTE", ru = "Реферат")),
Course(t(en = "TOTE", ru = "Курсовая работа")),
Graduation(t(en = "TOTE", ru = "Дипломная работа")),
Lab(t(en = "TOTE", ru = "Лабораторная работа")),
Test(t(en = "TOTE", ru = "Контрольная работа")),
RGR(t(en = "TOTE", ru = "РГР")),
Drawing(t(en = "TOTE", ru = "Чертеж")),
Dissertation(t(en = "TOTE", ru = "Диссертация")),
Essay(t(en = "TOTE", ru = "Эссе (сочинение)")),
Practice(t(en = "TOTE", ru = "Отчет по практике")),
Other(t(en = "TOTE", ru = "Другое"))
}
@GelNew @GelFill @GelPropMetaVisitor
class File {
var id by notNull<Long>()
var createdAt by notNull<Timestamp>()
var updatedAt by notNull<Timestamp>()
var uuid by notNull<String>()
var state by notNull<Order.File.State>()
var title by notNull<String>()
var details by notNull<String>()
@AdminField var adminNotes: String? = null
var toBeFixed: Order.ToBeFixed? = null
var resource by notNull<Order.Resource>()
var copiedFrom: Order.File.Reference? = null
enum class State(override val title: String) : Titled {
Unknown(t(en = "Unknown", ru = "ХЗ"))
}
@GelNew class Reference {
var bucketName by place<String>()
var fileID by place<Long>()
fun display() = bucketName + " " + AlText.numString(fileID)
}
}
@GelNew @GelFill @GelPropMetaVisitor
class Resource : EncryptedDownloadableResource {
override var name by notNull<String>()
override var size by notNull<Int>()
override var downloadUrl by notNull<String>()
override var secretKeyBase64 by notNull<String>()
}
@GelNew open class Operation : OperationData() {
var orderBefore by maybeNull<Order>()
var orderAfter by notNull<Order>()
@GelNew class Generic : Order.Operation()
@GelNew class Create : Order.Operation()
@GelNew class UpdateParams : Order.Operation()
@GelNew class Customer_SendForApproval : Order.Operation()
@GelNew class Admin_Reject : Order.Operation()
@GelNew class Admin_MoveToBidding : Order.Operation()
@GelNew class Admin_UpdateBiddingParams : Order.Operation()
@GelNew class Admin_CloseBidding : Order.Operation()
@GelNew class Admin_UpdateAssignmentParams : Order.Operation()
@GelNew class Bid : Order.Operation()
@GelNew class CancelBid : Order.Operation()
@GelNew class CommentDuringBidding : Order.Operation()
@GelNew class CreateNote : Order.Operation()
@GelNew class UpdateNote : Order.Operation()
@GelNew class DeleteNote : Order.Operation()
@GelNew class FuckAround : Order.Operation()
@GelNew open class File : Order.Operation() {
var file by notNull<Order.File>()
@GelNew class Create : Order.Operation.File()
@GelNew class Update : Order.Operation.File()
@GelNew class Delete : Order.Operation.File()
}
}
@GelNew @GelFill @GelPropMetaVisitor
class ToBeFixed {
var what by notNull<String>()
@AdminField var detailsForAdmin by notNull<String>()
}
@GelNew class BiddingAction {
var kind by notNull<Order.BiddingAction.Kind>()
var userId by notNull<Long>()
var commentRecipientId by maybeNull<Long>()
var time by notNull<Timestamp>()
var money by maybeNull<Int>()
var comment by notNull<String>()
var isCancelation: Boolean = false
enum class Kind {Bid, Cancel, Comment}
}
fun bucket(name: String) = data.buckets.find {it.name == name} ?: bitch("name = $name")
fun toHandle() = OrderHandle(id, data.lockID, this.optimisticVersion)
fun assignedTestWriter(): TestUser = maybeAssignedTestWriter()!!
fun maybeAssignedTestWriter() = data.assignment?.writer?.data?.testUser
fun computeUserBiddingState(user: User): UserBiddingState? {
val relatedActions = data.biddingActions.filter {it.userId == user.id || it.commentRecipientId == user.id}
if (relatedActions.isEmpty()) return null
val state = UserBiddingState()
state.user = user
state.money = null
state.lastMoneyBeforeCancelation = null
for ((actionIndex, action) in relatedActions.withIndex()) {
exhaustive=when (action.kind) {
BiddingAction.Kind.Bid -> {
state.state = UserBiddingState.State.Offered
state.money = action.money
state.lastMoneyBeforeCancelation = null
}
BiddingAction.Kind.Cancel -> {
state.state = UserBiddingState.State.Canceled
state.lastMoneyBeforeCancelation = state.money ?: wtf()
state.money = null
}
BiddingAction.Kind.Comment -> {
cond(actionIndex == 0) {
state.state = UserBiddingState.State.OnlyCommented
}
}
}
}
return state
}
fun computeAllUserBiddingStates(): List<UserBiddingState> {
val list = mutableListOf<UserBiddingState>()
for (bidAction in data.biddingActions) {
var user = rctx0.al.dbCache.user(bidAction.userId)
if (user.kind == AlUserKind.Admin)
user = rctx0.al.dbCache.user(bidAction.commentRecipientId!!)
if (!list.any {it.user.id == user.id}) {
list += computeUserBiddingState(user)!!
}
}
return list
}
fun viewBucket(): Bucket {
return bucket(rctx0.al.viewBucketIfAdmin() ?: bucketNameForSite(rctx0.al.site()))
}
// fun postRequestBucket(): Bucket {
// rctx.checkPostRequest()
// return bucket(
// if (isAdmin()) rctx.postRequestBucket
// else rctx.site().name)
// }
}
// TODO:vgrechka Generate this shit
val Order.Meta.entityClass get() = Order::class
val Order.Meta.table get() = dbTableName(this.entityClass)
val Order.Meta.id get() = Order::id.name
val Order.Meta.optimisticVersion get() = Order::optimisticVersion.name
val Order.Meta.uuid get() = Order::uuid.name
val Order.Meta.state get() = Order::state.name
val Order.Meta.deadline get() = Order::deadline.name
val Order.Meta.data get() = Order::data.name
interface DeleteOperationMarker
| apache-2.0 | a2ee607d8a4057d3a62dbcd9002da6d3 | 33.75 | 114 | 0.627676 | 4.162292 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/LambdaToAnonymousFunctionIntention.kt | 1 | 8501 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveInsideParentheses
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.error.ErrorType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class LambdaToAnonymousFunctionIntention : SelfTargetingIntention<KtLambdaExpression>(
KtLambdaExpression::class.java,
KotlinBundle.lazyMessage("convert.to.anonymous.function"),
KotlinBundle.lazyMessage("convert.lambda.expression.to.anonymous.function")
), LowPriorityAction {
override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean {
val argument = element.getStrictParentOfType<KtValueArgument>()
val call = argument?.getStrictParentOfType<KtCallElement>()
if (call?.getStrictParentOfType<KtFunction>()?.hasModifier(KtTokens.INLINE_KEYWORD) == true) return false
val context = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
if (call?.getResolvedCall(context)?.getParameterForArgument(argument)?.type?.isSuspendFunctionType == true) return false
val descriptor = context[
BindingContext.DECLARATION_TO_DESCRIPTOR,
element.functionLiteral,
] as? AnonymousFunctionDescriptor ?: return false
if (descriptor.valueParameters.any { it.isDestructuring() || it.type is ErrorType }) return false
val lastElement = element.functionLiteral.arrow ?: element.functionLiteral.lBrace
return caretOffset <= lastElement.endOffset
}
override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
val functionDescriptor = element.functionLiteral.descriptor as? AnonymousFunctionDescriptor ?: return
val resultingFunction = convertLambdaToFunction(element, functionDescriptor) ?: return
val argument = when (val parent = resultingFunction.parent) {
is KtLambdaArgument -> parent
is KtLabeledExpression -> parent.replace(resultingFunction).parent as? KtLambdaArgument
else -> null
} ?: return
argument.moveInsideParentheses(argument.analyze(BodyResolveMode.PARTIAL))
}
private fun ValueParameterDescriptor.isDestructuring() = this is ValueParameterDescriptorImpl.WithDestructuringDeclaration
companion object {
fun convertLambdaToFunction(
lambda: KtLambdaExpression,
functionDescriptor: FunctionDescriptor,
functionName: String = "",
functionParameterName: (ValueParameterDescriptor, Int) -> String = { parameter, _ ->
val parameterName = parameter.name
if (parameterName.isSpecial) "_" else parameterName.asString().quoteIfNeeded()
},
typeParameters: Map<TypeConstructor, KotlinType> = emptyMap(),
replaceElement: (KtNamedFunction) -> KtExpression = { lambda.replaced(it) }
): KtExpression? {
val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES
val functionLiteral = lambda.functionLiteral
val bodyExpression = functionLiteral.bodyExpression ?: return null
val context = bodyExpression.analyze(BodyResolveMode.PARTIAL)
val functionLiteralDescriptor by lazy { functionLiteral.descriptor }
bodyExpression.collectDescendantsOfType<KtReturnExpression>().forEach {
val targetDescriptor = it.getTargetFunctionDescriptor(context)
if (targetDescriptor == functionDescriptor || targetDescriptor == functionLiteralDescriptor) it.labeledExpression?.delete()
}
val psiFactory = KtPsiFactory(lambda)
val function = psiFactory.createFunction(
KtPsiFactory.CallableBuilder(KtPsiFactory.CallableBuilder.Target.FUNCTION).apply {
typeParams()
functionDescriptor.extensionReceiverParameter?.type?.let {
receiver(typeSourceCode.renderType(it))
}
name(functionName)
for ((index, parameter) in functionDescriptor.valueParameters.withIndex()) {
val type = parameter.type.let { if (it.isFlexible()) it.makeNotNullable() else it }
val renderType = typeSourceCode.renderType(
getTypeFromParameters(type, typeParameters)
)
val parameterName = functionParameterName(parameter, index)
param(parameterName, renderType)
}
functionDescriptor.returnType?.takeIf { !it.isUnit() }?.let {
val lastStatement = bodyExpression.statements.lastOrNull()
if (lastStatement != null && lastStatement !is KtReturnExpression) {
val foldableReturns = BranchedFoldingUtils.getFoldableReturns(lastStatement)
if (foldableReturns.isNullOrEmpty()) {
lastStatement.replace(psiFactory.createExpressionByPattern("return $0", lastStatement))
}
}
val renderType = typeSourceCode.renderType(
getTypeFromParameters(it, typeParameters)
)
returnType(renderType)
} ?: noReturnType()
blockBody(" " + bodyExpression.text)
}.asString()
)
val result = wrapInParenthesisIfNeeded(replaceElement(function), psiFactory)
ShortenReferences.DEFAULT.process(result)
return result
}
private fun getTypeFromParameters(
type: KotlinType,
typeParameters: Map<TypeConstructor, KotlinType>
): KotlinType {
if (type.isTypeParameter())
return typeParameters[type.constructor] ?: type
return type
}
private fun wrapInParenthesisIfNeeded(expression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = expression.parent ?: return expression
val grandParent = parent.parent ?: return expression
if (parent is KtCallExpression && grandParent !is KtParenthesizedExpression && grandParent !is KtDeclaration) {
return expression.replaced(psiFactory.createExpressionByPattern("($0)", expression))
}
return expression
}
}
}
| apache-2.0 | ba6ef4a385878432cad0701272f3536e | 51.801242 | 158 | 0.695918 | 5.969803 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/mapMin3.kt | 9 | 390 | // API_VERSION: 1.3
// WITH_STDLIB
// PROBLEM: none
data class OrderItem(val name: String, val price: Double, val count: Int)
fun main() {
val order = listOf<OrderItem>(
OrderItem("Cake", price = 10.0, count = 1),
OrderItem("Coffee", price = 2.5, count = 3),
OrderItem("Tea", price = 1.5, count = 2)
)
val min = order.map<caret> { it.price }.min()!!
} | apache-2.0 | fa1088ee277b0b8b0781e758f91c6893 | 25.066667 | 73 | 0.584615 | 3.22314 | false | false | false | false |
oldcwj/iPing | commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context.kt | 1 | 11447 | package com.simplemobiletools.commons.extensions
import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Looper
import android.provider.BaseColumns
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.TextView
import android.widget.Toast
import com.github.ajalt.reprint.core.Reprint
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.views.*
import kotlinx.android.synthetic.main.dialog_title.view.*
import java.io.File
fun Context.isOnMainThread() = Looper.myLooper() == Looper.getMainLooper()
fun Context.getSharedPrefs() = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
fun Context.isAndroidFour() = Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH
fun Context.isKitkatPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
fun Context.isLollipopPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
fun Context.isMarshmallowPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
fun Context.isNougatPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
fun Context.updateTextColors(viewGroup: ViewGroup, tmpTextColor: Int = 0, tmpAccentColor: Int = 0) {
val textColor = if (tmpTextColor == 0) baseConfig.textColor else tmpTextColor
val accentColor = if (tmpAccentColor == 0) baseConfig.primaryColor else tmpAccentColor
val backgroundColor = baseConfig.backgroundColor
val cnt = viewGroup.childCount
(0 until cnt)
.map { viewGroup.getChildAt(it) }
.forEach {
when (it) {
is MyTextView -> it.setColors(textColor, accentColor, backgroundColor)
is MyAppCompatSpinner -> it.setColors(textColor, accentColor, backgroundColor)
is MySwitchCompat -> it.setColors(textColor, accentColor, backgroundColor)
is MyCompatRadioButton -> it.setColors(textColor, accentColor, backgroundColor)
is MyAppCompatCheckbox -> it.setColors(textColor, accentColor, backgroundColor)
is MyEditText -> it.setColors(textColor, accentColor, backgroundColor)
is MyFloatingActionButton -> it.setColors(textColor, accentColor, backgroundColor)
is MySeekBar -> it.setColors(textColor, accentColor, backgroundColor)
is MyButton -> it.setColors(textColor, accentColor, backgroundColor)
is ViewGroup -> updateTextColors(it, textColor, accentColor)
}
}
}
fun Context.getLinkTextColor(): Int {
return if (baseConfig.primaryColor == resources.getColor(R.color.color_primary)) {
baseConfig.primaryColor
} else {
baseConfig.textColor
}
}
fun Context.setupDialogStuff(view: View, dialog: AlertDialog, titleId: Int = 0) {
if (view is ViewGroup)
updateTextColors(view)
else if (view is MyTextView) {
view.setTextColor(baseConfig.textColor)
}
var title: TextView? = null
if (titleId != 0) {
title = LayoutInflater.from(this).inflate(R.layout.dialog_title, null) as TextView
title.dialog_title_textview.apply {
setText(titleId)
setTextColor(baseConfig.textColor)
}
}
dialog.apply {
setView(view)
requestWindowFeature(Window.FEATURE_NO_TITLE)
setCustomTitle(title)
setCanceledOnTouchOutside(true)
show()
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(baseConfig.textColor)
getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(baseConfig.textColor)
getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(baseConfig.textColor)
window.setBackgroundDrawable(ColorDrawable(baseConfig.backgroundColor))
}
}
fun Context.toast(id: Int, length: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, id, length).show()
}
fun Context.toast(msg: String, length: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, msg, length).show()
}
val Context.baseConfig: BaseConfig get() = BaseConfig.newInstance(this)
val Context.sdCardPath: String get() = baseConfig.sdCardPath
val Context.internalStoragePath: String get() = baseConfig.internalStoragePath
fun Context.isThankYouInstalled(): Boolean {
return try {
packageManager.getPackageInfo("com.simplemobiletools.thankyou", 0)
true
} catch (e: Exception) {
false
}
}
@SuppressLint("InlinedApi", "NewApi")
fun Context.isFingerPrintSensorAvailable() = isMarshmallowPlus() && Reprint.isHardwarePresent()
fun Context.getLatestMediaId(uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI): Long {
val projection = arrayOf(BaseColumns._ID)
val sortOrder = "${MediaStore.Images.ImageColumns.DATE_TAKEN} DESC"
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, null, null, sortOrder)
if (cursor?.moveToFirst() == true) {
return cursor.getLongValue(BaseColumns._ID)
}
} finally {
cursor?.close()
}
return 0
}
// some helper functions were taken from https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
@SuppressLint("NewApi")
fun Context.getRealPathFromURI(uri: Uri): String? {
if (uri.scheme == "file") {
return uri.path
}
if (isKitkatPlus()) {
if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
if (id.areDigitsOnly()) {
val newUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id.toLong())
val path = getDataColumn(newUri)
if (path != null) {
return path
}
}
} else if (isExternalStorageDocument(uri)) {
val documentId = DocumentsContract.getDocumentId(uri)
val parts = documentId.split(":")
if (parts[0].equals("primary", true)) {
return "${Environment.getExternalStorageDirectory().absolutePath}/${parts[1]}"
}
} else if (isMediaDocument(uri)) {
val documentId = DocumentsContract.getDocumentId(uri)
val split = documentId.split(":").dropLastWhile { it.isEmpty() }.toTypedArray()
val type = split[0]
val contentUri = when (type) {
"video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
"audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
else -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
val path = getDataColumn(contentUri, selection, selectionArgs)
if (path != null) {
return path
}
}
}
return getDataColumn(uri)
}
fun Context.getDataColumn(uri: Uri, selection: String? = null, selectionArgs: Array<String>? = null): String? {
var cursor: Cursor? = null
try {
val projection = arrayOf(MediaStore.Images.Media.DATA)
cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
if (cursor?.moveToFirst() == true) {
return cursor.getStringValue(MediaStore.Images.Media.DATA)
}
} catch (e: Exception) {
} finally {
cursor?.close()
}
return null
}
private fun isMediaDocument(uri: Uri) = uri.authority == "com.android.providers.media.documents"
private fun isDownloadsDocument(uri: Uri) = uri.authority == "com.android.providers.downloads.documents"
private fun isExternalStorageDocument(uri: Uri) = uri.authority == "com.android.externalstorage.documents"
fun Context.hasPermission(permId: Int) = ContextCompat.checkSelfPermission(this, getPermissionString(permId)) == PackageManager.PERMISSION_GRANTED
fun Context.getPermissionString(id: Int) = when (id) {
PERMISSION_READ_STORAGE -> Manifest.permission.READ_EXTERNAL_STORAGE
PERMISSION_WRITE_STORAGE -> Manifest.permission.WRITE_EXTERNAL_STORAGE
PERMISSION_CAMERA -> Manifest.permission.CAMERA
PERMISSION_RECORD_AUDIO -> Manifest.permission.RECORD_AUDIO
PERMISSION_READ_CONTACTS -> Manifest.permission.READ_CONTACTS
PERMISSION_WRITE_CALENDAR -> Manifest.permission.WRITE_CALENDAR
else -> ""
}
fun Context.getFilePublicUri(file: File, applicationId: String): Uri {
// try getting a media content uri first, like content://media/external/images/media/438
// if media content uri is null, get our custom uri like content://com.simplemobiletools.gallery.provider/external_files/emulated/0/DCIM/IMG_20171104_233915.jpg
return getMediaContentUri(file.absolutePath) ?: FileProvider.getUriForFile(this, "$applicationId.provider", file)
}
fun Context.getMediaContentUri(path: String): Uri? {
val uri = when {
path.isImageFast() -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
path.isVideoFast() -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
else -> MediaStore.Files.getContentUri("external")
}
val projection = arrayOf(MediaStore.Images.Media._ID)
val selection = MediaStore.Images.Media.DATA + "= ?"
val selectionArgs = arrayOf(path)
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
if (cursor?.moveToFirst() == true) {
val id = cursor.getIntValue(MediaStore.Images.Media._ID).toString()
return Uri.withAppendedPath(uri, id)
}
} catch (e: Exception) {
} finally {
cursor?.close()
}
return null
}
fun Context.getFilenameFromUri(uri: Uri): String {
return if (uri.scheme == "file") {
File(uri.toString()).name
} else {
var name = getFilenameFromContentUri(uri) ?: ""
if (name.isEmpty()) {
name = uri.lastPathSegment ?: ""
}
name
}
}
fun Context.getMimeTypeFromUri(uri: Uri): String {
var mimetype = uri.path.getMimeTypeFromPath()
if (mimetype.isEmpty()) {
try {
mimetype = contentResolver.getType(uri)
} catch (e: IllegalStateException) {
}
}
return mimetype
}
fun Context.ensurePublicUri(uri: Uri, applicationId: String): Uri {
return if (uri.scheme == "content") {
uri
} else {
val file = File(uri.path)
getFilePublicUri(file, applicationId)
}
}
fun Context.getFilenameFromContentUri(uri: Uri): String? {
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, null, null, null, null)
if (cursor?.moveToFirst() == true) {
return cursor.getStringValue(OpenableColumns.DISPLAY_NAME)
}
} catch (e: Exception) {
} finally {
cursor?.close()
}
return ""
}
| gpl-3.0 | 585496717d4e1420122150e69e0f459d | 37.80339 | 164 | 0.678955 | 4.357442 | false | true | false | false |
androidx/androidx | compose/animation/animation-core/samples/src/main/java/androidx/compose/animation/core/samples/AnimatableSamples.kt | 3 | 9756 | /*
* 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.animation.core.samples
import androidx.annotation.Sampled
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationEndReason
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.core.exponentialDecay
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.splineBasedDecay
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.verticalDrag
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
@Sampled
@Composable
fun AnimatableAnimateToGenericsType() {
// Creates an `Animatable` to animate Offset and `remember` it.
val animatedOffset = remember { Animatable(Offset(0f, 0f), Offset.VectorConverter) }
Box(
Modifier.fillMaxSize().background(Color(0xffb99aff)).pointerInput(Unit) {
coroutineScope {
while (true) {
val offset = awaitPointerEventScope {
awaitFirstDown().position
}
// Launch a new coroutine for animation so the touch detection thread is not
// blocked.
launch {
// Animates to the pressed position, with the given animation spec.
animatedOffset.animateTo(
offset,
animationSpec = spring(stiffness = Spring.StiffnessLow)
)
}
}
}
}
) {
Text("Tap anywhere", Modifier.align(Alignment.Center))
Box(
Modifier
.offset {
// Use the animated offset as the offset of the Box.
IntOffset(
animatedOffset.value.x.roundToInt(),
animatedOffset.value.y.roundToInt()
)
}
.size(40.dp)
.background(Color(0xff3c1361), CircleShape)
)
}
}
@Sampled
fun AnimatableDecayAndAnimateToSample() {
/**
* In this example, we create a swipe-to-dismiss modifier that dismisses the child via a
* vertical swipe-up.
*/
fun Modifier.swipeToDismiss(): Modifier = composed {
// Creates a Float type `Animatable` and `remember`s it
val animatedOffsetY = remember { Animatable(0f) }
this.pointerInput(Unit) {
coroutineScope {
while (true) {
val pointerId = awaitPointerEventScope {
awaitFirstDown().id
}
val velocityTracker = VelocityTracker()
awaitPointerEventScope {
verticalDrag(pointerId) {
// Snaps the value by the amount of finger movement
launch {
animatedOffsetY.snapTo(
animatedOffsetY.value + it.positionChange().y
)
}
velocityTracker.addPosition(
it.uptimeMillis,
it.position
)
}
}
// At this point, drag has finished. Now we obtain the velocity at the end of
// the drag, and animate the offset with it as the starting velocity.
val velocity = velocityTracker.calculateVelocity().y
// The goal for the animation below is to animate the dismissal if the fling
// velocity is high enough. Otherwise, spring back.
launch {
// Checks where the animation will end using decay
val decay = splineBasedDecay<Float>(this@pointerInput)
// If the animation can naturally end outside of visual bounds, we will
// animate with decay.
if (decay.calculateTargetValue(
animatedOffsetY.value,
velocity
) < -size.height
) {
// (Optionally) updates lower bounds. This stops the animation as soon
// as bounds are reached.
animatedOffsetY.updateBounds(
lowerBound = -size.height.toFloat()
)
// Animate with the decay animation spec using the fling velocity
animatedOffsetY.animateDecay(velocity, decay)
} else {
// Not enough velocity to be dismissed, spring back to 0f
animatedOffsetY.animateTo(0f, initialVelocity = velocity)
}
}
}
}
}.offset { IntOffset(0, animatedOffsetY.value.roundToInt()) }
}
}
@Sampled
fun AnimatableAnimationResultSample() {
suspend fun CoroutineScope.animateBouncingOffBounds(
animatable: Animatable<Offset, *>,
flingVelocity: Offset,
parentSize: Size
) {
launch {
var startVelocity = flingVelocity
// Set bounds for the animation, so that when it reaches bounds it will stop
// immediately. We can then inspect the returned `AnimationResult` and decide whether
// we should start another animation.
animatable.updateBounds(Offset(0f, 0f), Offset(parentSize.width, parentSize.height))
do {
val result = animatable.animateDecay(startVelocity, exponentialDecay())
// Copy out the end velocity of the previous animation.
startVelocity = result.endState.velocity
// Negate the velocity for the dimension that hits the bounds, to create a
// bouncing off the bounds effect.
with(animatable) {
if (value.x == upperBound?.x || value.x == lowerBound?.x) {
// x dimension hits bounds
startVelocity = startVelocity.copy(x = -startVelocity.x)
}
if (value.y == upperBound?.y || value.y == lowerBound?.y) {
// y dimension hits bounds
startVelocity = startVelocity.copy(y = -startVelocity.y)
}
}
// Repeat the animation until the animation ends for reasons other than hitting
// bounds, e.g. if `stop()` is called, or preempted by another animation.
} while (result.endReason == AnimationEndReason.BoundReached)
}
}
}
@Sampled
fun AnimatableFadeIn() {
fun Modifier.fadeIn(): Modifier = composed {
// Creates an `Animatable` and remembers it.
val alphaAnimation = remember { Animatable(0f) }
// Launches a coroutine for the animation when entering the composition.
// Uses `alphaAnimation` as the subject so the job in `LaunchedEffect` will run only when
// `alphaAnimation` is created, which happens one time when the modifier enters
// composition.
LaunchedEffect(alphaAnimation) {
// Animates to 1f from 0f for the fade-in, and uses a 500ms tween animation.
alphaAnimation.animateTo(
targetValue = 1f,
// Default animationSpec uses [spring] animation, here we overwrite the default.
animationSpec = tween(500)
)
}
this.graphicsLayer(alpha = alphaAnimation.value)
}
}
| apache-2.0 | 3101c34c3bea22646b5cc266d57b88f7 | 43.144796 | 98 | 0.591533 | 5.426029 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/FabPrimaryTokens.kt | 3 | 1737 | /*
* 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.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object FabPrimaryTokens {
val ContainerColor = ColorSchemeKeyTokens.PrimaryContainer
val ContainerElevation = ElevationTokens.Level3
val ContainerHeight = 56.0.dp
val ContainerShape = ShapeKeyTokens.CornerLarge
val ContainerWidth = 56.0.dp
val FocusContainerElevation = ElevationTokens.Level3
val FocusIconColor = ColorSchemeKeyTokens.OnPrimaryContainer
val HoverContainerElevation = ElevationTokens.Level4
val HoverIconColor = ColorSchemeKeyTokens.OnPrimaryContainer
val IconColor = ColorSchemeKeyTokens.OnPrimaryContainer
val IconSize = 24.0.dp
val LoweredContainerElevation = ElevationTokens.Level1
val LoweredFocusContainerElevation = ElevationTokens.Level1
val LoweredHoverContainerElevation = ElevationTokens.Level2
val LoweredPressedContainerElevation = ElevationTokens.Level1
val PressedContainerElevation = ElevationTokens.Level3
val PressedIconColor = ColorSchemeKeyTokens.OnPrimaryContainer
} | apache-2.0 | bf2690f98d125ab137f43e5a088213b0 | 41.390244 | 75 | 0.785838 | 4.851955 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/TextDelegateTest.kt | 3 | 4145 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Density
import com.google.common.truth.Truth.assertThat
import org.mockito.kotlin.mock
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(InternalFoundationTextApi::class)
@RunWith(JUnit4::class)
class TextDelegateTest {
private val density = Density(density = 1f)
private val fontFamilyResolver = mock<FontFamily.Resolver>()
@Test
fun `constructor with default values`() {
val textDelegate = TextDelegate(
text = AnnotatedString(text = ""),
style = TextStyle.Default,
density = density,
fontFamilyResolver = fontFamilyResolver
)
assertThat(textDelegate.maxLines).isEqualTo(Int.MAX_VALUE)
assertThat(textDelegate.minLines).isEqualTo(DefaultMinLines)
assertThat(textDelegate.overflow).isEqualTo(TextOverflow.Clip)
}
@Test
fun `constructor with customized text(TextSpan)`() {
val text = AnnotatedString("Hello")
val textDelegate = TextDelegate(
text = text,
style = TextStyle.Default,
density = density,
fontFamilyResolver = fontFamilyResolver
)
assertThat(textDelegate.text).isEqualTo(text)
}
@Test
fun `constructor with customized maxLines`() {
val maxLines = 8
val textDelegate = TextDelegate(
text = AnnotatedString(text = ""),
style = TextStyle.Default,
maxLines = maxLines,
density = density,
fontFamilyResolver = fontFamilyResolver
)
assertThat(textDelegate.maxLines).isEqualTo(maxLines)
}
@Test
fun `constructor with customized minLines`() {
val minLines = 8
val textDelegate = TextDelegate(
text = AnnotatedString(text = ""),
style = TextStyle.Default,
minLines = minLines,
density = density,
fontFamilyResolver = fontFamilyResolver
)
assertThat(textDelegate.minLines).isEqualTo(minLines)
}
@Test
fun `constructor with customized overflow`() {
val overflow = TextOverflow.Ellipsis
val textDelegate = TextDelegate(
text = AnnotatedString(text = ""),
style = TextStyle.Default,
overflow = overflow,
density = density,
fontFamilyResolver = fontFamilyResolver
)
assertThat(textDelegate.overflow).isEqualTo(overflow)
}
@Test(expected = IllegalStateException::class)
fun `minIntrinsicWidth without layout assertion should fail`() {
val textDelegate = TextDelegate(
text = AnnotatedString(text = ""),
style = TextStyle.Default,
density = density,
fontFamilyResolver = fontFamilyResolver
)
textDelegate.minIntrinsicWidth
}
@Test(expected = IllegalStateException::class)
fun `maxIntrinsicWidth without layout assertion should fail`() {
val textDelegate = TextDelegate(
text = AnnotatedString(text = ""),
style = TextStyle.Default,
density = density,
fontFamilyResolver = fontFamilyResolver
)
textDelegate.maxIntrinsicWidth
}
}
| apache-2.0 | 8f07b3bccf24aaea561043103f6b0786 | 30.641221 | 75 | 0.656936 | 5.220403 | false | true | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ColorPickerDialog.kt | 1 | 9275 | package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.graphics.Color
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isQPlus
import com.simplemobiletools.commons.views.ColorPickerSquare
import kotlinx.android.synthetic.main.dialog_color_picker.view.*
import java.util.*
private const val RECENT_COLORS_NUMBER = 5
// forked from https://github.com/yukuku/ambilwarna
class ColorPickerDialog(
val activity: Activity,
color: Int,
val removeDimmedBackground: Boolean = false,
showUseDefaultButton: Boolean = false,
val currentColorCallback: ((color: Int) -> Unit)? = null,
val callback: (wasPositivePressed: Boolean, color: Int) -> Unit
) {
var viewHue: View
var viewSatVal: ColorPickerSquare
var viewCursor: ImageView
var viewNewColor: ImageView
var viewTarget: ImageView
var newHexField: EditText
var viewContainer: ViewGroup
private val baseConfig = activity.baseConfig
private val currentColorHsv = FloatArray(3)
private val backgroundColor = baseConfig.backgroundColor
private var isHueBeingDragged = false
private var wasDimmedBackgroundRemoved = false
private var dialog: AlertDialog? = null
init {
Color.colorToHSV(color, currentColorHsv)
val view = activity.layoutInflater.inflate(R.layout.dialog_color_picker, null).apply {
if (isQPlus()) {
isForceDarkAllowed = false
}
viewHue = color_picker_hue
viewSatVal = color_picker_square
viewCursor = color_picker_hue_cursor
viewNewColor = color_picker_new_color
viewTarget = color_picker_cursor
viewContainer = color_picker_holder
newHexField = color_picker_new_hex
viewSatVal.setHue(getHue())
viewNewColor.setFillWithStroke(getColor(), backgroundColor)
color_picker_old_color.setFillWithStroke(color, backgroundColor)
val hexCode = getHexCode(color)
color_picker_old_hex.text = "#$hexCode"
color_picker_old_hex.setOnLongClickListener {
activity.copyToClipboard(hexCode)
true
}
newHexField.setText(hexCode)
setupRecentColors()
}
viewHue.setOnTouchListener(OnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
isHueBeingDragged = true
}
if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) {
var y = event.y
if (y < 0f)
y = 0f
if (y > viewHue.measuredHeight) {
y = viewHue.measuredHeight - 0.001f // to avoid jumping the cursor from bottom to top.
}
var hue = 360f - 360f / viewHue.measuredHeight * y
if (hue == 360f)
hue = 0f
currentColorHsv[0] = hue
updateHue()
newHexField.setText(getHexCode(getColor()))
if (event.action == MotionEvent.ACTION_UP) {
isHueBeingDragged = false
}
return@OnTouchListener true
}
false
})
viewSatVal.setOnTouchListener(OnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) {
var x = event.x
var y = event.y
if (x < 0f)
x = 0f
if (x > viewSatVal.measuredWidth)
x = viewSatVal.measuredWidth.toFloat()
if (y < 0f)
y = 0f
if (y > viewSatVal.measuredHeight)
y = viewSatVal.measuredHeight.toFloat()
currentColorHsv[1] = 1f / viewSatVal.measuredWidth * x
currentColorHsv[2] = 1f - 1f / viewSatVal.measuredHeight * y
moveColorPicker()
viewNewColor.setFillWithStroke(getColor(), backgroundColor)
newHexField.setText(getHexCode(getColor()))
return@OnTouchListener true
}
false
})
newHexField.onTextChangeListener {
if (it.length == 6 && !isHueBeingDragged) {
try {
val newColor = Color.parseColor("#$it")
Color.colorToHSV(newColor, currentColorHsv)
updateHue()
moveColorPicker()
} catch (ignored: Exception) {
}
}
}
val textColor = activity.getProperTextColor()
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { dialog, which -> confirmNewColor() }
.setNegativeButton(R.string.cancel) { dialog, which -> dialogDismissed() }
.setOnCancelListener { dialogDismissed() }
if (showUseDefaultButton) {
builder.setNeutralButton(R.string.use_default) { dialog, which -> useDefault() }
}
builder.apply {
activity.setupDialogStuff(view, this) { alertDialog ->
dialog = alertDialog
view.color_picker_arrow.applyColorFilter(textColor)
view.color_picker_hex_arrow.applyColorFilter(textColor)
viewCursor.applyColorFilter(textColor)
}
}
view.onGlobalLayout {
moveHuePicker()
moveColorPicker()
}
}
private fun View.setupRecentColors() {
val recentColors = baseConfig.colorPickerRecentColors
if (recentColors.isNotEmpty()) {
recent_colors.beVisible()
val squareSize = context.resources.getDimensionPixelSize(R.dimen.colorpicker_hue_width)
recentColors.take(RECENT_COLORS_NUMBER).forEach { recentColor ->
val recentColorView = ImageView(context)
recentColorView.id = View.generateViewId()
recentColorView.layoutParams = ViewGroup.LayoutParams(squareSize, squareSize)
recentColorView.setFillWithStroke(recentColor, backgroundColor)
recentColorView.setOnClickListener { newHexField.setText(getHexCode(recentColor)) }
recent_colors.addView(recentColorView)
recent_colors_flow.addView(recentColorView)
}
}
}
private fun dialogDismissed() {
callback(false, 0)
}
private fun confirmNewColor() {
val hexValue = newHexField.value
val newColor = if (hexValue.length == 6) {
Color.parseColor("#$hexValue")
} else {
getColor()
}
addRecentColor(newColor)
callback(true, newColor)
}
private fun useDefault() {
val defaultColor = baseConfig.defaultNavigationBarColor
addRecentColor(defaultColor)
callback(true, defaultColor)
}
private fun addRecentColor(color: Int) {
var recentColors = baseConfig.colorPickerRecentColors
recentColors.remove(color)
if (recentColors.size >= RECENT_COLORS_NUMBER) {
val numberOfColorsToDrop = recentColors.size - RECENT_COLORS_NUMBER + 1
recentColors = LinkedList(recentColors.dropLast(numberOfColorsToDrop))
}
recentColors.addFirst(color)
baseConfig.colorPickerRecentColors = recentColors
}
private fun getHexCode(color: Int) = color.toHex().substring(1)
private fun updateHue() {
viewSatVal.setHue(getHue())
moveHuePicker()
viewNewColor.setFillWithStroke(getColor(), backgroundColor)
if (removeDimmedBackground && !wasDimmedBackgroundRemoved) {
dialog?.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
wasDimmedBackgroundRemoved = true
}
currentColorCallback?.invoke(getColor())
}
private fun moveHuePicker() {
var y = viewHue.measuredHeight - getHue() * viewHue.measuredHeight / 360f
if (y == viewHue.measuredHeight.toFloat())
y = 0f
viewCursor.x = (viewHue.left - viewCursor.width).toFloat()
viewCursor.y = viewHue.top + y - viewCursor.height / 2
}
private fun moveColorPicker() {
val x = getSat() * viewSatVal.measuredWidth
val y = (1f - getVal()) * viewSatVal.measuredHeight
viewTarget.x = viewSatVal.left + x - viewTarget.width / 2
viewTarget.y = viewSatVal.top + y - viewTarget.height / 2
}
private fun getColor() = Color.HSVToColor(currentColorHsv)
private fun getHue() = currentColorHsv[0]
private fun getSat() = currentColorHsv[1]
private fun getVal() = currentColorHsv[2]
}
| gpl-3.0 | 10ca461e6d23df00372bf199509e43f8 | 35.372549 | 142 | 0.613477 | 4.727319 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/gestures/EventTypesDemo.kt | 3 | 4481 | /*
* 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.demos.gestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
private fun TextItem(text: String, color: Color) {
Row {
Box(Modifier.size(25.dp).background(color))
Spacer(Modifier.width(5.dp))
Text(text, fontSize = 20.sp)
}
}
@Composable
private fun DrawEvents(events: List<Pair<PointerEventType, Any>>) {
for (i in events.lastIndex downTo 0) {
val (type, value) = events[i]
val color = when (type) {
PointerEventType.Press -> Color.Red
PointerEventType.Move -> Color(0xFFFFA500) // Orange
PointerEventType.Release -> Color.Yellow
PointerEventType.Enter -> Color.Green
PointerEventType.Exit -> Color.Blue
PointerEventType.Scroll -> Color(0xFF800080) // Purple
else -> Color.Black
}
TextItem("$type $value", color)
}
}
/**
* Demo to show the event types that are sent
*/
@Composable
fun EventTypesDemo() {
val innerPointerEvents = remember { mutableStateListOf<Pair<PointerEventType, Any>>() }
val outerPointerEvents = remember { mutableStateListOf<Pair<PointerEventType, Any>>() }
Box(
Modifier.pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
event.changes.forEach { it.consume() }
addEvent(event, outerPointerEvents)
}
}
}
) {
Column {
DrawEvents(outerPointerEvents)
}
Column(
Modifier.size(200.dp)
.border(2.dp, Color.Black)
.align(Alignment.CenterEnd)
.clipToBounds()
.pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
addEvent(event, innerPointerEvents)
}
}
}
) {
DrawEvents(innerPointerEvents)
}
}
}
private fun addEvent(
event: PointerEvent,
events: MutableList<Pair<PointerEventType, Any>>,
) {
event.changes.forEach { it.consume() }
val scrollTotal = event.changes.foldRight(Offset.Zero) { c, acc -> acc + c.scrollDelta }
if (events.lastOrNull()?.first == event.type) {
val (type, value) = events.last()
if (type == PointerEventType.Scroll) {
events[events.lastIndex] = type to ((value as Offset) + scrollTotal)
} else {
events[events.lastIndex] = type to ((value as Int) + 1)
}
} else if (event.type == PointerEventType.Scroll) {
events += event.type to scrollTotal
} else {
events += event.type to 1
}
while (events.size > 100) {
events.removeAt(0)
}
} | apache-2.0 | e917e88743722533da73236c9155ec4e | 33.21374 | 92 | 0.645838 | 4.427866 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ModuleDefaultVcsRootPolicy.kt | 2 | 1867 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.stateStore
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity
open class ModuleDefaultVcsRootPolicy(project: Project) : DefaultVcsRootPolicy(project) {
init {
project.messageBus.connect().subscribe(WorkspaceModelTopics.CHANGED, MyModulesListener())
}
override fun getDefaultVcsRoots(): Collection<VirtualFile> {
val result = mutableSetOf<VirtualFile>()
val baseDir = myProject.baseDir
if (baseDir != null) {
result.add(baseDir)
val directoryStorePath = myProject.stateStore.directoryStorePath
if (directoryStorePath != null) {
val ideaDir = LocalFileSystem.getInstance().findFileByNioFile(directoryStorePath)
if (ideaDir != null) {
result.add(ideaDir)
}
}
}
result += runReadAction {
WorkspaceModel.getInstance(myProject).entityStorage.current
.entities(ContentRootEntity::class.java)
.mapNotNull { it.url.virtualFile }
.filter { it.isInLocalFileSystem }
.filter { it.isDirectory }
}
return result
}
private inner class MyModulesListener : ContentRootChangeListener(skipFileChanges = true) {
override fun contentRootsChanged(removed: List<VirtualFile>, added: List<VirtualFile>) {
scheduleMappedRootsUpdate()
}
}
} | apache-2.0 | 3ddc0ec5595ba648ee0fcb4be7a50aab | 36.36 | 140 | 0.750937 | 4.750636 | false | false | false | false |
JetBrains/xodus | utils/src/main/kotlin/jetbrains/exodus/core/dataStructures/hash/PackedLongHashSet.kt | 1 | 3184 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.core.dataStructures.hash
import java.lang.Long.SIZE
import java.util.*
private const val LONG_BITS: Int = SIZE
private const val LONG_BITS_LOG: Int = 6
class PackedLongHashSet(source: Collection<Long>? = null, loadFactor: Float = HashUtil.DEFAULT_LOAD_FACTOR) : AbstractSet<Long>(), LongSet {
private val map = LongLongHashMap(20, loadFactor)
private var count: Int = 0
init {
source?.forEach { add(it) }
}
override val size: Int
get() {
return count
}
override fun contains(element: Long): Boolean {
val v = map[element.key]
return v != null && v and masks[element.bit] != 0L
}
override fun add(element: Long): Boolean {
val key = element.key
val bit = element.bit
val mask = masks[bit]
return map.addBit(key, mask).also { if (it) ++count }
}
override fun remove(element: Long): Boolean {
val key = element.key
val bit = element.bit
val mask = masks[bit]
return map.removeBit(key, mask).also { if (it) --count }
}
override fun clear() {
map.clear()
count = 0
}
override fun iterator(): LongIterator {
return object : LongIterator {
private val longs = toLongArray()
private var i = 0
override fun next(): Long {
return nextLong()
}
override fun remove() {
remove(longs[i - 1])
}
override fun hasNext(): Boolean {
return i < longs.size
}
override fun nextLong(): Long {
return longs[i++]
}
}
}
override fun toLongArray(): LongArray {
return LongArray(count).apply {
var i = 0
map.forEach { entry ->
val base = entry.key shl LONG_BITS_LOG
val value = entry.value
for (j in 0 until LONG_BITS) {
if (value and masks[j] != 0L) {
this[i++] = base + j
}
}
}
}
}
companion object {
private val masks = LongArray(LONG_BITS).apply {
var mask = 1L
for (i in 0 until LONG_BITS) {
this[i] = mask
mask = mask shl 1
}
}
private val Long.key: Long get() = this shr LONG_BITS_LOG
private val Long.bit: Int get() = (this and (LONG_BITS - 1).toLong()).toInt()
}
} | apache-2.0 | 7629b8375f994644212a2a0f948a4de5 | 26.695652 | 140 | 0.550879 | 4.320217 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/type/SuspendFunction.kt | 7 | 423 | //ALLOW_AST_ACCESS
package test
fun test1(): suspend () -> Unit = null!!
fun test1N(): (suspend () -> Unit)? = null
fun test2(): suspend Int.() -> Int = null!!
fun test2N(): (suspend Int.() -> Int)? = null
fun test3(): List<suspend () -> Unit> = null!!
fun test3N(): List<(suspend () -> Unit)?> = null!!
fun test4(): suspend () -> (suspend () -> Unit) = null!!
fun test4N(): (suspend () -> (suspend () -> Unit)?)? = null
| apache-2.0 | d35367cb7dee7568f3a0125552ff5e37 | 34.25 | 59 | 0.565012 | 3.156716 | false | true | false | false |
vovagrechka/fucking-everything | 1/3rd-party-web-apis/src/main/java/ms-apis.kt | 1 | 17917 | package vgrechka
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.scribejava.core.builder.ServiceBuilder
import com.github.scribejava.core.builder.api.DefaultApi20
import javafx.application.Application
import javafx.application.Platform
import javafx.concurrent.Worker
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.layout.StackPane
import javafx.scene.layout.VBox
import javafx.scene.web.WebEngine
import javafx.scene.web.WebView
import javafx.stage.Stage
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.RandomAccessFile
import java.util.*
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.properties.Delegates.notNull
// https://apps.dev.microsoft.com
// https://developer.microsoft.com/en-us/graph/graph-explorer
// https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview
// https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/onedrive
class OneDrive {
// val redirectURIPort = 8000
val uploadChunkSize = 320 * 1024 * 32 // OneDrive wants chunk size to be divisible by 320KB
val readTimeoutWhenDownloadingSeconds = 5 * 60
var state: AuthenticationState = AuthenticationState.INITIAL
var accessToken by notNull<String>()
var code by notNull<String>()
val once = InvokerOnce()
var account by notNullOnce<Account>()
class Account(val displayName: String)
val debug_actLikeGotAccessToken = false
enum class AuthenticationState {
INITIAL, VIRGIN, HAS_CODE, HAS_ACCESS_TOKEN, ACCESS_TOKEN_SEEMS_VALID
}
fun getDirToStoreAccessTokenIn() =
FilePile.ensuringDirectoryExists("c:/tmp/${this::class.qualifiedName}-shit")
init {
val secrets = BigPile.saucerfulOfSecrets.onedrive.pepezdus
clog("secrets.scopes = " + secrets.scopes)
val service = ServiceBuilder()
.apiKey(secrets.tokenID)
// .callback("http://localhost:$redirectURIPort")
.callback(secrets.redirectURI)
.scope(secrets.scopes)
.build(object : DefaultApi20() {
override fun getAuthorizationBaseUrl(): String {
return secrets.authorityURL + secrets.authorizationEndpoint
}
override fun getAccessTokenEndpoint(): String {
return secrets.authorityURL + secrets.tokenEndpoint
}
})
val codeFile = File(getDirToStoreAccessTokenIn().path + "/code")
val accessTokenFile = File(getDirToStoreAccessTokenIn().path + "/access-token")
o@while (true) {
clog("state = $state")
exhaustive=when (state) {
AuthenticationState.ACCESS_TOKEN_SEEMS_VALID -> {
break@o
}
AuthenticationState.INITIAL -> {
if (accessTokenFile.exists()) {
accessToken = accessTokenFile.readText()
state = AuthenticationState.HAS_ACCESS_TOKEN
} else {
if (codeFile.exists()) {
code = codeFile.readText()
state = AuthenticationState.HAS_CODE
} else {
state = AuthenticationState.VIRGIN
}
}
}
AuthenticationState.VIRGIN -> {
val url = service.getAuthorizationUrl(mapOf())
code = ObtainCodeViaJavaFX(url).ignite()
codeFile.writeText(code)
state = AuthenticationState.HAS_CODE
}
AuthenticationState.HAS_CODE -> {
try {
accessToken = when {
debug_actLikeGotAccessToken -> "fucking-token"
else -> {
val token = service.getAccessToken(code)
clog("token.rawResponse = " + token.rawResponse)
token.accessToken
}
}
accessTokenFile.writeText(accessToken)
state = AuthenticationState.HAS_ACCESS_TOKEN
} catch(e: Throwable) {
state = AuthenticationState.VIRGIN
}
}
AuthenticationState.HAS_ACCESS_TOKEN -> {
try {
val request = Request.Builder()
.url("https://graph.microsoft.com/v1.0/me/")
.header("Authorization", "Bearer " + accessTokenFile.readText())
.header("Content-type", "application/json")
.get()
.build()
val response = HTTPPile.send_receiveUTF8(request)
// clog(response.body)
if (response.code != HTTPPile.code.ok) {
state = AuthenticationState.VIRGIN
} else {
val map = ObjectMapper().readValue(response.body, Map::class.java)
account = Account(displayName = map["displayName"] as String)
clog("User: " + account.displayName)
state = AuthenticationState.ACCESS_TOKEN_SEEMS_VALID
}
} catch (e: Throwable) {
e.printStackTrace()
state = AuthenticationState.VIRGIN
}
}
}
}
}
companion object {
val javafxLaunchedEvent = ArrayBlockingQueue<Any>(1)
}
class App : Application() {
override fun start(ignore_primaryStage: Stage) {
Platform.setImplicitExit(false)
JFXPile.installUncaughtExceptionHandler_errorAlert()
javafxLaunchedEvent.add(Any())
}
}
inner class ObtainCodeViaJavaFX(val url: String) {
val codeObtainedEvent = ArrayBlockingQueue<String>(1)
fun ignite(): String {
javafxLaunchedEvent.clear()
thread {
try {
Application.launch(App::class.java)
} catch (e: IllegalStateException) {
if (e.message == "Application launch must not be called more than once") {
// OK
javafxLaunchedEvent.add(Any())
} else {
throw e
}
}
}
javafxLaunchedEvent.take()
JFXPile.later {ShowAuthenticationWindow()}
return codeObtainedEvent.take()
}
inner class ShowAuthenticationWindow {
val stage = Stage()
val stackPane = StackPane()
val vbox = VBox()
val loadWorker: Worker<Void>
val progressIndicator = ProgressIndicator()
val engine: WebEngine
val once = InvokerOnce()
init {
Thread.setDefaultUncaughtExceptionHandler {thread, exception ->
showException(exception)
}
stage.width = 500.0
stage.height = 600.0
stage.title = "Authentication"
vbox.children += MenuBar()-{o->
o.menus += Menu("_Tools")-{o->
o.addItem("_Mess Around") {
yieldCode("pizda")
}
}
}
val webView = WebView()
vbox.children += webView
engine = webView.engine
loadWorker = engine.loadWorker
// debug_doSomeShit()
loadWorker.progressProperty().addListener {_,_,_-> handleLoadWorkerState()}
loadWorker.stateProperty().addListener {_,_,_-> handleLoadWorkerState()}
engine.load(url)
stackPane.children += vbox
stackPane.children += progressIndicator
if (!once.wasExecuted(this::showIllegalStateScene)) {
stage.scene = Scene(stackPane)
}
stage.show()
}
fun showIllegalStateScene(text: String) {
once(this::showIllegalStateScene) {
val label = Label(text)
StackPane.setAlignment(label, Pos.TOP_LEFT)
label.alignment = Pos.TOP_LEFT
stage.scene = Scene(label)
}
}
fun showException(e: Throwable) {
e.printStackTrace()
showIllegalStateScene(e.stackTraceString)
}
fun yieldCode(code: String) {
once(this::yieldCode) {
codeObtainedEvent.add(code)
stage.close()
}
}
fun handleLoadWorkerState() {
// clog("progress = " + loadWorker.progress)
// clog("state = " + loadWorker.state)
// clog("location = " + engine.location)
if (loadWorker.state == Worker.State.FAILED) {
showException(loadWorker.exception)
return
}
progressIndicator.isVisible = loadWorker.state in setOf(Worker.State.SCHEDULED, Worker.State.RUNNING)
val loc = engine.location
val prefix = "https://login.microsoftonline.com/common/oauth2/nativeclient?code="
if (loc.startsWith(prefix))
yieldCode(loc.substring(prefix.length))
}
fun debug_doSomeShit() {
if (false) {
thread {
while (true) {
Thread.sleep(3000)
JFXPile.later {showException(Exception("Всему пиздец ${Date()}"))}
}
}
}
if (false) {
thread {
Thread.sleep(3000)
JFXPile.later {yieldCode("pipiska")}
}
}
}
}
}
// private fun obtainCodeViaLocalWebServer(url: String): String {
// var code by notNullOnce<String>()
//
// val server = Server(redirectURIPort)
// server.handler = ServletHandler() - {o ->
// o.addServletWithMapping(ServletHolder(object : HttpServlet() {
// override fun service(req: HttpServletRequest, res: HttpServletResponse) {
// code = req.getParameter("code")
// res.contentType = "text/html; charset=utf-8"
// res.writer.println("Fuck you")
// res.status = HttpServletResponse.SC_OK
// res.flushBuffer()
// thread {
// // If not in separate thread, Jetty hangs
// server.stop()
// }
// }
// }), "/*")
// }
// server.start()
// clog("Shit is spinning")
// clog("Move your ass here: " + url)
//
// server.join()
// return code
// }
fun createFolder(remotePath: String) {
val lastSlash = remotePath.lastIndexOfOrNull("/") ?: bitch("0981f6c9-4a97-4b3e-8776-d6408acf1de3")
val name = remotePath.substring(lastSlash + 1)
val parentPath = remotePath.substring(0, lastSlash)
check(parentPath.startsWith("/"))
check(!parentPath.endsWith("/"))
check(!name.contains("/"))
val res = post("/me/drive/root:$parentPath:/children", mapOf(
"name" to name,
"folder" to mapOf<Any, Any>()
))
bitchUnlessCode(res, HTTPPile.code.created, "Failed to create OneDrive folder")
}
private fun bitchUnlessCode(res: HTTPPile.StringResponse, expectedCode: Int, message: String) {
if (res.code != expectedCode) {
throw Exception(message + "\n"
+ "HTTP code: ${res.code} (expecting $expectedCode)\n\n"
+ JSONPile.prettyPrintJSON(res.body))
}
}
private fun bitchUnlessCode(res: Response, expectedCode: Int, message: String) {
if (res.code() != expectedCode) {
throw Exception(message + "\n"
+ "HTTP code: ${res.code()} (expecting $expectedCode)\n\n"
+ JSONPile.prettyPrintJSON(res.readUTF8()))
}
}
private fun post(url: String, body: Map<String, Any>): HTTPPile.StringResponse {
check(url.startsWith("/"))
val request = Request.Builder()
.url("https://graph.microsoft.com/v1.0" + url)
.header("Authorization", "Bearer " + accessToken)
.post(HTTPPile.makeJSONRequestBody(ObjectMapper().writeValueAsString(body)))
.build()
val response = HTTPPile.send_receiveUTF8(request)
// clog(response.body)
return response
}
@JsonIgnoreProperties(ignoreUnknown = true)
@Ser class JSON_CreateUploadSessionResponse(
val uploadUrl: String,
val expirationDateTime: String,
val nextExpectedRanges: List<String>)
@JsonIgnoreProperties(ignoreUnknown = true)
@Ser class JSON_UploadChunkAcceptedResponse(
val nextExpectedRanges: List<String>)
fun getRangeStart(nextExpectedRanges: List<String>): Long {
check(nextExpectedRanges.size == 1) {"35c076a4-4fee-498b-975a-3ab35f79d6bb"}
val s = nextExpectedRanges.first()
val mr = Regex("(\\d+)-.*").matchEntire(s)
?: bitch("Weird range: `$s` 2bc128c9-8e7f-4757-a233-df8b8320b232")
return mr.groupValues[1].toLong()
}
fun uploadFile(file: File, remoteFilePath: String) {
val sessionRawResponse = post("/me/drive/root:$remoteFilePath:/createUploadSession", mapOf())
bitchUnlessCode(sessionRawResponse, HTTPPile.code.ok, "Failed to create OneDrive upload session")
val sessionResponse = ObjectMapper().readValue(sessionRawResponse.body, JSON_CreateUploadSessionResponse::class.java)
var rangeFrom = getRangeStart(sessionResponse.nextExpectedRanges)
val raf = RandomAccessFile(file, "r")
raf.use {
loop@while (true) {
val bytesLeft = raf.length() - rangeFrom
val chunkSize = when {
bytesLeft < uploadChunkSize -> bytesLeft.toInt()
else -> uploadChunkSize
}
val chunk = ByteArray(chunkSize)
raf.seek(rangeFrom)
val bytesRead = raf.read(chunk)
if (bytesRead != chunk.size) bitch("75cdb36d-998e-49bc-b014-848d9f90d110")
val uploadRequest = Request.Builder()
.url(sessionResponse.uploadUrl)
.header("Content-Length", "${chunk.size}")
.header("Content-Range", "bytes $rangeFrom-${rangeFrom + chunk.size - 1}/${raf.length()}")
.put(RequestBody.create(null, chunk))
.build()
val uploadRawResponse = HTTPPile.send_receiveUTF8(uploadRequest)
when (uploadRawResponse.code) {
HTTPPile.code.accepted -> {
val uploadResponse = ObjectMapper().readValue(uploadRawResponse.body, JSON_UploadChunkAcceptedResponse::class.java)
rangeFrom = getRangeStart(uploadResponse.nextExpectedRanges)
}
HTTPPile.code.created -> {
break@loop
}
else -> {
throw Exception("Failed to upload chunk to OneDrive" + "\n"
+ "HTTP code: ${uploadRawResponse.code} (expecting either ${HTTPPile.code.accepted} or ${HTTPPile.code.created})\n\n"
+ JSONPile.prettyPrintJSON(uploadRawResponse.body))
}
}
}
}
}
fun downloadFile(remotePath: String, stm: FileOutputStream) {
check(remotePath.startsWith("/"))
val request = Request.Builder()
.url("https://graph.microsoft.com/v1.0/me/drive/root:$remotePath:/content")
.header("Authorization", "Bearer " + accessToken)
.get()
.build()
val client = OkHttpClient.Builder()
.readTimeout(readTimeoutWhenDownloadingSeconds.toLong(), TimeUnit.SECONDS)
.build()
val response = client.newCall(request).execute()
bitchUnlessCode(response, HTTPPile.code.ok, "Failed to download shit from OneDrive")
val chunk = ByteArray(1024 * 1024)
response.body().byteStream().use {istm->
while (true) {
val bytesRead = istm.read(chunk)
if (bytesRead == -1)
break
stm.write(chunk, 0, bytesRead)
}
}
}
}
//private fun Menu.addItem(title: String, handler: () -> Unit) {
// items += MenuItem(title)-{o->
// o.onAction = EventHandler {e->
// handler()
// }
// }
//}
| apache-2.0 | 4ea2d1b46bc8a039842c8dd8f07182e1 | 37.590517 | 161 | 0.530213 | 4.908443 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/util/application/ApplicationUtils.kt | 3 | 3766 | // 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.util.application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.impl.CancellationCheck
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.psi.PsiElement
fun <T> runReadAction(action: () -> T): T {
return ApplicationManager.getApplication().runReadAction<T>(action)
}
fun <T> runWriteAction(action: () -> T): T {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}
/**
* Run under the write action if the supplied element is physical; run normally otherwise.
*
* @param e context element
* @param action action to execute
* @return result of action execution
*/
fun <T> runWriteActionIfPhysical(e: PsiElement, action: () -> T): T {
if (e.isPhysical) {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}
return action()
}
fun Project.executeWriteCommand(@NlsContexts.Command name: String, command: () -> Unit) {
CommandProcessor.getInstance().executeCommand(this, { runWriteAction(command) }, name, null)
}
fun <T> Project.executeWriteCommand(@NlsContexts.Command name: String, groupId: Any? = null, command: () -> T): T {
return executeCommand<T>(name, groupId) { runWriteAction(command) }
}
fun <T> Project.executeCommand(@NlsContexts.Command name: String, groupId: Any? = null, command: () -> T): T {
@Suppress("UNCHECKED_CAST") var result: T = null as T
CommandProcessor.getInstance().executeCommand(this, { result = command() }, name, groupId)
@Suppress("USELESS_CAST")
return result as T
}
fun <T> runWithCancellationCheck(block: () -> T): T = CancellationCheck.runWithCancellationCheck(block)
inline fun executeOnPooledThread(crossinline action: () -> Unit) =
ApplicationManager.getApplication().executeOnPooledThread { action() }
inline fun invokeLater(crossinline action: () -> Unit) =
ApplicationManager.getApplication().invokeLater { action() }
inline fun invokeLater(expired: Condition<*>, crossinline action: () -> Unit) =
ApplicationManager.getApplication().invokeLater({ action() }, expired)
@Suppress("NOTHING_TO_INLINE")
inline fun isUnitTestMode(): Boolean = ApplicationManager.getApplication().isUnitTestMode
@Suppress("NOTHING_TO_INLINE")
inline fun isDispatchThread(): Boolean = ApplicationManager.getApplication().isDispatchThread
@Suppress("NOTHING_TO_INLINE")
inline fun isApplicationInternalMode(): Boolean = ApplicationManager.getApplication().isInternal
fun <T> executeInBackgroundWithProgress(project: Project? = null, @NlsContexts.ProgressTitle title: String, block: () -> T): T {
assert(!ApplicationManager.getApplication().isWriteAccessAllowed) {
"Rescheduling computation into the background is impossible under the write lock"
}
return ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable { block() }, title, true, project
)
}
inline fun <T> runAction(runImmediately: Boolean, crossinline action: () -> T): T {
if (runImmediately) {
return action()
}
var result: T? = null
ApplicationManager.getApplication().invokeAndWait {
CommandProcessor.getInstance().runUndoTransparentAction {
result = ApplicationManager.getApplication().runWriteAction<T> { action() }
}
}
return result!!
} | apache-2.0 | 771099ff348ee6637df290e69cb338ce | 39.505376 | 158 | 0.742432 | 4.587089 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/ExtensionsUtils.kt | 4 | 3259 | // 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.
@file:JvmName("ExtensionUtils")
package org.jetbrains.kotlin.idea.util
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.nullability
fun <TCallable : CallableDescriptor> TCallable.substituteExtensionIfCallable(
receiverTypes: Collection<KotlinType>,
callType: CallType<*>
): Collection<TCallable> {
if (!callType.descriptorKindFilter.accepts(this)) return listOf()
var types = receiverTypes.asSequence()
if (callType == CallType.SAFE) {
types = types.map { it.makeNotNullable() }
}
val extensionReceiverType = fuzzyExtensionReceiverType()!!
val substitutors = types.mapNotNull {
var substitutor = extensionReceiverType.checkIsSuperTypeOf(it)
// check if we may fail due to receiver expression being nullable
if (substitutor == null && it.nullability() == TypeNullability.NULLABLE && extensionReceiverType.nullability() == TypeNullability.NOT_NULL) {
substitutor = extensionReceiverType.checkIsSuperTypeOf(it.makeNotNullable())
}
substitutor
}
return if (typeParameters.isEmpty()) { // optimization for non-generic callables
if (substitutors.any()) listOf(this) else listOf()
} else {
substitutors
.mapNotNull { @Suppress("UNCHECKED_CAST") (substitute(it) as TCallable?) }
.toList()
}
}
fun ReceiverValue?.getThisReceiverOwner(bindingContext: BindingContext): DeclarationDescriptor? {
return when (this) {
is ExpressionReceiver -> {
val thisRef = (KtPsiUtil.deparenthesize(this.expression) as? KtThisExpression)?.instanceReference ?: return null
bindingContext[BindingContext.REFERENCE_TARGET, thisRef]
}
is ImplicitReceiver -> this.declarationDescriptor
else -> null
}
}
fun ReceiverValue?.getReceiverTargetDescriptor(bindingContext: BindingContext): DeclarationDescriptor? {
return when (this) {
is ExpressionReceiver -> {
val target = when (val expression = KtPsiUtil.deparenthesize(this.expression)) {
is KtThisExpression -> expression.instanceReference
is KtReferenceExpression -> expression
else -> null
}
return if (target != null) bindingContext[BindingContext.REFERENCE_TARGET, target] else null
}
is ImplicitReceiver -> this.declarationDescriptor
else -> null
}
}
| apache-2.0 | 106bf8c4aacb0ce6efa2fbefeee3eb05 | 42.453333 | 158 | 0.727524 | 5.140379 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/formatting/commandLine/FileSetCodeStyleProcessor.kt | 2 | 9215 | // 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.formatting.commandLine
import com.intellij.application.options.CodeStyle
import com.intellij.formatting.service.CoreFormattingService
import com.intellij.formatting.service.FormattingServiceUtil
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.lang.LanguageFormatting
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.util.LocalTimeCounter
import com.intellij.util.PlatformUtils
import org.jetbrains.jps.model.serialization.PathMacroUtil
import java.io.Closeable
import java.nio.charset.Charset
import java.nio.file.Files
import java.util.*
private val LOG = Logger.getInstance(FileSetCodeStyleProcessor::class.java)
private const val RESULT_MESSAGE_OK = "OK"
private const val RESULT_MESSAGE_FAILED = "Failed"
private const val RESULT_MESSAGE_NOT_SUPPORTED = "Skipped, not supported."
private const val RESULT_MESSAGE_REJECTED_BY_FORMATTER = "Skipped, rejected by formatter."
private const val RESULT_MESSAGE_BINARY_FILE = "Skipped, binary file."
private const val RESULT_MESSAGE_DRY_OK = "Formatted well"
private const val RESULT_MESSAGE_DRY_FAIL = "Needs reformatting"
class FileSetFormatter(
messageOutput: MessageOutput,
isRecursive: Boolean,
charset: Charset? = null,
primaryCodeStyle: CodeStyleSettings? = null,
defaultCodeStyle: CodeStyleSettings? = null
) : FileSetCodeStyleProcessor(messageOutput, isRecursive, charset, primaryCodeStyle, defaultCodeStyle) {
override val operationContinuous = "Formatting"
override val operationPerfect = "formatted"
override fun processFileInternal(virtualFile: VirtualFile): String {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
if (document == null) {
LOG.warn("No document available for " + virtualFile.path)
return RESULT_MESSAGE_FAILED
}
try {
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document)
NonProjectFileWritingAccessProvider.allowWriting(listOf(virtualFile))
if (psiFile == null) {
LOG.warn("Unable to get a PSI file for " + virtualFile.path)
return RESULT_MESSAGE_FAILED
}
if (!psiFile.isFormattingSupported()) {
return RESULT_MESSAGE_NOT_SUPPORTED
}
try {
reformatFile(psiFile, document)
}
catch (pce: ProcessCanceledException) {
val cause = pce.cause?.message ?: pce.message ?: ""
LOG.warn("${virtualFile.canonicalPath}: $RESULT_MESSAGE_REJECTED_BY_FORMATTER $cause")
return RESULT_MESSAGE_REJECTED_BY_FORMATTER
}
FileDocumentManager.getInstance().saveDocument(document)
}
finally {
closeOpenFiles()
}
statistics.fileProcessed(true)
return RESULT_MESSAGE_OK
}
private fun reformatFile(file: PsiFile, document: Document) {
WriteCommandAction.runWriteCommandAction(project) {
val codeStyleManager = CodeStyleManager.getInstance(project)
codeStyleManager.reformatText(file, 0, file.textLength)
PsiDocumentManager.getInstance(project).commitDocument(document)
}
}
private fun closeOpenFiles() {
val editorManager = FileEditorManager.getInstance(project)
val openFiles = editorManager.openFiles
for (openFile in openFiles) {
editorManager.closeFile(openFile)
}
}
}
class FileSetFormatValidator(
messageOutput: MessageOutput,
isRecursive: Boolean,
charset: Charset? = null,
primaryCodeStyle: CodeStyleSettings? = null,
defaultCodeStyle: CodeStyleSettings? = null
) : FileSetCodeStyleProcessor(messageOutput, isRecursive, charset, primaryCodeStyle, defaultCodeStyle) {
override val operationContinuous = "Checking"
override val operationPerfect = "checked"
override fun printReport() {
super.printReport()
messageOutput.info("${succeeded} file(s) are well formed.\n")
}
override fun isResultSuccessful() = succeeded == processed
override fun processFileInternal(virtualFile: VirtualFile): String {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
if (document == null) {
LOG.warn("No document available for " + virtualFile.path)
return RESULT_MESSAGE_FAILED
}
val originalContent = document.text
val psiCopy = createPsiCopy(virtualFile, originalContent)
CodeStyleManager
.getInstance(project)
.reformatText(psiCopy, 0, psiCopy.textLength)
val reformattedContent = psiCopy.text
return if (originalContent == reformattedContent) {
statistics.fileProcessed(true)
RESULT_MESSAGE_DRY_OK
}
else {
statistics.fileProcessed(false)
RESULT_MESSAGE_DRY_FAIL
}
}
private fun createPsiCopy(originalFile: VirtualFile, originalContent: String): PsiFile {
val psiCopy = PsiFileFactory.getInstance(project).createFileFromText(
"a." + originalFile.fileType.defaultExtension,
originalFile.fileType,
originalContent,
LocalTimeCounter.currentTime(),
false
)
val originalPsi = PsiManager.getInstance(project).findFile(originalFile)
if (originalPsi != null) {
psiCopy.putUserData(PsiFileFactory.ORIGINAL_FILE, originalPsi)
}
return psiCopy
}
}
abstract class FileSetCodeStyleProcessor(
messageOutput: MessageOutput,
isRecursive: Boolean,
charset: Charset? = null,
private val primaryCodeStyle: CodeStyleSettings? = null,
val defaultCodeStyle: CodeStyleSettings? = null
) : FileSetProcessor(messageOutput, isRecursive, charset), Closeable {
private val projectUID = UUID.randomUUID().toString()
protected val project = createProject(projectUID)
abstract val operationContinuous: String
abstract val operationPerfect: String
abstract fun processFileInternal(virtualFile: VirtualFile): String
open fun printReport() {
messageOutput.info("\n")
messageOutput.info("${total} file(s) scanned.\n")
messageOutput.info("${processed} file(s) $operationPerfect.\n")
}
open fun isResultSuccessful() = true
override fun close() {
ProjectManager.getInstance().closeAndDispose(project)
}
override fun processVirtualFile(virtualFile: VirtualFile, projectSettings: CodeStyleSettings?) {
messageOutput.info("$operationContinuous ${virtualFile.canonicalPath}...")
val style = listOfNotNull(primaryCodeStyle, projectSettings, defaultCodeStyle).firstOrNull()
if (style == null) {
messageOutput.error("No style for ${virtualFile.canonicalPath}, skipping...")
statistics.fileProcessed(true)
return
}
withStyleSettings(style) {
VfsUtil.markDirtyAndRefresh(false, false, false, virtualFile)
val resultMessage =
if (virtualFile.fileType.isBinary) {
RESULT_MESSAGE_BINARY_FILE
}
else {
processFileInternal(virtualFile)
}
messageOutput.info("$resultMessage\n")
}
}
private fun <T> withStyleSettings(style: CodeStyleSettings, body: () -> T): T {
val cssManager = CodeStyleSettingsManager.getInstance(project)
val tmp = cssManager.mainProjectCodeStyle!!
try {
CodeStyle.setMainProjectSettings(project, style)
return body()
} finally {
CodeStyle.setMainProjectSettings(project, tmp)
}
}
}
private val PROJECT_DIR_PREFIX = PlatformUtils.getPlatformPrefix() + ".format."
private const val PROJECT_DIR_SUFFIX = ".tmp"
private fun createProjectDir(projectUID: String) = FileUtil
.createTempDirectory(PROJECT_DIR_PREFIX, projectUID + PROJECT_DIR_SUFFIX)
.toPath()
.resolve(PathMacroUtil.DIRECTORY_STORE_NAME)
.also { Files.createDirectories(it) }
private fun createProject(projectUID: String) =
ProjectManagerEx.getInstanceEx()
.openProject(createProjectDir(projectUID), OpenProjectTask(isNewProject = true))
?.also {
CodeStyle.setMainProjectSettings(it, CodeStyleSettingsManager.getInstance().createSettings())
}
?: throw RuntimeException("Failed to create temporary project $projectUID")
private fun PsiFile.isFormattingSupported(): Boolean {
val formattingService = FormattingServiceUtil.findService(this, true, true)
return (formattingService !is CoreFormattingService)
|| (LanguageFormatting.INSTANCE.forContext(this) != null)
}
| apache-2.0 | b5adfbe70e6c3540fd7c622277035022 | 33.513109 | 120 | 0.752469 | 4.628327 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/autolink/GradleUnlinkedProjectAware.kt | 12 | 2174 | // 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.gradle.autolink
import com.intellij.openapi.Disposable
import com.intellij.openapi.externalSystem.autolink.ExternalSystemProjectLinkListener
import com.intellij.openapi.externalSystem.autolink.ExternalSystemUnlinkedProjectAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter
import org.jetbrains.plugins.gradle.service.project.open.linkAndRefreshGradleProject
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants.KNOWN_GRADLE_FILES
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
class GradleUnlinkedProjectAware : ExternalSystemUnlinkedProjectAware {
override val systemId = SYSTEM_ID
override fun isBuildFile(project: Project, buildFile: VirtualFile): Boolean {
return buildFile.name in KNOWN_GRADLE_FILES
}
override fun isLinkedProject(project: Project, externalProjectPath: String): Boolean {
val gradleSettings = GradleSettings.getInstance(project)
val projectSettings = gradleSettings.getLinkedProjectSettings(externalProjectPath)
return projectSettings != null
}
override fun subscribe(project: Project, listener: ExternalSystemProjectLinkListener, parentDisposable: Disposable) {
val gradleSettings = GradleSettings.getInstance(project)
gradleSettings.subscribe(object : GradleSettingsListenerAdapter() {
override fun onProjectsLinked(settings: Collection<GradleProjectSettings>) =
settings.forEach { listener.onProjectLinked(it.externalProjectPath) }
override fun onProjectsUnlinked(linkedProjectPaths: Set<String>) =
linkedProjectPaths.forEach { listener.onProjectUnlinked(it) }
}, parentDisposable)
}
override fun linkAndLoadProject(project: Project, externalProjectPath: String) {
linkAndRefreshGradleProject(externalProjectPath, project)
}
} | apache-2.0 | 2ecfd389bc7d7cdbf1ea34e8b1d61c96 | 49.581395 | 140 | 0.821987 | 5.009217 | false | false | false | false |
NlRVANA/Unity | app/src/test/java/com/zwq65/unity/pattern/dynamic_proxy/LoggerHandler.kt | 1 | 642 | package com.zwq65.unity.pattern.dynamic_proxy
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/11/15
* Contact with <[email protected]>
* ================================================
*/
class LoggerHandler(private val target: Any) : InvocationHandler {
@Throws(Throwable::class)
override fun invoke(proxy: Any, method: Method, args: Array<Any>): Any {
println("準備打印")
val response = method.invoke(target, *args)
println("結束打印")
return response
}
}
| apache-2.0 | 9f49edb6eaab77c41ee8be9763baec49 | 27.454545 | 76 | 0.570288 | 4.118421 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.kt | 3 | 5199 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.ex
import com.intellij.diff.util.DiffUtil
import com.intellij.ide.GeneralSettings
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.editor.markup.MarkupEditorFilter
import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.CalledInAwt
import java.awt.Graphics
import java.awt.Point
import java.awt.event.MouseEvent
import java.util.*
abstract class LineStatusTracker<R : Range> constructor(override val project: Project,
document: Document,
override val virtualFile: VirtualFile,
mode: Mode
) : LineStatusTrackerBase<R>(project, document) {
enum class Mode {
DEFAULT, SMART, SILENT
}
private val vcsDirtyScopeManager: VcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(project)
override abstract val renderer: LocalLineStatusMarkerRenderer
var mode: Mode = mode
set(value) {
if (value == mode) return
field = value
updateInnerRanges()
}
@CalledInAwt
fun isAvailableAt(editor: Editor): Boolean {
return mode != Mode.SILENT && editor.settings.isLineMarkerAreaShown && !DiffUtil.isDiffEditor(editor)
}
@CalledInAwt
override fun isDetectWhitespaceChangedLines(): Boolean = mode == Mode.SMART
@CalledInAwt
override fun fireFileUnchanged() {
if (GeneralSettings.getInstance().isSaveOnFrameDeactivation) {
// later to avoid saving inside document change event processing and deadlock with CLM.
TransactionGuard.getInstance().submitTransactionLater(project, Runnable {
FileDocumentManager.getInstance().saveDocument(document)
val isEmpty = documentTracker.readLock { blocks.isEmpty() }
if (isEmpty) {
// file was modified, and now it's not -> dirty local change
vcsDirtyScopeManager.fileDirty(virtualFile)
}
})
}
}
override fun fireLinesUnchanged(startLine: Int, endLine: Int) {
if (document.textLength == 0) return // empty document has no lines
if (startLine == endLine) return
(document as DocumentImpl).clearLineModificationFlags(startLine, endLine)
}
fun scrollAndShowHint(range: Range, editor: Editor) {
renderer.scrollAndShow(editor, range)
}
fun showHint(range: Range, editor: Editor) {
renderer.showAfterScroll(editor, range)
}
protected open class LocalLineStatusMarkerRenderer(open val tracker: LineStatusTracker<*>)
: LineStatusMarkerPopupRenderer(tracker) {
override fun getEditorFilter(): MarkupEditorFilter? = MarkupEditorFilterFactory.createIsNotDiffFilter()
override fun canDoAction(range: Range, e: MouseEvent?): Boolean {
if (tracker.mode == Mode.SILENT) return false
return super.canDoAction(range, e)
}
override fun paint(editor: Editor, range: Range, g: Graphics) {
if (tracker.mode == Mode.SILENT) return
super.paint(editor, range, g)
}
override fun createToolbarActions(editor: Editor, range: Range, mousePosition: Point?): List<AnAction> {
val actions = ArrayList<AnAction>()
actions.add(ShowPrevChangeMarkerAction(editor, range))
actions.add(ShowNextChangeMarkerAction(editor, range))
actions.add(RollbackLineStatusRangeAction(editor, range))
actions.add(ShowLineStatusRangeDiffAction(editor, range))
actions.add(CopyLineStatusRangeAction(editor, range))
actions.add(ToggleByWordDiffAction(editor, range, mousePosition))
return actions
}
override fun getFileType(): FileType = tracker.virtualFile.fileType
private inner class RollbackLineStatusRangeAction(editor: Editor, range: Range)
: RangeMarkerAction(editor, range, IdeActions.SELECTED_CHANGES_ROLLBACK) {
override fun isEnabled(editor: Editor, range: Range): Boolean = true
override fun actionPerformed(editor: Editor, range: Range) {
RollbackLineStatusAction.rollback(tracker, range, editor)
}
}
}
}
| apache-2.0 | 5c44e00baee4be515093390faa6f4866 | 37.798507 | 108 | 0.728025 | 4.646113 | false | false | false | false |
DrOptix/strava-intervall | strava-intervall/src/main/kotlin/com/worldexplorerblog/stravaintervall/service/TrainingRecordingService.kt | 1 | 7825 | package com.worldexplorerblog.stravaintervall.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Binder
import android.os.Bundle
import android.os.IBinder
import android.speech.tts.TextToSpeech
import com.worldexplorerblog.stravaintervall.models.TrainingIntervalModel
import java.text.SimpleDateFormat
import java.util.*
data class RecordedIntervalModel(var timestamp: String,
val locations: ArrayList<Location>)
class TrainingRecordingService : Service() {
public var trainingIntervals = emptyList<TrainingIntervalModel>().toArrayList()
public var recordedIntervals = emptyList<RecordedIntervalModel>().toArrayList()
get
private set
public var intervalRemainingSeconds = 0
get
private set
public var trainingElapsedSeconds = 0
get
private set
public var currentIntervalIndex = -1
get
private set
public var onTimerTick: () -> Unit = { /* Do Nothing */ }
private val binder = TrainingRecordingBinder()
private var timer = Timer()
private var textToSpeech: TextToSpeech? = null
private val listener = object : LocationListener {
override fun onLocationChanged(location: Location?) {
if (currentIntervalIndex != -1
&& currentIntervalIndex < trainingIntervals.count()
&& isBetterLocation(location as Location, previousBestLocation)) {
recordedIntervals[currentIntervalIndex].locations.add(location)
previousBestLocation = location
}
}
override fun onProviderDisabled(provider: String?) {
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}
override fun onProviderEnabled(provider: String?) {
}
}
var locationManager: LocationManager? = null
var previousBestLocation: Location? = null
public fun startRecording() {
recordedIntervals.clear()
trainingIntervals.forEach {
recordedIntervals.add(RecordedIntervalModel(timeStamp(), ArrayList<Location>()))
}
trainingElapsedSeconds = 0
intervalRemainingSeconds = 0
timer.schedule(object : TimerTask() {
override fun run() {
processTimerTick()
onTimerTick()
}
}, 0, 1000)
}
public fun stopRecording() {
timer.cancel()
timer.purge()
timer = Timer()
}
override fun onBind(intent: Intent?): IBinder? {
return binder
}
override fun onDestroy() {
super.onDestroy()
textToSpeech?.shutdown()
locationManager?.removeUpdates(listener);
}
override fun onCreate() {
super.onCreate()
textToSpeech = TextToSpeech(this, TextToSpeech.OnInitListener {
textToSpeech?.setLanguage(Locale.UK)
})
textToSpeech?.speak(" ", TextToSpeech.QUEUE_FLUSH, null)
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
// locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 5.0f, listener)
locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5.0f, listener)
}
private fun processTimerTick() {
if (intervalRemainingSeconds == 0) {
currentIntervalIndex += 1
if (currentIntervalIndex < trainingIntervals.count()) {
speakInterval()
intervalRemainingSeconds = trainingIntervals[currentIntervalIndex].durationInSeconds
recordedIntervals[currentIntervalIndex].timestamp = timeStamp()
} else if (currentIntervalIndex == trainingIntervals.count()) {
speakGoalAchieved()
}
}
trainingElapsedSeconds += 1
if (currentIntervalIndex < trainingIntervals.count()) {
intervalRemainingSeconds -= 1
}
}
private fun speakGoalAchieved() {
textToSpeech?.speak("You achieved your goal. You can continue training or conclude your training session.",
TextToSpeech.QUEUE_FLUSH,
null)
}
private fun speakInterval() {
val currentInterval = trainingIntervals[currentIntervalIndex]
val minutes = currentInterval.durationInSeconds / 60
val seconds = currentInterval.durationInSeconds % 60
var durationString = if (minutes > 1 && seconds > 0) {
"$minutes minutes $seconds seconds"
} else if (minutes > 1 && seconds == 0) {
"$minutes minutes"
} else if (minutes == 1 && seconds > 0) {
"1 minute $seconds seconds"
} else if (minutes == 1 && seconds == 0) {
"1 minute"
} else {
"$seconds seconds"
}
textToSpeech?.speak("${currentInterval.intensity.toString()} intensity, $durationString",
TextToSpeech.QUEUE_FLUSH,
null)
}
private fun timeStamp(): String {
val timezone = TimeZone.getTimeZone("UTC")
val calendar = Calendar.getInstance(timezone)
val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
formatter.calendar = calendar
formatter.timeZone = timezone
val timestamp = formatter.format(calendar.time)
return timestamp
}
private fun isBetterLocation(location: Location, currentBestLocation: Location?): Boolean {
if (currentBestLocation == null) {
// A new location is always better than no location
return true
}
// Check whether the new location fix is newer or older
val oneSecond = 1000
val timeDelta = location.time - currentBestLocation.time
val isSignificantlyNewer = timeDelta > oneSecond
val isSignificantlyOlder = timeDelta < -oneSecond
val isNewer = timeDelta > 0
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false
}
// Check whether the new location fix is more or less accurate
val accuracyDelta = (location.accuracy - currentBestLocation.accuracy).toInt()
val isLessAccurate = accuracyDelta > 0
val isMoreAccurate = accuracyDelta < 0
val isSignificantlyLessAccurate = accuracyDelta > 200
// Check if the old and new location are from the same provider
val isFromSameProvider = isSameProvider(location.provider,
currentBestLocation.provider)
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true
} else if (isNewer && !isLessAccurate) {
return true
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true
}
return false
}
private fun isSameProvider(provider1: String?, provider2: String?): Boolean {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
inner class TrainingRecordingBinder : Binder() {
fun getService(): TrainingRecordingService {
return this@TrainingRecordingService
}
}
}
| gpl-3.0 | 23681ca1b0e5b1a1480111de92a2835f | 32.874459 | 115 | 0.63016 | 5.437804 | false | false | false | false |
excref/kotblog | blog/service/impl/src/main/kotlin/com/excref/kotblog/blog/service/user/impl/UserServiceImpl.kt | 1 | 2369 | package com.excref.kotblog.blog.service.user.impl
import com.excref.kotblog.blog.persistence.user.UserRepository
import com.excref.kotblog.blog.service.user.UserService
import com.excref.kotblog.blog.service.user.domain.User
import com.excref.kotblog.blog.service.user.domain.UserRole
import com.excref.kotblog.blog.service.user.exception.UserAlreadyExistsForEmailException
import com.excref.kotblog.blog.service.user.exception.UserNotFoundForUuidException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
/**
* @author Arthur Asatryan
* @since 6/8/17 12:44 AM
*/
@Service
internal class UserServiceImpl : UserService {
//region Dependencies
@Autowired
private lateinit var userRepository: UserRepository
//endregion
//region Public methods
override fun create(email: String, password: String, role: UserRole): User {
logger.debug("Creating user for email - $email, password - $password and role - $role")
assertUserNotExistsForEmail(email)
return userRepository.save(User(email, password, role))
}
override fun getByUuid(uuid: String): User {
logger.debug("Getting user for with - $uuid")
val user = userRepository.findByUuid(uuid)
assertUserNotNullForUuid(user, uuid)
return user as User
}
override fun existsForEmail(email: String): Boolean {
logger.debug("Getting user for email - $email")
return userRepository.findByEmail(email) != null
}
//endregion
//region Utility methods
private fun assertUserNotExistsForEmail(email: String) {
if (existsForEmail(email)) {
logger.error("The user with email - $email already exists")
throw UserAlreadyExistsForEmailException(email, "The user with email - $email already exists")
}
}
private fun assertUserNotNullForUuid(user: User?, uuid: String) {
if (user == null) {
logger.error("Can not find user for uuid - $uuid")
throw UserNotFoundForUuidException(uuid, "Can not find user for uuid - $uuid")
}
}
//endregion
//region Companion
companion object {
private val logger: Logger = LoggerFactory.getLogger(UserServiceImpl::class.java)
}
//endregion
} | apache-2.0 | 07c041c6f06638dae53a9ce752f4b74b | 33.852941 | 106 | 0.711271 | 4.330896 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/rc/adapter/RobotListAdapter.kt | 1 | 3696 | package pt.joaomneto.titancompanion.adventure.impl.fragments.rc.adapter
import android.content.Context
import android.view.ContextMenu
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.RadioButton
import android.widget.TextView
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.impl.RCAdventure
import pt.joaomneto.titancompanion.adventure.impl.fragments.rc.Robot
class RobotListAdapter(private val adv: RCAdventure, private val values: List<Robot>) :
ArrayAdapter<Robot>(
adv,
-1,
values
),
View.OnCreateContextMenuListener {
override fun onCreateContextMenu(p0: ContextMenu?, p1: View?, p2: ContextMenu.ContextMenuInfo?) {
TODO("not implemented")
}
var currentRobot: Robot?
get() = adv.currentRobot
set(currentRobot) {
adv.currentRobot = currentRobot
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val robotView = inflater.inflate(R.layout.component_22rc_robot, parent, false)
val robotTextName = robotView.rootView.findViewById<TextView>(R.id.robotTextNameValue)
val robotTextArmor = robotView.rootView.findViewById<TextView>(R.id.robotTextArmorValue)
val robotTextSpeed = robotView.rootView.findViewById<TextView>(R.id.robotTextSpeedValue)
val robotTextBonus = robotView.rootView.findViewById<TextView>(R.id.robotTextBonusValue)
val robotTextLocation = robotView.rootView.findViewById<TextView>(R.id.robotTextLocationValue)
val robotTextSpecialAbility = robotView.rootView.findViewById<TextView>(R.id.robotTextSpecialAbilityValue)
// final Button removeRobotButton = (Button)
// robotView.getRootView().findViewById(R.id.removeRobotButton);
val robotPosition = values[position]
robotTextName.text = robotPosition.name
robotTextArmor.text = "" + robotPosition.armor!!
robotTextSpeed.text = "" + robotPosition.speed
robotTextBonus.text = "" + robotPosition.bonus!!
robotTextLocation.text = robotPosition.location
if (robotPosition.robotSpecialAbility != null) {
robotTextSpecialAbility.setText(robotPosition.robotSpecialAbility.getName()!!)
}
val minusCombatArmor = robotView.findViewById<Button>(R.id.minusRobotArmorButton)
val plusCombatArmor = robotView.findViewById<Button>(R.id.plusRobotArmorButton)
val radio = robotView.rootView.findViewById<RadioButton>(R.id.robotSelected)
radio.isChecked = robotPosition.isActive
if (robotPosition.isActive) {
currentRobot = robotPosition
}
val adapter = this
radio.setOnCheckedChangeListener { buttonView, isChecked ->
for (r in values) {
r.isActive = false
}
robotPosition.isActive = true
adapter.notifyDataSetChanged()
currentRobot = robotPosition
adv.fullRefresh()
}
minusCombatArmor.setOnClickListener {
robotPosition.armor = Math.max(0, robotPosition.armor!! - 1)
robotTextArmor.text = "" + robotPosition.armor!!
}
plusCombatArmor.setOnClickListener {
robotPosition.armor = robotPosition.armor!! + 1
robotTextArmor.text = "" + robotPosition.armor!!
}
robotView.setOnLongClickListener { false }
return robotView
}
}
| lgpl-3.0 | 181852f81ea62cf7a0ddd2ff88e0bb6f | 37.5 | 114 | 0.699675 | 4.574257 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/element/control/behavior/ListViewBehavior.kt | 1 | 21573 | package koma.gui.element.control.behavior
import javafx.beans.value.ChangeListener
import javafx.beans.value.WeakChangeListener
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.collections.WeakListChangeListener
import javafx.event.EventHandler
import javafx.scene.control.ListView
import javafx.scene.control.MultipleSelectionModel
import javafx.scene.control.SelectionMode
import javafx.scene.input.KeyCode.*
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseEvent
import koma.gui.element.control.Utils
import koma.gui.element.control.behavior.FocusTraversalInputMap.createInputMap
import koma.gui.element.control.inputmap.KInputMap
import koma.gui.element.control.inputmap.KeyBinding
import koma.gui.element.control.inputmap.MappingType
import koma.gui.element.control.inputmap.mapping.KeyMapping
import koma.gui.element.control.inputmap.mapping.MouseMapping
import mu.KotlinLogging
import java.util.*
import java.util.function.Predicate
private val logger = KotlinLogging.logger {}
class ListViewBehavior<T>(val node: ListView<T>) {
private val installedDefaultMappings = mutableListOf<MappingType>()
private val childInputMapDisposalHandlers = mutableListOf<Runnable>()
private val inputMap: KInputMap<ListView<T>> = createInputMap(node)
private val keyEventListener = { e: KeyEvent ->
if (!e.isConsumed) {
// RT-12751: we want to keep an eye on the user holding down the shift key,
// so that we know when they enter/leave multiple selection mode. This
// changes what happens when certain key combinations are pressed.
isShiftDown = e.eventType == KeyEvent.KEY_PRESSED && e.isShiftDown
isShortcutDown = e.eventType == KeyEvent.KEY_PRESSED && e.isShortcutDown
}
}
/**************************************************************************
* State and Functions *
*/
private var isShiftDown = false
private var isShortcutDown = false
var onScrollPageUp: ((KeyEvent)->Unit)? = null
var onScrollPageDown: ((KeyEvent)->Unit)? = null
private var onFocusPreviousRow: Runnable? = null
private var onFocusNextRow: Runnable? = null
private var onSelectPreviousRow: Runnable? = null
private var onSelectNextRow: Runnable? = null
private var onMoveToFirstCell: Runnable? = null
private var onMoveToLastCell: Runnable? = null
private var selectionChanging = false
private fun selectedIndicesChange(c: ListChangeListener.Change<out Int>) {
var newAnchor = anchor
while (c.next()) {
if (c.wasReplaced()) {
if (CellBehaviorBase.hasDefaultAnchor(node)) {
CellBehaviorBase.removeAnchor(node)
continue
}
}
val shift = if (c.wasPermutated()) c.to - c.from else 0
val sm = node.selectionModel
// there are no selected items, so lets clear out the anchor
if (!selectionChanging) {
if (sm.isEmpty) {
newAnchor = -1
} else if (hasAnchor() && !sm.isSelected(anchor + shift)) {
newAnchor = -1
}
}
// we care about the situation where the selection changes, and there is no anchor. In this
// case, we set a new anchor to be the selected index
if (newAnchor == -1) {
val addedSize = c.addedSize
newAnchor = if (addedSize > 0) c.addedSubList[addedSize - 1] else newAnchor
}
}
if (newAnchor > -1) {
anchor = newAnchor
}
}
private val selectedIndicesListener = ListChangeListener<Int> { selectedIndicesChange(it) }
private fun itemsListChange(c: ListChangeListener.Change<out T>) {
while (c.next()) {
if (!hasAnchor()) continue
var newAnchor = if (hasAnchor()) anchor else 0
if (c.wasAdded() && c.from <= newAnchor) {
newAnchor += c.addedSize
} else if (c.wasRemoved() && c.from <= newAnchor) {
newAnchor -= c.removedSize
}
anchor = if (newAnchor < 0) 0 else newAnchor
}
}
private val itemsListListener = ListChangeListener<T> { itemsListChange(it) }
private val itemsListener = ChangeListener<ObservableList<T>> { _, oldValue, newValue ->
oldValue?.removeListener(weakItemsListListener)
newValue?.addListener(weakItemsListListener)
}
private val selectionModelListener = ChangeListener<MultipleSelectionModel<T>> { _, oldValue, newValue ->
oldValue?.selectedIndices?.removeListener(weakSelectedIndicesListener)
newValue?.selectedIndices?.addListener(weakSelectedIndicesListener)
}
private val weakItemsListener = WeakChangeListener(itemsListener)
private val weakSelectedIndicesListener = WeakListChangeListener<Int>(selectedIndicesListener)
private val weakItemsListListener = WeakListChangeListener<T>(itemsListListener)
private val weakSelectionModelListener = WeakChangeListener(selectionModelListener)
private var anchor: Int
get() = CellBehaviorBase.getAnchor<Int>(node, node.focusModel.focusedIndex)
set(anchor) {
CellBehaviorBase.setAnchor<Int>(node, if (anchor < 0) null else anchor, false)
}
private val rowCount: Int
get() = if (node.items == null) 0 else node.items.size
init {
// create a map for listView-specific mappings
val control = node
// add focus traversal mappings
addDefaultMapping(inputMap, FocusTraversalInputMap.mappings.map { MappingType.Key(it) })
addDefaultMapping(inputMap, listOf(
KeyMapping(HOME, {
logger.debug { "ListViewBehavior<T> KeyMapping HOME selectFirstRow" }
selectFirstRow()
}),
KeyMapping(END, {
logger.debug { "ListViewBehavior<T> KeyMapping END selectLastRow" }
selectLastRow()
}),
KeyMapping(KeyBinding(HOME).shift(), { _ -> selectAllToFirstRow() }),
KeyMapping(KeyBinding(END).shift(), { _ -> selectAllToLastRow() }),
KeyMapping(KeyBinding(SPACE).shift(), { _ -> selectAllToFocus() }),
KeyMapping(KeyBinding(SPACE).shortcut().shift(), { _ -> selectAllToFocus() }),
KeyMapping(PAGE_UP, {
onScrollPageUp?.invoke(it)
}),
KeyMapping(PAGE_DOWN, {
onScrollPageDown?.invoke(it)
}),
KeyMapping(ENTER, { _ -> activate() }),
KeyMapping(SPACE, { _ -> activate() }),
KeyMapping(F2, { _ -> activate() }),
KeyMapping(ESCAPE, { _ -> cancelEdit() }),
KeyMapping(KeyBinding(A).shortcut(), { _ -> selectAll() }),
KeyMapping(KeyBinding(HOME).shortcut(), { _ -> focusFirstRow() }),
KeyMapping(KeyBinding(END).shortcut(), { _ -> focusLastRow() }),
KeyMapping(KeyBinding(BACK_SLASH).shortcut(), { _ -> clearSelection() })
).map { MappingType.Key(it) })
addDefaultMapping(inputMap, MouseMapping(MouseEvent.MOUSE_PRESSED, EventHandler { this.mousePressed(it) }))
// create OS-specific child mappings
// --- mac OS
val macInputMap = KInputMap<ListView<T>>(control)
macInputMap.interceptor = Predicate { _ -> !Utils.MAC }
addDefaultMapping(macInputMap, KeyMapping(KeyBinding(SPACE).shortcut().ctrl(), { _ -> toggleFocusOwnerSelection() }))
addDefaultChildMap(inputMap, macInputMap)
// --- all other platforms
val otherOsInputMap = KInputMap<ListView<T>>(control)
otherOsInputMap.interceptor = Predicate{ _ -> Utils.MAC }
addDefaultMapping(otherOsInputMap, KeyMapping(KeyBinding(SPACE).ctrl(), { _ -> toggleFocusOwnerSelection() }))
addDefaultChildMap(inputMap, otherOsInputMap)
// create child map for vertical listview
val verticalListInputMap = KInputMap<ListView<T>>(control)
addDefaultKeyMapping(verticalListInputMap, listOf(
KeyMapping(UP, { _ -> selectPreviousRow() }),
KeyMapping(KP_UP, { _ -> selectPreviousRow() }),
KeyMapping(DOWN, { _ -> selectNextRow() }),
KeyMapping(KP_DOWN, { _ -> selectNextRow() }),
KeyMapping(KeyBinding(UP).shift(), { _ -> alsoSelectPreviousRow() }),
KeyMapping(KeyBinding(KP_UP).shift(), { _ -> alsoSelectPreviousRow() }),
KeyMapping(KeyBinding(DOWN).shift(), { _ -> alsoSelectNextRow() }),
KeyMapping(KeyBinding(KP_DOWN).shift(), { _ -> alsoSelectNextRow() }),
KeyMapping(KeyBinding(UP).shortcut(), { _ -> focusPreviousRow() }),
KeyMapping(KeyBinding(DOWN).shortcut(), { _ -> focusNextRow() }),
KeyMapping(KeyBinding(UP).shortcut().shift(), { _ -> discontinuousSelectPreviousRow() }),
KeyMapping(KeyBinding(DOWN).shortcut().shift(), { _ -> discontinuousSelectNextRow() }),
KeyMapping(KeyBinding(HOME).shortcut().shift(), { _ -> discontinuousSelectAllToFirstRow() }),
KeyMapping(KeyBinding(END).shortcut().shift(), { _ -> discontinuousSelectAllToLastRow() })
))
addDefaultChildMap(inputMap, verticalListInputMap)
// set up other listeners
// We make this an event _filter_ so that we can determine the state
// of the shift key before the event handlers get a shot at the event.
control.addEventFilter(KeyEvent.ANY, keyEventListener)
control.itemsProperty().addListener(weakItemsListener)
if (control.items != null) {
control.items.addListener(weakItemsListListener)
}
// Fix for RT-16565
control.selectionModelProperty().addListener(weakSelectionModelListener)
if (control.selectionModel != null) {
control.selectionModel.selectedIndices.addListener(weakSelectedIndicesListener)
}
}
fun dispose() {
val control = node
CellBehaviorBase.removeAnchor(control)
control.removeEventHandler(KeyEvent.ANY, keyEventListener)
}
fun setOnFocusPreviousRow(r: Runnable) {
onFocusPreviousRow = r
}
fun setOnFocusNextRow(r: Runnable) {
onFocusNextRow = r
}
fun setOnSelectPreviousRow(r: Runnable) {
onSelectPreviousRow = r
}
fun setOnSelectNextRow(r: Runnable) {
onSelectNextRow = r
}
fun setOnMoveToFirstCell(r: Runnable) {
onMoveToFirstCell = r
}
fun setOnMoveToLastCell(r: Runnable) {
onMoveToLastCell = r
}
private fun hasAnchor(): Boolean {
return CellBehaviorBase.hasNonDefaultAnchor(node)
}
private fun mousePressed(e: MouseEvent) {
if (!e.isShiftDown && !e.isSynthesized) {
val index = node.selectionModel.selectedIndex
anchor = index
}
if (!node.isFocused && node.isFocusTraversable) {
node.requestFocus()
}
}
private fun clearSelection() {
node.selectionModel.clearSelection()
}
private fun focusFirstRow() {
val fm = node.focusModel ?: return
fm.focus(0)
if (onMoveToFirstCell != null) onMoveToFirstCell!!.run()
}
private fun focusLastRow() {
val fm = node.focusModel ?: return
fm.focus(rowCount - 1)
if (onMoveToLastCell != null) onMoveToLastCell!!.run()
}
private fun focusPreviousRow() {
val fm = node.focusModel ?: return
node.selectionModel ?: return
fm.focusPrevious()
if (!isShortcutDown || anchor == -1) {
anchor = fm.focusedIndex
}
if (onFocusPreviousRow != null) onFocusPreviousRow!!.run()
}
private fun focusNextRow() {
val fm = node.focusModel ?: return
node.selectionModel ?: return
fm.focusNext()
if (!isShortcutDown || anchor == -1) {
anchor = fm.focusedIndex
}
if (onFocusNextRow != null) onFocusNextRow!!.run()
}
private fun alsoSelectPreviousRow() {
val fm = node.focusModel ?: return
val sm = node.selectionModel ?: return
if (isShiftDown && anchor != -1) {
val newRow = fm.focusedIndex - 1
if (newRow < 0) return
var anchor = anchor
if (!hasAnchor()) {
anchor = fm.focusedIndex
}
if (sm.selectedIndices.size > 1) {
clearSelectionOutsideRange(anchor, newRow)
}
if (anchor > newRow) {
sm.selectRange(anchor, newRow - 1)
} else {
sm.selectRange(anchor, newRow + 1)
}
} else {
sm.selectPrevious()
}
onSelectPreviousRow!!.run()
}
private fun alsoSelectNextRow() {
val fm = node.focusModel ?: return
val sm = node.selectionModel ?: return
if (isShiftDown && anchor != -1) {
val newRow = fm.focusedIndex + 1
var anchor = anchor
if (!hasAnchor()) {
anchor = fm.focusedIndex
}
if (sm.selectedIndices.size > 1) {
clearSelectionOutsideRange(anchor, newRow)
}
if (anchor > newRow) {
sm.selectRange(anchor, newRow - 1)
} else {
sm.selectRange(anchor, newRow + 1)
}
} else {
sm.selectNext()
}
onSelectNextRow!!.run()
}
private fun clearSelectionOutsideRange(start: Int, end: Int) {
val sm = node.selectionModel ?: return
val min = Math.min(start, end)
val max = Math.max(start, end)
val indices = ArrayList(sm.selectedIndices)
selectionChanging = true
for (i in indices.indices) {
val index = indices[i]
if (index < min || index > max) {
sm.clearSelection(index)
}
}
selectionChanging = false
}
private fun selectPreviousRow() {
val fm = node.focusModel ?: return
val focusIndex = fm.focusedIndex
if (focusIndex <= 0) {
return
}
anchor = focusIndex - 1
node.selectionModel.clearAndSelect(focusIndex - 1)
onSelectPreviousRow!!.run()
}
private fun selectNextRow() {
val listView = node
val fm = listView.focusModel ?: return
val focusIndex = fm.focusedIndex
if (focusIndex == rowCount - 1) {
return
}
val sm = listView.selectionModel ?: return
anchor = focusIndex + 1
sm.clearAndSelect(focusIndex + 1)
if (onSelectNextRow != null) onSelectNextRow!!.run()
}
private fun selectFirstRow() {
if (rowCount > 0) {
node.selectionModel.clearAndSelect(0)
if (onMoveToFirstCell != null) onMoveToFirstCell!!.run()
}
}
private fun selectLastRow() {
node.selectionModel.clearAndSelect(rowCount - 1)
if (onMoveToLastCell != null) onMoveToLastCell!!.run()
}
private fun selectAllToFirstRow() {
val sm = node.selectionModel ?: return
val fm = node.focusModel ?: return
var leadIndex = fm.focusedIndex
if (isShiftDown) {
leadIndex = if (hasAnchor()) anchor else leadIndex
}
sm.clearSelection()
sm.selectRange(leadIndex, -1)
// RT-18413: Focus must go to first row
fm.focus(0)
if (isShiftDown) {
anchor = leadIndex
}
if (onMoveToFirstCell != null) onMoveToFirstCell!!.run()
}
private fun selectAllToLastRow() {
val sm = node.selectionModel ?: return
val fm = node.focusModel ?: return
var leadIndex = fm.focusedIndex
if (isShiftDown) {
leadIndex = if (hasAnchor()) anchor else leadIndex
}
sm.clearSelection()
sm.selectRange(leadIndex, rowCount)
if (isShiftDown) {
anchor = leadIndex
}
if (onMoveToLastCell != null) onMoveToLastCell!!.run()
}
private fun selectAll() {
val sm = node.selectionModel ?: return
sm.selectAll()
}
private fun selectAllToFocus() {
// Fix for RT-31241
val listView = node
if (listView.editingIndex >= 0) return
val sm = listView.selectionModel ?: return
val fm = listView.focusModel ?: return
val focusIndex = fm.focusedIndex
val anchor = anchor
sm.clearSelection()
val startPos = anchor
val endPos = if (anchor > focusIndex) focusIndex - 1 else focusIndex + 1
sm.selectRange(startPos, endPos)
// anchor = if (setAnchorToFocusIndex) focusIndex else anchor
}
private fun cancelEdit() {
node.edit(-1)
}
private fun activate() {
val focusedIndex = node.focusModel.focusedIndex
node.selectionModel.select(focusedIndex)
anchor = focusedIndex
// edit this row also
if (focusedIndex >= 0) {
node.edit(focusedIndex)
}
}
private fun toggleFocusOwnerSelection() {
val sm = node.selectionModel ?: return
val fm = node.focusModel ?: return
val focusedIndex = fm.focusedIndex
if (sm.isSelected(focusedIndex)) {
sm.clearSelection(focusedIndex)
fm.focus(focusedIndex)
} else {
sm.select(focusedIndex)
}
anchor = focusedIndex
}
/**************************************************************************
* Discontinuous Selection *
*/
private fun discontinuousSelectPreviousRow() {
val sm = node.selectionModel ?: return
if (sm.selectionMode != SelectionMode.MULTIPLE) {
selectPreviousRow()
return
}
val fm = node.focusModel ?: return
val focusIndex = fm.focusedIndex
val newFocusIndex = focusIndex - 1
if (newFocusIndex < 0) return
var startIndex = focusIndex
if (isShiftDown) {
startIndex = if (anchor == -1) focusIndex else anchor
}
sm.selectRange(newFocusIndex, startIndex + 1)
fm.focus(newFocusIndex)
if (onFocusPreviousRow != null) onFocusPreviousRow!!.run()
}
private fun discontinuousSelectNextRow() {
val sm = node.selectionModel ?: return
if (sm.selectionMode != SelectionMode.MULTIPLE) {
selectNextRow()
return
}
val fm = node.focusModel ?: return
val focusIndex = fm.focusedIndex
val newFocusIndex = focusIndex + 1
if (newFocusIndex >= rowCount) return
var startIndex = focusIndex
if (isShiftDown) {
startIndex = if (anchor == -1) focusIndex else anchor
}
sm.selectRange(startIndex, newFocusIndex + 1)
fm.focus(newFocusIndex)
if (onFocusNextRow != null) onFocusNextRow!!.run()
}
private fun discontinuousSelectAllToFirstRow() {
val sm = node.selectionModel ?: return
val fm = node.focusModel ?: return
val index = fm.focusedIndex
sm.selectRange(0, index)
fm.focus(0)
if (onMoveToFirstCell != null) onMoveToFirstCell!!.run()
}
private fun discontinuousSelectAllToLastRow() {
val sm = node.selectionModel ?: return
val fm = node.focusModel ?: return
val index = fm.focusedIndex + 1
sm.selectRange(index, rowCount)
if (onMoveToLastCell != null) onMoveToLastCell!!.run()
}
protected fun addDefaultKeyMapping(i: KInputMap<ListView<T>>, newMapping: List<KeyMapping>) {
addDefaultMapping(i, newMapping.map { MappingType.Key(it) })
}
protected fun addDefaultMapping(i: KInputMap<ListView<T>>, newMapping: KeyMapping) {
addDefaultMapping(i, listOf(MappingType.Key(newMapping)))
}
protected fun addDefaultMapping(i: KInputMap<ListView<T>>, newMapping: MouseMapping) {
addDefaultMapping(i, listOf(MappingType.Mouse(newMapping)))
}
protected fun addDefaultMapping(inputMap: KInputMap<ListView<T>>, newMapping: List<MappingType>) {
// make a copy of the existing mappings, so we only check against those
val existingMappings = inputMap.mappings.toList()
for (mapping in newMapping) {
// check if a mapping already exists, and if so, do not add this mapping
// TODO this is insufficient as we need to check entire InputMap hierarchy
if (existingMappings.contains(mapping)) continue
inputMap.mappings.add(mapping)
installedDefaultMappings.add(mapping)
}
}
protected fun addDefaultChildMap(
parentInputMap: KInputMap<ListView<T>>,
newChildInputMap: KInputMap<ListView<T>>) {
parentInputMap.childInputMaps.add(newChildInputMap)
childInputMapDisposalHandlers.add(Runnable{ parentInputMap.childInputMaps.remove(newChildInputMap) })
}
}
| gpl-3.0 | de484c52887edbdb3cc3b7ca0145a82e | 31.587613 | 125 | 0.599268 | 4.652361 | false | false | false | false |
quran/quran_android | feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/sheikhdownload/DownloadProgressDialog.kt | 2 | 2878 | package com.quran.mobile.feature.downloadmanager.ui.sheikhdownload
import android.content.Context
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.material.AlertDialog
import androidx.compose.material.Text
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.quran.mobile.feature.downloadmanager.R
import com.quran.mobile.feature.downloadmanager.model.sheikhdownload.NoProgress
import com.quran.mobile.feature.downloadmanager.model.sheikhdownload.SuraDownloadStatusEvent
import kotlinx.coroutines.flow.Flow
import java.text.DecimalFormat
@Composable
fun DownloadProgressDialog(
progressEvents: Flow<SuraDownloadStatusEvent.Progress>,
onCancel: () -> Unit
) {
val progressState = progressEvents.collectAsState(NoProgress)
val currentEvent = progressState.value
AlertDialog(
title = {
Text(
text = stringResource(id = R.string.downloading_title),
modifier = Modifier.padding(top = 16.dp)
)
},
text = {
val progress = if (currentEvent.progress == -1) 0 else currentEvent.progress
Column {
Text(
currentEvent.asMessage(LocalContext.current),
modifier = Modifier.padding(bottom = 8.dp, end = 16.dp)
)
LinearProgressIndicator(progress = (progress / 100.0f))
}
},
buttons = {
Row(modifier = Modifier.padding(horizontal = 16.dp)) {
Spacer(modifier = Modifier.weight(1f))
TextButton(onClick = onCancel) {
Text(text = stringResource(id = com.quran.mobile.common.ui.core.R.string.cancel))
}
}
},
onDismissRequest = onCancel
)
}
private fun SuraDownloadStatusEvent.Progress.asMessage(context: Context): String {
val decimalFormat = DecimalFormat("###.00")
val megabyte = 1024 * 1024
val downloaded = context.getString(
R.string.download_amount_in_megabytes,
decimalFormat.format(1.0 * downloadedAmount / megabyte)
)
val total = context.getString(
R.string.download_amount_in_megabytes,
decimalFormat.format(1.0 * totalAmount / megabyte)
)
return if (sura < 1) {
// no sura, no ayah
context.getString(R.string.download_progress, downloaded, total)
} else if (ayah <= 0) {
// sura, no ayah
context.getString(R.string.download_sura_progress, downloaded, total, sura)
} else {
// sura and ayah
context.getString(R.string.download_sura_ayah_progress, sura, ayah)
}
}
| gpl-3.0 | 2818d21b2852bdd7d4b2d6f54b642714 | 33.261905 | 92 | 0.735233 | 4.093883 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | benchmarks/commonMain/src/benchmarks/immutableList/builder/RemoveAll.kt | 1 | 3708 | /*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package benchmarks.immutableList.builder
import benchmarks.*
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.benchmark.*
import kotlin.random.Random
@State(Scope.Benchmark)
open class RemoveAll {
@Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000, BM_10000000)
var size: Int = 0
@Param(IP_100, IP_99_09, IP_95, IP_70, IP_50, IP_30, IP_0)
var immutablePercentage: Double = 0.0
// Results of the following benchmarks do not indicate memory or time spent per operation,
// however regressions there do indicate changes.
//
// The benchmarks measure (mean time and memory spent per `add` operation) + (time and memory spent on `removeAll` operation) / size.
//
// Expected time: [Add.addLast] + nearly constant.
// Expected memory: [Add.addLast] + nearly constant.
/**
* Adds [size] elements to an empty persistent list builder
* and then removes all of them using `removeAll(elements)` operation.
*/
@Benchmark
fun addAndRemoveAll_All(): Boolean {
val builder = persistentListBuilderAddIndexes()
val elementsToRemove = List(size) { it }
return builder.removeAll(elementsToRemove)
}
/**
* Adds [size] elements to an empty persistent list builder
* and then removes half of them using `removeAll(elements)` operation.
*/
@Benchmark
fun addAndRemoveAll_RandomHalf(): Boolean {
val builder = persistentListBuilderAddIndexes()
val elementsToRemove = randomIndexes(size / 2)
return builder.removeAll(elementsToRemove)
}
/**
* Adds [size] elements to an empty persistent list builder
* and then removes 10 of them using `removeAll(elements)` operation.
*/
@Benchmark
fun addAndRemoveAll_RandomTen(): Boolean {
val builder = persistentListBuilderAddIndexes()
val elementsToRemove = randomIndexes(10)
return builder.removeAll(elementsToRemove)
}
/**
* Adds [size] elements to an empty persistent list builder
* and then removes last [tailSize] of them using `removeAll(elements)` operation.
*/
@Benchmark
fun addAndRemoveAll_Tail(): Boolean {
val builder = persistentListBuilderAddIndexes()
val elementsToRemove = List(tailSize()) { size - 1 - it }
return builder.removeAll(elementsToRemove)
}
/**
* Adds [size] elements to an empty persistent list builder
* and then removes 10 non-existing elements using `removeAll(elements)` operation.
*/
@Benchmark
fun addAndRemoveAll_NonExisting(): Boolean {
val builder = persistentListBuilderAddIndexes()
val elementsToRemove = randomIndexes(10).map { size + it }
return builder.removeAll(elementsToRemove)
}
private fun persistentListBuilderAddIndexes(): PersistentList.Builder<Int> {
val immutableSize = immutableSize(size, immutablePercentage)
var list = persistentListOf<Int>()
for (i in 0 until immutableSize) {
list = list.add(i)
}
val builder = list.builder()
for (i in immutableSize until size) {
builder.add(i)
}
return builder
}
private fun randomIndexes(count: Int): List<Int> {
return List(count) { Random.nextInt(size) }
}
private fun tailSize(): Int {
val bufferSize = 32
return (size and (bufferSize - 1)).let { if (it == 0) bufferSize else it }
}
} | apache-2.0 | d5bf989c873abc888d5e67648756ad71 | 33.990566 | 137 | 0.666936 | 4.393365 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | benchmarks/commonMain/src/benchmarks/immutableList/builder/AddAll.kt | 1 | 4530 | /*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package benchmarks.immutableList.builder
import benchmarks.*
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.benchmark.*
@State(Scope.Benchmark)
open class AddAll {
@Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000, BM_10000000)
var size: Int = 0
@Param(IP_100, IP_99_09, IP_95, IP_70, IP_50, IP_30, IP_0)
var immutablePercentage: Double = 0.0
private var listToAdd = emptyList<String>()
@Setup
fun prepare() {
listToAdd = List(size) { "another element" }
}
// Results of the following benchmarks do not indicate memory or time spent per operation,
// however regressions there do indicate changes.
//
// The benchmarks measure mean time and memory spent per added element.
//
// Expected time: nearly constant.
// Expected memory: nearly constant.
/**
* Adds [size] elements to an empty persistent list builder using `addAll` operation.
*/
@Benchmark
fun addAllLast(): PersistentList.Builder<String> {
val builder = persistentListOf<String>().builder()
builder.addAll(listToAdd)
return builder
}
/**
* Adds `size / 2` elements to an empty persistent list builder
* and then adds `size - size / 2` elements using `addAll` operation.
*/
@Benchmark
fun addAllLast_Half(): PersistentList.Builder<String> {
val initialSize = size / 2
val subListToAdd = listToAdd.subList(0, size - initialSize) // assuming subList creation is neglectable
val builder = persistentListBuilderAdd(initialSize, immutablePercentage)
builder.addAll(subListToAdd)
return builder
}
/**
* Adds `size - size / 3` elements to an empty persistent list builder
* and then adds `size / 3` elements using `addAll` operation.
*/
@Benchmark
fun addAllLast_OneThird(): PersistentList.Builder<String> {
val initialSize = size - size / 3
val subListToAdd = listToAdd.subList(0, size - initialSize)
val builder = persistentListBuilderAdd(initialSize, immutablePercentage)
builder.addAll(subListToAdd)
return builder
}
/**
* Adds `size / 2` elements to an empty persistent list builder
* and then inserts `size - size / 2` elements at the beginning using `addAll` operation.
*/
@Benchmark
fun addAllFirst_Half(): PersistentList.Builder<String> {
val initialSize = size / 2
val subListToAdd = listToAdd.subList(0, size - initialSize)
val builder = persistentListBuilderAdd(initialSize, immutablePercentage)
builder.addAll(0, subListToAdd)
return builder
}
/**
* Adds `size - size / 3` elements to an empty persistent list builder
* and then inserts `size / 3` elements at the beginning using `addAll` operation.
*/
@Benchmark
fun addAllFirst_OneThird(): PersistentList.Builder<String> {
val initialSize = size - size / 3
val subListToAdd = listToAdd.subList(0, size - initialSize)
val builder = persistentListBuilderAdd(initialSize, immutablePercentage)
builder.addAll(0, subListToAdd)
return builder
}
/**
* Adds `size / 2` elements to an empty persistent list builder
* and then inserts `size - size / 2` elements at the middle using `addAll` operation.
*/
@Benchmark
fun addAllMiddle_Half(): PersistentList.Builder<String> {
val initialSize = size / 2
val index = initialSize / 2
val subListToAdd = listToAdd.subList(0, size - initialSize)
val builder = persistentListBuilderAdd(initialSize, immutablePercentage)
builder.addAll(index, subListToAdd)
return builder
}
/**
* Adds `size - size / 3` elements to an empty persistent list builder
* and then inserts `size / 3` elements at the middle using `addAll` operation.
*/
@Benchmark
fun addAllMiddle_OneThird(): PersistentList.Builder<String> {
val initialSize = size - size / 3
val index = initialSize / 2
val subListToAdd = listToAdd.subList(0, size - initialSize)
val builder = persistentListBuilderAdd(initialSize, immutablePercentage)
builder.addAll(index, subListToAdd)
return builder
}
} | apache-2.0 | a386d484261303ac9c75280d0c96d195 | 33.587786 | 111 | 0.666225 | 4.364162 | false | false | false | false |
firebase/quickstart-android | storage/app/src/main/java/com/google/firebase/quickstart/firebasestorage/kotlin/MainActivity.kt | 1 | 9650 | package com.google.firebase.quickstart.firebasestorage.kotlin
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.firebasestorage.R
import com.google.firebase.quickstart.firebasestorage.databinding.ActivityMainBinding
import java.util.Locale
/**
* Activity to upload and download photos from Firebase Storage.
*
* See [MyUploadService] for upload example.
* See [MyDownloadService] for download example.
*/
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var broadcastReceiver: BroadcastReceiver
private lateinit var auth: FirebaseAuth
private var downloadUrl: Uri? = null
private var fileUri: Uri? = null
private lateinit var binding: ActivityMainBinding
private lateinit var cameraIntent: ActivityResultLauncher<Array<String>>;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize Firebase Auth
auth = Firebase.auth
// Click listeners
with(binding) {
buttonCamera.setOnClickListener(this@MainActivity)
buttonSignIn.setOnClickListener(this@MainActivity)
buttonDownload.setOnClickListener(this@MainActivity)
}
cameraIntent = registerForActivityResult(ActivityResultContracts.OpenDocument()) { fileUri ->
if (fileUri != null) {
uploadFromUri(fileUri)
} else {
Log.w(TAG, "File URI is null")
}
}
// Local broadcast receiver
broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive:$intent")
hideProgressBar()
when (intent.action) {
MyDownloadService.DOWNLOAD_COMPLETED -> {
// Get number of bytes downloaded
val numBytes = intent.getLongExtra(MyDownloadService.EXTRA_BYTES_DOWNLOADED, 0)
// Alert success
showMessageDialog(getString(R.string.success), String.format(Locale.getDefault(),
"%d bytes downloaded from %s",
numBytes,
intent.getStringExtra(MyDownloadService.EXTRA_DOWNLOAD_PATH)))
}
MyDownloadService.DOWNLOAD_ERROR ->
// Alert failure
showMessageDialog("Error", String.format(Locale.getDefault(),
"Failed to download from %s",
intent.getStringExtra(MyDownloadService.EXTRA_DOWNLOAD_PATH)))
MyUploadService.UPLOAD_COMPLETED, MyUploadService.UPLOAD_ERROR -> onUploadResultIntent(intent)
}
}
}
// Restore instance state
savedInstanceState?.let {
fileUri = it.getParcelable(KEY_FILE_URI)
downloadUrl = it.getParcelable(KEY_DOWNLOAD_URL)
}
onNewIntent(intent)
}
public override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
// Check if this Activity was launched by clicking on an upload notification
if (intent.hasExtra(MyUploadService.EXTRA_DOWNLOAD_URL)) {
onUploadResultIntent(intent)
}
}
public override fun onStart() {
super.onStart()
updateUI(auth.currentUser)
// Register receiver for uploads and downloads
val manager = LocalBroadcastManager.getInstance(this)
manager.registerReceiver(broadcastReceiver, MyDownloadService.intentFilter)
manager.registerReceiver(broadcastReceiver, MyUploadService.intentFilter)
}
public override fun onStop() {
super.onStop()
// Unregister download receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
}
public override fun onSaveInstanceState(out: Bundle) {
super.onSaveInstanceState(out)
out.putParcelable(KEY_FILE_URI, fileUri)
out.putParcelable(KEY_DOWNLOAD_URL, downloadUrl)
}
private fun uploadFromUri(uploadUri: Uri) {
Log.d(TAG, "uploadFromUri:src: $uploadUri")
// Save the File URI
fileUri = uploadUri
// Clear the last download, if any
updateUI(auth.currentUser)
downloadUrl = null
// Start MyUploadService to upload the file, so that the file is uploaded
// even if this Activity is killed or put in the background
startService(Intent(this, MyUploadService::class.java)
.putExtra(MyUploadService.EXTRA_FILE_URI, uploadUri)
.setAction(MyUploadService.ACTION_UPLOAD))
// Show loading spinner
showProgressBar(getString(R.string.progress_uploading))
}
private fun beginDownload() {
fileUri?.let {
// Get path
val path = "photos/" + it.lastPathSegment
// Kick off MyDownloadService to download the file
val intent = Intent(this, MyDownloadService::class.java)
.putExtra(MyDownloadService.EXTRA_DOWNLOAD_PATH, path)
.setAction(MyDownloadService.ACTION_DOWNLOAD)
startService(intent)
// Show loading spinner
showProgressBar(getString(R.string.progress_downloading))
}
}
private fun launchCamera() {
Log.d(TAG, "launchCamera")
// Pick an image from storage
cameraIntent.launch(arrayOf("image/*"))
}
private fun signInAnonymously() {
// Sign in anonymously. Authentication is required to read or write from Firebase Storage.
showProgressBar(getString(R.string.progress_auth))
auth.signInAnonymously()
.addOnSuccessListener(this) { authResult ->
Log.d(TAG, "signInAnonymously:SUCCESS")
hideProgressBar()
updateUI(authResult.user)
}
.addOnFailureListener(this) { exception ->
Log.e(TAG, "signInAnonymously:FAILURE", exception)
hideProgressBar()
updateUI(null)
}
}
private fun onUploadResultIntent(intent: Intent) {
// Got a new intent from MyUploadService with a success or failure
downloadUrl = intent.getParcelableExtra(MyUploadService.EXTRA_DOWNLOAD_URL)
fileUri = intent.getParcelableExtra(MyUploadService.EXTRA_FILE_URI)
updateUI(auth.currentUser)
}
private fun updateUI(user: FirebaseUser?) {
with(binding) {
// Signed in or Signed out
if (user != null) {
layoutSignin.visibility = View.GONE
layoutStorage.visibility = View.VISIBLE
} else {
layoutSignin.visibility = View.VISIBLE
layoutStorage.visibility = View.GONE
}
// Download URL and Download button
if (downloadUrl != null) {
pictureDownloadUri.text = downloadUrl.toString()
layoutDownload.visibility = View.VISIBLE
} else {
pictureDownloadUri.text = null
layoutDownload.visibility = View.GONE
}
}
}
private fun showMessageDialog(title: String, message: String) {
val ad = AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.create()
ad.show()
}
private fun showProgressBar(progressCaption: String) {
with(binding) {
caption.text = progressCaption
progressBar.visibility = View.VISIBLE
}
}
private fun hideProgressBar() {
with(binding) {
caption.text = ""
progressBar.visibility = View.INVISIBLE
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val i = item.itemId
return if (i == R.id.action_logout) {
FirebaseAuth.getInstance().signOut()
updateUI(null)
true
} else {
super.onOptionsItemSelected(item)
}
}
override fun onClick(v: View) {
when (v.id) {
R.id.buttonCamera -> launchCamera()
R.id.buttonSignIn -> signInAnonymously()
R.id.buttonDownload -> beginDownload()
}
}
companion object {
private const val TAG = "Storage#MainActivity"
private const val KEY_FILE_URI = "key_file_uri"
private const val KEY_DOWNLOAD_URL = "key_download_url"
}
}
| apache-2.0 | 05e47612358964fd4935682e28ff6cd6 | 34.090909 | 114 | 0.622383 | 5.258856 | false | false | false | false |
jrenner/kotlin-voxel | core/src/main/kotlin/org/jrenner/learngl/HUD.kt | 1 | 2602 | package org.jrenner.learngl
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.StringBuilder
import org.jrenner.RenStringBuilder
import org.jrenner.learngl.utils.plus
class HUD {
val stage = Stage()
val table = Table()
val info: Label = Label("Info", skin)
init {
refresh()
}
fun refresh() {
table.clear()
table.setFillParent(true)
table.align(Align.left or Align.top)
fun label(act: Actor) = table.add(act).align(Align.left or Align.top).row()
label(info)
stage.addActor(table)
}
var accumulatedTime = 0f
fun isReadyForUpdate(): Boolean {
val interval = 0.1f
if (accumulatedTime >= interval) {
accumulatedTime -= interval
return true
}
return false
}
val sb = RenStringBuilder()
fun update(dt: Float) {
if (isReadyForUpdate()) {
sb.delete(0, sb.sbLength())
sb + "FPS: " + Gdx.graphics.getFramesPerSecond().toString()
sb + "\nMemory\n\tJava: ${Gdx.app.getJavaHeap() / 1000000} MB\n\tNative: ${Gdx.app.getNativeHeap() / 1000000} MB"
sb + "\nChunks: ${world.chunks.size}, Rendered: ${view.chunksRendered}"
sb + "\nChunkQueue: ${world.chunkCreationQueue.size}"
val c = view.camera.position
sb + "\nChunks, created: ${world.chunksCreated}, removed: ${world.chunksRemoved}"
val camElev = world.getElevation(c.x, c.z)
sb + "\nCamera: %.1f, %.1f %.1f\n\tAltitude above ground: $camElev".format(c.x, c.y, c.z)
val moveMode = if (view.walkingEnabled) "Walking" else "Flying"
sb + "\nMovement mode: ${moveMode}"
sb + "\nView Distance: ${View.maxViewDist}"
sb + "\nWARNING: \nHigh view distances require\nexponentially large amounts of memory"
sb + "\n\nCONTROLS:\n\tW, A, S, D to move\n\tClick and hold mouse to look around\n\t- and + to change view distance"
sb + "\nSpace to switch flying/walking"
info.setText(sb.toString())
}
}
var enabled = true
fun render(dt: Float) {
accumulatedTime += dt
if (enabled) {
update(dt)
stage.act(dt)
stage.draw()
}
}
} | apache-2.0 | 8fb17b04a97c911835ae18256c861a18 | 32.72 | 128 | 0.583782 | 3.680339 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/locus/api/mapper/ImageDataConverter.kt | 1 | 607 | package locus.api.mapper
import androidx.annotation.Nullable
import com.arcao.geocaching4locus.data.api.model.Image
import locus.api.objects.geocaching.GeocachingImage
class ImageDataConverter {
@Nullable
fun createLocusGeocachingImage(@Nullable imageData: Image?): GeocachingImage? {
if (imageData == null)
return null
return GeocachingImage().apply {
name = imageData.description.orEmpty()
description = imageData.description.orEmpty()
thumbUrl = imageData.thumbnailUrl.orEmpty()
url = imageData.url
}
}
}
| gpl-3.0 | 97d69228d0abd7205498dae43d109f25 | 29.35 | 83 | 0.682043 | 4.779528 | false | false | false | false |
web3j/quorum | src/integration-test/kotlin/org/web3j/quorum/Params.kt | 1 | 5098 | /*
* Copyright 2019 Web3 Labs LTD.
*
* 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.web3j.quorum
import okhttp3.OkHttpClient
import org.web3j.protocol.http.HttpService
import org.web3j.quorum.enclave.Constellation
import org.web3j.quorum.enclave.Tessera
import org.web3j.quorum.enclave.protocol.EnclaveService
import java.io.File
import java.util.Base64
/**
* Common parameters for unit tests.
*/
// ASCII base 64 encoded payload
val PAYLOAD: String = Base64.getEncoder().encodeToString("message payload1".toByteArray())
val localhost = "http://localhost"
// Tessera Node configuration
val quorum1T = Node(
"0xed9d02e382b34818e88b88a309c7fe71e65f419d",
Arrays.asList(
"/+UuD63zItL1EbjxkKUljMgG8Z1w0AJ8pNOR4iq2yQc="),
"http://localhost:22001")
val quorum2T = Node(
"0xca843569e3427144cead5e4d5999a3d0ccf92b8e",
Arrays.asList(
"yGcjkFyZklTTXrn8+WIkYwicA2EGBn9wZFkctAad4X0="),
"http://localhost:22002")
val quorum3T = Node(
"0x0fbdc686b912d7722dc86510934589e0aaf3b55a",
Arrays.asList(
"jP4f+k/IbJvGyh0LklWoea2jQfmLwV53m9XoHVS4NSU="),
"http://localhost:22003")
val quorum4T = Node(
"0x9186eb3d20cbd1f5f992a950d808c4495153abd5",
Arrays.asList(
"giizjhZQM6peq52O7icVFxdTmTYinQSUsvyhXzgZqkE="),
"http://localhost:22004")
val nodesT = Arrays.asList(
quorum1T, quorum2T, quorum3T, quorum4T)
val quorumTessera = Quorum.build(HttpService(quorum1T.url))
val tessera = Arrays.asList(Tessera(EnclaveService(localhost, 8090), quorumTessera),
Tessera(EnclaveService(localhost, 8091), Quorum.build(HttpService(quorum2T.url))),
Tessera(EnclaveService(localhost, 8092), Quorum.build(HttpService(quorum3T.url))),
Tessera(EnclaveService(localhost, 8093), Quorum.build(HttpService(quorum4T.url))))
val upCheckTessera = Tessera(EnclaveService(localhost, 8080), quorumTessera)
// Constellation configuration parameters
private val quorum1C = Node(
"0xed9d02e382b34818e88b88a309c7fe71e65f419d",
Arrays.asList(
"BULeR8JyUWhiuuCMU/HLA0Q5pzkYT+cHII3ZKBey3Bo="),
"http://localhost:22001")
private val quorum2C = Node(
"0xca843569e3427144cead5e4d5999a3d0ccf92b8e",
Arrays.asList(
"QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc="),
"http://localhost:22002")
private val quorum3C = Node(
"0x0fbdc686b912d7722dc86510934589e0aaf3b55a",
Arrays.asList(
"1iTZde/ndBHvzhcl7V68x44Vx7pl8nwx9LqnM/AfJUg="),
"http://localhost:22003")
private val quorum4C = Node(
"0x9186eb3d20cbd1f5f992a950d808c4495153abd5",
Arrays.asList(
"oNspPPgszVUFw0qmGFfWwh1uxVUXgvBxleXORHj07g8="),
"http://localhost:22004")
val nodesC = Arrays.asList(
quorum1C, quorum2C, quorum3C, quorum4C)
val constellationIpcPath1 = "/Users/sebastianraba/Desktop/work/web3js-quorum/constellation/data/constellation.ipc"
val constellationIpcPath2 = "/Users/sebastianraba/Desktop/work/web3js-quorum/constellation/data1/constellation.ipc"
val constellationIpcPath3 = "/Users/sebastianraba/Desktop/work/web3js-quorum/constellation/data2/constellation.ipc"
val constellationIpcPath4 = "/Users/sebastianraba/Desktop/work/web3js-quorum/constellation/data3/constellation.ipc"
val client = OkHttpClient.Builder()
.socketFactory(UnixDomainSocketFactory(File(constellationIpcPath1)))
.build()
val client1 = OkHttpClient.Builder()
.socketFactory(UnixDomainSocketFactory(File(constellationIpcPath2)))
.build()
val client2 = OkHttpClient.Builder()
.socketFactory(UnixDomainSocketFactory(File(constellationIpcPath3)))
.build()
val client3 = OkHttpClient.Builder()
.socketFactory(UnixDomainSocketFactory(File(constellationIpcPath4)))
.build()
val constellation = Arrays.asList(Constellation(EnclaveService("http://localhost", 9020, client), Quorum.build(HttpService(quorum1C.url))),
Constellation(EnclaveService("http://localhost", 9020, client1), Quorum.build(HttpService(quorum2C.url))),
Constellation(EnclaveService("http://localhost", 9020, client2), Quorum.build(HttpService(quorum3C.url))),
Constellation(EnclaveService("http://localhost", 9020, client3), Quorum.build(HttpService(quorum4C.url))))
// ASCII base 64 encoded public keys for our transaction managers
const val TM1_PUBLIC_KEY = "BULeR8JyUWhiuuCMU/HLA0Q5pzkYT+cHII3ZKBey3Bo="
const val TM2_PUBLIC_KEY = "QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc="
| apache-2.0 | 1b7c1fd396cbc376a72e2c23b18fc314 | 42.948276 | 139 | 0.735975 | 2.955362 | false | false | false | false |
esafirm/android-image-picker | sample/src/main/java/com/esafirm/sample/MainFragment.kt | 1 | 1681 | package com.esafirm.sample
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.esafirm.imagepicker.features.*
import com.esafirm.sample.databinding.FragmentMainBinding
class MainFragment : Fragment(R.layout.fragment_main) {
private lateinit var binding: FragmentMainBinding
private val imagePickerLauncher = registerImagePicker {
val firstImage = it.firstOrNull() ?: return@registerImagePicker
Glide.with(binding.imgFragment)
.load(firstImage.uri)
.into(binding.imgFragment)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentMainBinding.bind(view)
binding.buttonPickFragment.setOnClickListener {
imagePickerLauncher.launch(
ImagePickerConfig {
mode = ImagePickerMode.SINGLE
returnMode = ReturnMode.ALL // set whether pick action or camera action should return immediate result or not. Only works in single mode for image picker
isFolderMode = true // set folder mode (false by default)
folderTitle = "Folder" // folder selection title
imageTitle = "Tap to select" // image selection title
doneButtonText = "DONE" // done button text
}
)
}
binding.buttonClose.setOnClickListener {
parentFragmentManager.beginTransaction()
.remove(this@MainFragment)
.commitAllowingStateLoss()
}
}
} | mit | 48ef245b4068435ac2570dc0dbfc00b1 | 36.377778 | 173 | 0.653778 | 5.353503 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/repository/ArtfulExtensions.kt | 2 | 666 | package com.lasthopesoftware.bluewater.repository
import com.namehillsoftware.artful.Artful
import com.namehillsoftware.handoff.promises.Promise
inline fun <reified T> Artful.fetchFirst(): T = fetchFirst(T::class.java)
inline fun <reified T> Artful.fetch(): List<T> = fetch(T::class.java)
inline fun <reified T> Promise<Artful>.promiseFirst(): Promise<T> =
then { it.fetchFirst(T::class.java) }
inline fun <reified T> Artful.promiseFirst(): Promise<T> =
DatabasePromise { fetchFirst(T::class.java) }
fun Promise<Artful>.promiseExecution(): Promise<Long> =
then { it.execute() }
fun Artful.promiseExecution(): Promise<Long> =
DatabasePromise { execute() }
| lgpl-3.0 | a07e73c822ef4c40d694425f035e50aa | 32.3 | 73 | 0.749249 | 3.313433 | false | false | false | false |
mcxiaoke/kotlin-koi | core/src/main/kotlin/com/mcxiaoke/koi/ext/SystemService.kt | 1 | 7653 | package com.mcxiaoke.koi.ext
/**
* User: mcxiaoke
* Date: 16/1/26
* Time: 17:35
*/
import android.accounts.AccountManager
import android.annotation.TargetApi
import android.app.*
import android.app.admin.DevicePolicyManager
import android.app.job.JobScheduler
import android.appwidget.AppWidgetManager
import android.bluetooth.BluetoothAdapter
import android.content.ClipboardManager
import android.content.Context
import android.content.RestrictionsManager
import android.content.pm.LauncherApps
import android.hardware.ConsumerIrManager
import android.hardware.SensorManager
import android.hardware.camera2.CameraManager
import android.hardware.display.DisplayManager
import android.hardware.input.InputManager
import android.hardware.usb.UsbManager
import android.location.LocationManager
import android.media.AudioManager
import android.media.MediaRouter
import android.media.projection.MediaProjectionManager
import android.media.session.MediaSessionManager
import android.media.tv.TvInputManager
import android.net.ConnectivityManager
import android.net.nsd.NsdManager
import android.net.wifi.WifiManager
import android.net.wifi.p2p.WifiP2pManager
import android.nfc.NfcManager
import android.os.*
import android.os.storage.StorageManager
import android.print.PrintManager
import android.service.wallpaper.WallpaperService
import android.telephony.TelephonyManager
import android.view.LayoutInflater
import android.view.WindowManager
import android.view.accessibility.AccessibilityManager
import android.view.accessibility.CaptioningManager
import android.view.inputmethod.InputMethodManager
import android.view.textservice.TextServicesManager
fun Context.getAccessibilityManager(): AccessibilityManager =
getSystemServiceAs(Context.ACCESSIBILITY_SERVICE)
fun Context.getAccountManager(): AccountManager =
getSystemServiceAs(Context.ACCOUNT_SERVICE)
fun Context.getActivityManager(): ActivityManager =
getSystemServiceAs(Context.ACTIVITY_SERVICE)
fun Context.getAlarmManager(): AlarmManager =
getSystemServiceAs(Context.ALARM_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getAppWidgetManager(): AppWidgetManager =
getSystemServiceAs(Context.APPWIDGET_SERVICE)
@TargetApi(Build.VERSION_CODES.KITKAT)
fun Context.getAppOpsManager(): AppOpsManager =
getSystemServiceAs(Context.APP_OPS_SERVICE)
fun Context.getAudioManager(): AudioManager =
getSystemServiceAs(Context.AUDIO_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getBatteryManager(): BatteryManager =
getSystemServiceAs(Context.BATTERY_SERVICE)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
fun Context.getBluetoothAdapter(): BluetoothAdapter =
getSystemServiceAs(Context.BLUETOOTH_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getCameraManager(): CameraManager =
getSystemServiceAs(Context.CAMERA_SERVICE)
@TargetApi(Build.VERSION_CODES.KITKAT)
fun Context.getCaptioningManager(): CaptioningManager =
getSystemServiceAs(Context.CAPTIONING_SERVICE)
fun Context.getClipboardManager(): ClipboardManager =
getSystemServiceAs(Context.CLIPBOARD_SERVICE)
fun Context.getConnectivityManager(): ConnectivityManager =
getSystemServiceAs(Context.CONNECTIVITY_SERVICE)
@TargetApi(Build.VERSION_CODES.KITKAT)
fun Context.getConsumerIrManager(): ConsumerIrManager =
getSystemServiceAs(Context.CONSUMER_IR_SERVICE)
fun Context.getDevicePolicyManager(): DevicePolicyManager =
getSystemServiceAs(Context.DEVICE_POLICY_SERVICE)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
fun Context.getDisplayManager(): DisplayManager =
getSystemServiceAs(Context.DISPLAY_SERVICE)
fun Context.getDownloadManager(): DownloadManager =
getSystemServiceAs(Context.DOWNLOAD_SERVICE)
fun Context.getDropBoxManager(): DropBoxManager =
getSystemServiceAs(Context.DROPBOX_SERVICE)
fun Context.getInputMethodManager(): InputMethodManager =
getSystemServiceAs(Context.INPUT_METHOD_SERVICE)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
fun Context.getInputManager(): InputManager =
getSystemServiceAs(Context.INPUT_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getJobScheduler(): JobScheduler =
getSystemServiceAs(Context.JOB_SCHEDULER_SERVICE)
fun Context.getKeyguardManager(): KeyguardManager =
getSystemServiceAs(Context.KEYGUARD_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getLauncherApps(): LauncherApps =
getSystemServiceAs(Context.LAUNCHER_APPS_SERVICE)
fun Context.getLayoutService(): LayoutInflater =
getSystemServiceAs(Context.LAYOUT_INFLATER_SERVICE)
fun Context.getLocationManager(): LocationManager =
getSystemServiceAs(Context.LOCATION_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getMediaProjectionManager(): MediaProjectionManager =
getSystemServiceAs(Context.MEDIA_PROJECTION_SERVICE)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
fun Context.getMediaRouter(): MediaRouter =
getSystemServiceAs(Context.MEDIA_ROUTER_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getMediaSessionManager(): MediaSessionManager =
getSystemServiceAs(Context.MEDIA_SESSION_SERVICE)
fun Context.getNfcManager(): NfcManager =
getSystemServiceAs(Context.NFC_SERVICE)
fun Context.getNotificationManager(): NotificationManager =
getSystemServiceAs(Context.NOTIFICATION_SERVICE)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
fun Context.getNsdManager(): NsdManager =
getSystemServiceAs(Context.NSD_SERVICE)
fun Context.getPowerManager(): PowerManager =
getSystemServiceAs(Context.POWER_SERVICE)
@TargetApi(Build.VERSION_CODES.KITKAT)
fun Context.getPrintManager(): PrintManager =
getSystemServiceAs(Context.PRINT_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getRestrictionsManager(): RestrictionsManager =
getSystemServiceAs(Context.RESTRICTIONS_SERVICE)
fun Context.getSearchManager(): SearchManager =
getSystemServiceAs(Context.SEARCH_SERVICE)
fun Context.getSensorManager(): SensorManager =
getSystemServiceAs(Context.SENSOR_SERVICE)
fun Context.getStorageManager(): StorageManager =
getSystemServiceAs(Context.STORAGE_SERVICE)
fun Context.getTelephonyManager(): TelephonyManager =
getSystemServiceAs(Context.TELEPHONY_SERVICE)
fun Context.getTextServicesManager(): TextServicesManager =
getSystemServiceAs(Context.TEXT_SERVICES_MANAGER_SERVICE)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun Context.getTvInputManager(): TvInputManager =
getSystemServiceAs(Context.TV_INPUT_SERVICE)
fun Context.getUiModeManager(): UiModeManager =
getSystemServiceAs(Context.UI_MODE_SERVICE)
fun Context.getUsbManager(): UsbManager =
getSystemServiceAs(Context.USB_SERVICE)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
fun Context.getUserManager(): UserManager =
getSystemServiceAs(Context.USER_SERVICE)
fun Context.getVibrator(): Vibrator =
getSystemServiceAs(Context.VIBRATOR_SERVICE)
fun Context.getWallpaperService(): WallpaperService =
getSystemServiceAs(Context.WALLPAPER_SERVICE)
fun Context.getWifiP2pManager(): WifiP2pManager =
getSystemServiceAs(Context.WIFI_P2P_SERVICE)
fun Context.getWifiManager(): WifiManager =
getSystemServiceAs(Context.WIFI_SERVICE)
fun Context.getWindowService(): WindowManager =
getSystemServiceAs(Context.WINDOW_SERVICE)
@Suppress("UNCHECKED_CAST")
fun <T> Context.getSystemServiceAs(serviceName: String): T =
this.getSystemService(serviceName) as T
| apache-2.0 | 3dd658856f8ca9c807f05fcd66ecd105 | 34.595349 | 65 | 0.80243 | 4.649453 | false | false | false | false |
JetBrains/resharper-unity | rider/buildSrc/src/main/kotlin/com/jetbrains/rider/plugins/gradle/tasks/GenerateNuGetConfig.kt | 1 | 1539 | package com.jetbrains.rider.plugins.gradle.tasks
import com.jetbrains.rider.plugins.gradle.buildServer.buildServer
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import java.io.File
open class GenerateNuGetConfig: DefaultTask() {
@Input
var dotNetSdkPath: () -> File? = { null }
@OutputFile
var nuGetConfigFile = File("${project.projectDir}/../NuGet.Config")
@TaskAction
fun generate() {
val dotNetSdkFile = dotNetSdkPath() ?: error("dotNetSdkLocation not set")
logger.info("dotNetSdk location: '$dotNetSdkFile'")
assert(dotNetSdkFile.isDirectory)
project.buildServer.progress("Generating :${nuGetConfigFile.canonicalPath}...")
val nugetConfigText = """<?xml version="1.0" encoding="utf-8"?>
|<configuration>
| <packageSources>
| <clear />
| <add key="local-dotnet-sdk" value="${dotNetSdkFile.canonicalPath}" />
| <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
| </packageSources>
|</configuration>
""".trimMargin()
nuGetConfigFile.writeText(nugetConfigText)
logger.info("Generated content:\n$nugetConfigText")
val sb = StringBuilder("Dump dotNetSdkFile content:\n")
for(file in dotNetSdkFile.listFiles()) {
sb.append("${file.canonicalPath}\n")
}
logger.info(sb.toString())
}
} | apache-2.0 | e7acb1b75a74403fcfa7422e48343bf6 | 34.813953 | 87 | 0.641975 | 4.05 | false | true | false | false |
ReactiveCircus/FlowBinding | flowbinding-material/src/androidTest/java/reactivecircus/flowbinding/material/MaterialCardViewCheckedChangedFlowTest.kt | 1 | 2488 | package reactivecircus.flowbinding.material
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.google.android.material.card.MaterialCardView
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.flowbinding.material.fixtures.MaterialFragment1
import reactivecircus.flowbinding.material.test.R
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@LargeTest
class MaterialCardViewCheckedChangedFlowTest {
@Test
fun materialCardViewCheckedChanges() {
launchTest<MaterialFragment1> {
val recorder = FlowRecorder<Boolean>(testScope)
val cardView = getViewById<MaterialCardView>(R.id.materialCardViewTop).apply {
runOnUiThread { isCheckable = true }
}
cardView.checkedChanges().recordWith(recorder)
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
runOnUiThread { cardView.isChecked = true }
assertThat(recorder.takeValue())
.isTrue()
recorder.assertNoMoreValues()
runOnUiThread { cardView.isChecked = false }
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
cancelTestScope()
runOnUiThread { cardView.isChecked = true }
recorder.assertNoMoreValues()
}
}
@Test
fun materialCardViewCheckedChanges_skipInitialValue() {
launchTest<MaterialFragment1> {
val recorder = FlowRecorder<Boolean>(testScope)
val cardView = getViewById<MaterialCardView>(R.id.materialCardViewTop).apply {
runOnUiThread {
isCheckable = true
isChecked = true
}
}
cardView.checkedChanges()
.skipInitialValue()
.recordWith(recorder)
recorder.assertNoMoreValues()
runOnUiThread { cardView.isChecked = false }
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
cancelTestScope()
runOnUiThread { cardView.isChecked = true }
recorder.assertNoMoreValues()
}
}
}
| apache-2.0 | 6c89007d88b3376ae2254d37cea5c0ee | 32.621622 | 90 | 0.643891 | 5.952153 | false | true | false | false |
Zhuinden/simple-stack | tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_2/Step2Activity.kt | 1 | 2211 | package com.zhuinden.simplestacktutorials.steps.step_2
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import androidx.appcompat.app.AppCompatActivity
import com.zhuinden.simplestack.Backstack
import com.zhuinden.simplestack.History
import com.zhuinden.simplestack.SimpleStateChanger
import com.zhuinden.simplestack.StateChange
import com.zhuinden.simplestack.navigator.Navigator
import com.zhuinden.simplestacktutorials.databinding.ActivityStep2Binding
import com.zhuinden.simplestacktutorials.utils.hide
import com.zhuinden.simplestacktutorials.utils.onClick
import com.zhuinden.simplestacktutorials.utils.safe
import com.zhuinden.simplestacktutorials.utils.show
import kotlinx.parcelize.Parcelize
private val Context.backstack: Backstack
get() = Navigator.getBackstack(this)
class Step2Activity : AppCompatActivity(), SimpleStateChanger.NavigationHandler {
sealed class Screens : Parcelable {
@Parcelize
object First : Screens()
@Parcelize
object Second : Screens()
}
private lateinit var binding: ActivityStep2Binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityStep2Binding.inflate(layoutInflater)
setContentView(binding.root)
Navigator.configure()
.setStateChanger(SimpleStateChanger(this))
.install(this, binding.step2Root, History.of(Screens.First)) // auto-install backstack
}
override fun onBackPressed() {
if (!Navigator.onBackPressed(this)) {
super.onBackPressed()
}
}
override fun onNavigationEvent(stateChange: StateChange) {
val newKey = stateChange.topNewKey<Screens>()
when (newKey) {
Screens.First -> {
binding.step2Text.text = "First Screen"
binding.step2Button.show()
binding.step2Button.onClick {
backstack.goTo(Screens.Second)
}
}
Screens.Second -> {
binding.step2Text.text = "Second Screen"
binding.step2Button.hide()
}
}.safe()
}
} | apache-2.0 | 720a565542131ad79a83ded637d9634b | 31.057971 | 98 | 0.695161 | 4.870044 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/server/data/DataRepository.kt | 1 | 1184 | package me.mrkirby153.KirBot.server.data
import com.google.gson.GsonBuilder
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.kcutils.child
import me.mrkirby153.kcutils.mkdirIfNotExist
import net.dv8tion.jda.api.entities.Guild
private val GSON = GsonBuilder().setPrettyPrinting().create()
class DataRepository(@Transient var server: Guild) {
private val data = mutableMapOf<String, String>()
fun <T> get(type: Class<T>, key: String): T? {
if (!data.containsKey(key))
return null
return GSON.fromJson(data[key], type)
}
fun getBoolean(key: String): Boolean? {
return get(Boolean::class.java, key)
}
fun getString(key: String, default: String?): String? {
return get(String::class.java, key) ?: default
}
fun put(key: String, value: Any) {
data.put(key, GSON.toJson(value))
save()
}
fun remove(key: String) {
data.remove(key)
save()
}
fun save() {
val fileName = "${server.id}.json"
val file = Bot.files.data.child("servers").mkdirIfNotExist().child(fileName)
val json = GSON.toJson(this)
file.writeText(json)
}
} | mit | 50c54af399317dd85cba949b32e5779f | 25.333333 | 84 | 0.638514 | 3.770701 | false | false | false | false |
toastkidjp/Yobidashi_kt | article/src/main/java/jp/toastkid/article_viewer/article/detail/view/ArticleContentUi.kt | 1 | 8947 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.detail.view
import androidx.activity.ComponentActivity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import com.halilibo.richtext.markdown.Markdown
import com.halilibo.richtext.ui.RichText
import com.halilibo.richtext.ui.RichTextStyle
import com.halilibo.richtext.ui.RichTextThemeIntegration
import com.halilibo.richtext.ui.string.RichTextStringStyle
import jp.toastkid.article_viewer.R
import jp.toastkid.article_viewer.article.data.AppDatabase
import jp.toastkid.article_viewer.article.detail.LinkBehaviorService
import jp.toastkid.article_viewer.article.detail.viewmodel.ContentViewerFragmentViewModel
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.color.LinkColorGenerator
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.view.scroll.usecase.ScrollerUseCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
fun ArticleContentUi(title: String) {
val context = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(context)
val viewModelProvider = ViewModelProvider(context)
val repository = AppDatabase.find(context).articleRepository()
val linkBehaviorService = LinkBehaviorService(
viewModelProvider.get(ContentViewModel::class.java),
viewModelProvider.get(BrowserViewModel::class.java),
{ repository.exists(it) > 0 }
)
val viewModel = ViewModelProvider(context).get(ContentViewerFragmentViewModel::class.java)
viewModel.setTitle(title)
LaunchedEffect(key1 = title, block = {
val content = withContext(Dispatchers.IO) {
repository.findContentByTitle(title)
}
if (content.isNullOrBlank()) {
return@LaunchedEffect
}
withContext(Dispatchers.Main) {
viewModel.setContent(content)
}
})
viewModelProvider.get(ContentViewModel::class.java).replaceAppBarContent {
AppBarContent(viewModel)
}
val scrollState = rememberScrollState()
/*
binding.content.highlightColor = preferenceApplier.editorHighlightColor(Color.CYAN)*/
val editorFontColor = preferenceApplier.editorFontColor()
val stringStyle = RichTextStringStyle(
linkStyle = SpanStyle(Color(LinkColorGenerator().invoke(editorFontColor)))
)
SelectionContainer {
RichTextThemeIntegration(
contentColor = { Color(editorFontColor) }
) {
RichText(
style = RichTextStyle(stringStyle = stringStyle),
modifier = Modifier
.background(Color(preferenceApplier.editorBackgroundColor()))
.padding(8.dp)
.verticalScroll(scrollState)
) {
Markdown(
viewModel.content.value,
onLinkClicked = {
linkBehaviorService.invoke(it)
}
)
}
}
}
val contentViewModel = viewModelProvider.get(ContentViewModel::class.java)
ScrollerUseCase(contentViewModel, scrollState).invoke(LocalLifecycleOwner.current)
contentViewModel.clearOptionMenus()
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun AppBarContent(viewModel: ContentViewerFragmentViewModel) {
val activityContext = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(activityContext)
val tabListViewModel = ViewModelProvider(activityContext).get(TabListViewModel::class.java)
var searchInput by remember { mutableStateOf("") }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(56.dp)
.fillMaxWidth()
) {
Column(Modifier.weight(1f)) {
TextField(
value = searchInput,
onValueChange = {
searchInput = it
},
label = {
Text(
viewModel.title.value,
color = Color(preferenceApplier.editorFontColor())
)
},
singleLine = true,
keyboardActions = KeyboardActions {
//TODO contentTextSearchUseCase.invoke(it.toString())
},
colors = TextFieldDefaults.textFieldColors(
textColor = Color(preferenceApplier.fontColor),
cursorColor = MaterialTheme.colors.onPrimary,
unfocusedLabelColor = Color(preferenceApplier.fontColor),
focusedIndicatorColor = Color(preferenceApplier.fontColor)
),
trailingIcon = {
Icon(
Icons.Filled.Clear,
tint = Color(preferenceApplier.fontColor),
contentDescription = "clear text",
modifier = Modifier
.offset(x = 8.dp)
.clickable {
searchInput = ""
}
)
}
)
}
Box(
Modifier
.width(40.dp)
.fillMaxHeight()
.combinedClickable(
true,
onClick = {
ViewModelProvider(activityContext)
.get(ContentViewModel::class.java)
.switchTabList()
},
onLongClick = {
tabListViewModel.openNewTabForLongTap()
}
)
) {
Image(
painter = painterResource(id = R.drawable.ic_tab),
contentDescription = stringResource(id = R.string.tab),
colorFilter = ColorFilter.tint(
MaterialTheme.colors.onPrimary,
BlendMode.SrcIn
),
modifier = Modifier.align(Alignment.Center)
)
Text(
text = tabListViewModel.tabCount.value.toString(),
fontSize = 9.sp,
color = MaterialTheme.colors.onPrimary,
modifier = Modifier
.align(Alignment.Center)
.padding(start = 2.dp, bottom = 2.dp)
)
}
}
}
| epl-1.0 | d9f6c2480996be1f29610170bb471752 | 38.069869 | 95 | 0.659439 | 5.341493 | false | false | false | false |
http4k/http4k | http4k-testing/servirtium/src/main/kotlin/org/http4k/servirtium/InteractionStorage.kt | 1 | 1855 | package org.http4k.servirtium
import java.io.File
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Consumer
import java.util.function.Supplier
typealias StorageProvider = (String) -> InteractionStorage
/**
* Provides storage for the recorded Servirtium interaction data.
*/
interface InteractionStorage : Supplier<ByteArray>, Consumer<ByteArray> {
fun clean(): Boolean
companion object {
@JvmStatic
fun Disk(root: File): StorageProvider = object : StorageProvider {
override fun invoke(name: String): InteractionStorage {
val file = fileFor(name)
return object : InteractionStorage {
override fun get() = file.takeIf { it.exists() }?.readBytes() ?: ByteArray(0)
override fun accept(data: ByteArray) {
file.apply { parentFile.mkdirs() }.appendBytes(data)
}
override fun clean(): Boolean = fileFor(name).delete()
}
}
private fun fileFor(name: String) = File(root, "$name.md")
}
@JvmStatic
fun InMemory() = object : StorageProvider {
private val created = mutableMapOf<String, AtomicReference<ByteArray>>()
override fun invoke(name: String): InteractionStorage {
val ref = created[name] ?: AtomicReference(ByteArray(0))
created[name] = ref
return object : InteractionStorage {
override fun get() = ref.get()
override fun accept(data: ByteArray) {
ref.set(ref.get() + data)
}
override fun clean() = created[name]?.let { it.set(ByteArray(0)); true } ?: false
}
}
}
}
}
| apache-2.0 | cfdea1cc95eb93a84e9599556cc8198c | 34.673077 | 101 | 0.563881 | 5.0271 | false | false | false | false |
laurencegw/jenjin | jenjin-spine/src/main/kotlin/com/binarymonks/jj/spine/components/SpineBoneComponent.kt | 1 | 3711 | package com.binarymonks.jj.spine.components
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.physics.box2d.BodyDef
import com.badlogic.gdx.utils.Array
import com.binarymonks.jj.core.components.Component
import com.binarymonks.jj.core.pools.new
import com.binarymonks.jj.core.pools.recycle
import com.binarymonks.jj.core.scenes.ScenePath
import com.binarymonks.jj.core.spine.RagDollBone
import com.binarymonks.jj.spine.render.SpineRenderNode
import com.binarymonks.jj.core.scenes.Scene
import com.esotericsoftware.spine.Bone
class SpineBoneComponent : Component() {
internal var spineParent: SpineComponent? = null
internal var bone: RagDollBone? = null
set(value) {
value!!.spinePart = this
field = value
}
internal var ragDoll = false
var bonePath: Array<String> = Array()
internal fun setSpineComponent(spineParentScene: Scene) {
spineParent = spineParentScene.getComponent(SpineComponent::class).first()
val spineRender: SpineRenderNode = spineParentScene.renderRoot.getNode(SPINE_RENDER_NAME) as SpineRenderNode
val boneNode = findMyBone(spineRender.skeleton.rootBone, 0) as RagDollBone
bone = boneNode
spineParent!!.addBone(bone!!.data.name, this)
}
fun spineComponent(): SpineComponent {
return checkNotNull(spineParent)
}
private fun findMyBone(boneNode: Bone?, offset: Int): Bone {
if (boneNode == null) {
throw Exception("Could not find bone")
}
if (offset + 1 == bonePath.size) {
return boneNode
}
boneNode.children.forEach {
if (it.data.name == bonePath[offset + 1]) {
return findMyBone(it, offset + 1)
}
}
throw Exception("Could not find bone ${bonePath[offset]}")
}
private fun getRootNode(): Scene {
val scenePath: ScenePath = new(ScenePath::class)
for (i in 0..bonePath.size - 1) {
scenePath.up()
}
val root = me().getNode(scenePath)
recycle(scenePath)
return root
}
fun applyToBones(sceneOperation: (Scene) -> Unit) {
spineParent!!.applyToBones(sceneOperation)
}
override fun update() {
updatePosition()
}
internal fun updatePosition() {
if (!ragDoll && bone != null) {
val x = bone!!.worldX
val y = bone!!.worldY
val rotation = bone!!.worldRotationX
me().physicsRoot.b2DBody.setTransform(x, y, rotation * MathUtils.degRad)
}
}
fun triggerRagDoll(gravity: Float = 1f) {
if (bone == null) println("No bone $bonePath")
if (!ragDoll && bone != null) {
ragDoll = true
bone!!.triggerRagDoll()
scene!!.physicsRoot.b2DBody.type = BodyDef.BodyType.DynamicBody
scene!!.physicsRoot.b2DBody.gravityScale = gravity
bone!!.children.forEach {
val name = it.data.name
val boneComponent = me().getChild(name)!!.getComponent(SpineBoneComponent::class).first()
boneComponent!!.triggerRagDoll(gravity)
}
}
}
fun reverseRagDoll() {
if (ragDoll) {
ragDoll = false
bone!!.reverseRagDoll()
me().physicsRoot.b2DBody.type = BodyDef.BodyType.StaticBody
me().physicsRoot.b2DBody.gravityScale = 0f
bone!!.children.forEach {
val name = it.data.name
val boneComponent = me().getChild(name)!!.getComponent(SpineBoneComponent::class).first()
boneComponent!!.reverseRagDoll()
}
}
}
}
| apache-2.0 | d754599bd548a5a970bf4f7e08e22e87 | 32.736364 | 116 | 0.616276 | 4.188488 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/MarkdownParserUtil.kt | 1 | 3241 | package org.intellij.markdown.parser.markerblocks
import org.intellij.markdown.lexer.Compat.assert
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.constraints.*
object MarkdownParserUtil {
fun calcNumberOfConsequentEols(pos: LookaheadText.Position, constraints: MarkdownConstraints): Int {
assert(pos.offsetInCurrentLine == -1)
var currentPos = pos
var result = 1
val isClearLine: (LookaheadText.Position) -> Boolean = { pos ->
val currentConstraints = constraints.applyToNextLine(pos)
val constraintsLength = currentConstraints.getCharsEaten(pos.currentLine)
currentConstraints.upstreamWith(constraints) && (
constraintsLength >= pos.currentLine.length ||
pos.nextPosition(1 + constraintsLength)?.charsToNonWhitespace() == null)
}
while (isClearLine(currentPos)) {
currentPos = currentPos.nextLinePosition()
?: break//return 5
result++
if (result > 4) {
break
}
}
return result
}
fun getFirstNonWhitespaceLinePos(pos: LookaheadText.Position, eolsToSkip: Int): LookaheadText.Position? {
var currentPos = pos
repeat(eolsToSkip - 1) {
currentPos = pos.nextLinePosition() ?: return null
}
while (currentPos.charsToNonWhitespace() == null) {
currentPos = currentPos.nextLinePosition()
?: return null
}
return currentPos
}
fun hasCodeBlockIndent(pos: LookaheadText.Position,
constraints: MarkdownConstraints): Boolean {
val constraintsLength = constraints.getCharsEaten(pos.currentLine)
if (pos.offsetInCurrentLine >= constraintsLength + 4) {
return true
}
for (i in constraintsLength..pos.offsetInCurrentLine) {
if (pos.currentLine[i] == '\t') {
return true
}
}
return false
}
fun isEmptyOrSpaces(s: CharSequence): Boolean {
for (c in s) {
if (c != ' ' && c != '\t') {
return false
}
}
return true
}
fun findNonEmptyLineWithSameConstraints(constraints: MarkdownConstraints,
pos: LookaheadText.Position): LookaheadText.Position? {
var currentPos = pos
while (true) {
// currentPos = currentPos.nextLinePosition() ?: return null
val nextLineConstraints = constraints.applyToNextLineAndAddModifiers(currentPos)
// kinda equals
if (!(nextLineConstraints.upstreamWith(constraints) && nextLineConstraints.extendsPrev(constraints))) {
return null
}
val stringAfterConstraints = nextLineConstraints.eatItselfFromString(currentPos.currentLine)
if (!MarkdownParserUtil.isEmptyOrSpaces(stringAfterConstraints)) {
return currentPos
} else {
currentPos = currentPos.nextLinePosition()
?: return null
}
}
}
}
| apache-2.0 | 82d2767ca1a8cbcf973d5073dbfb61ad | 32.760417 | 115 | 0.591484 | 5.521295 | false | false | false | false |
rascarlo/AURdroid | app/src/main/java/com/rascarlo/aurdroid/infoResult/InfoResultFragment.kt | 1 | 10512 | package com.rascarlo.aurdroid.infoResult
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.rascarlo.aurdroid.R
import com.rascarlo.aurdroid.databinding.FragmentInfoResultBinding
import com.rascarlo.aurdroid.utils.*
import timber.log.Timber
class InfoResultFragment : Fragment() {
private val args: InfoResultFragmentArgs by navArgs()
private lateinit var binding: FragmentInfoResultBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// binding
binding = FragmentInfoResultBinding.inflate(inflater)
// arg
val nameArg: String = args.name
Timber.d("name: $nameArg")
// view model factory
val viewModelFactory = InfoResultViewModelFactory(nameArg)
// view model
val viewModel: InfoResultViewModel =
ViewModelProvider(this, viewModelFactory).get(InfoResultViewModel::class.java)
// lifecycle owner
binding.lifecycleOwner = this
// assign view model
binding.viewModel = viewModel
// observe live data
viewModel.infoResult.observe(viewLifecycleOwner, {
if (null != it) {
binding.infoResult = it
// assign adapters
assignAdapters()
// execute bindings
binding.executePendingBindings()
// invalidate options meu
activity?.invalidateOptionsMenu()
} else {
binding.infoResult = null
}
})
// observe search result status view model
viewModel.status.observe(viewLifecycleOwner, {
bindAurDroidApiStatusImageView(
binding.fragmentInfoResultStatusInclude.apiStatusImage,
it
)
bindAurDroidApiStatusTextView(
binding.fragmentInfoResultStatusInclude.apiStatusText,
it
)
bindAurDroidApiStatusProgressBar(
binding.fragmentInfoResultStatusInclude.apiStatusProgressBar,
it
)
})
// observe search result error view model
viewModel.error.observe(viewLifecycleOwner, {
bindAurDroidApiErrorTextView(
binding.fragmentInfoResultStatusInclude.apiErrorText,
it
)
})
// Inflate the layout for this fragment
return binding.root
}
private fun assignAdapters() {
binding.apply {
// depends
infoResultDependsInclude.infoResultDependsRecyclerView.adapter =
DependencyAdapter()
// make depends
infoResultMakeDependsInclude.infoResultMakeDependsRecyclerView.adapter =
DependencyAdapter()
// opt depends
infoResultOptDependsInclude.infoResultOptDependsRecyclerView.adapter =
DependencyAdapter()
// check depends
infoResultCheckDependsInclude.infoResultCheckDependsRecyclerView.adapter =
DependencyAdapter()
// conflicts
infoResultConflictsInclude.infoResultConflictsRecyclerView.adapter =
DependencyAdapter()
// provides
infoResultProvidesInclude.infoResultProvidesRecyclerView.adapter =
DependencyAdapter()
// replaces
infoResultReplacesInclude.infoResultReplacesRecyclerView.adapter =
DependencyAdapter()
// groups
infoResultGroupsInclude.infoResultGroupsRecyclerView.adapter =
DependencyAdapter()
// keywords
infoResultKeywordsInclude.infoResultKeywordsRecyclerView.adapter =
DependencyAdapter()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_info_result, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.apply {
findItem(R.id.menu_info_result_share).isVisible = null != binding.infoResult
findItem(R.id.menu_info_result_main).isVisible = null != binding.infoResult
// view pkgbuild
findItem(R.id.menu_info_result_view_pkgbuild).isEnabled = null != getViewPkgbuildUri()
// view changes
findItem(R.id.menu_info_result_view_changes).isEnabled = null != getViewChangesUri()
// maintainer
findItem(R.id.menu_info_result_maintainer).isEnabled = null != getMaintainer()
// open in browser
findItem(R.id.menu_info_result_open_in_browser).isEnabled = null != getUri()
// download snapshot
findItem(R.id.menu_info_result_download_snapshot).isEnabled = null != getSnapshotUri()
// share pkgbuild
findItem(R.id.menu_info_result_share_pkgbuild).isEnabled = null != getViewChangesUri()
// share changes
findItem(R.id.menu_info_result_share_changes).isEnabled = null != getViewChangesUri()
// share package
findItem(R.id.menu_info_result_share_package).isEnabled = null != getUri()
// share upstream url
findItem(R.id.menu_info_result_share_upstream_url).isEnabled = null != getUpstreamUrl()
// share git clone url
findItem(R.id.menu_info_result_share_git_clone_url).isEnabled = null != getGitCloneUrl()
// share snapshot
findItem(R.id.menu_info_result_share_snapshot).isEnabled = null != getSnapshotUri()
}
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// view pkgbuild
R.id.menu_info_result_view_pkgbuild -> startIntentViewUri(getViewPkgbuildUri())
// view changes
R.id.menu_info_result_view_changes -> startIntentViewUri(getViewChangesUri())
// maintainer
R.id.menu_info_result_maintainer -> browseMaintainer()
// open in browser
R.id.menu_info_result_open_in_browser -> startIntentViewUri(getUri())
// download snapshot
R.id.menu_info_result_download_snapshot -> startIntentViewUri(getSnapshotUri())
// share pkgbuild
R.id.menu_info_result_share_pkgbuild -> startIntentShare(getViewPkgbuildUri().toString())
// share changes
R.id.menu_info_result_share_changes -> startIntentShare(getViewChangesUri().toString())
// share package
R.id.menu_info_result_share_package -> startIntentShare(getUri().toString())
// share upstream url
R.id.menu_info_result_share_upstream_url -> startIntentShare(getUpstreamUrl())
// share git clone url
R.id.menu_info_result_share_git_clone_url -> startIntentShare(getGitCloneUrl().toString())
// share snapshot
R.id.menu_info_result_share_snapshot -> startIntentShare(getSnapshotUri().toString())
}
return super.onOptionsItemSelected(item)
}
private fun getViewPkgbuildUri(): Uri? = when {
binding.infoResult?.packageBase != null
-> Uri.parse(Constants.PKGBUILD_BASE_URL)
.buildUpon()
.appendQueryParameter("h", binding.infoResult!!.packageBase)
.build()
else -> null
}
private fun getViewChangesUri(): Uri? {
return when {
binding.infoResult?.packageBase != null
-> Uri.parse(Constants.PACKAGE_LOG_BASE_URL)
.buildUpon()
.appendQueryParameter("h", binding.infoResult!!.packageBase)
.build()
else -> null
}
}
private fun getMaintainer(): String? {
return binding.infoResult?.maintainer?.trim() ?: return null
}
private fun getUri(): Uri? = when {
binding.infoResult?.name != null
-> Uri.parse(Constants.PACKAGES_BASE_URL)
.buildUpon()
.appendPath(binding.infoResult!!.name)
.build()
else -> null
}
private fun getSnapshotUri(): Uri? = when {
binding.infoResult?.name != null
-> Uri.parse(Constants.PACKAGE_SNAPSHOT_BASE_URL)
.buildUpon()
.appendPath(binding.infoResult!!.urlPath)
.build()
else -> null
}
private fun getUpstreamUrl(): String? {
return binding.infoResult?.url
}
private fun getGitCloneUrl(): Uri? = when {
binding.infoResult?.name != null
-> Uri.parse(Constants.PACKAGES_GIT_CLONE_BASE_URL)
.buildUpon()
.appendPath(binding.infoResult!!.name + ".git")
.build()
else -> null
}
private fun startIntentViewUri(uri: Uri?) {
try {
binding.root.context?.startActivity(Intent(Intent.ACTION_VIEW, uri))
} catch (e: Exception) {
showToast()
Timber.e(e)
}
}
private fun startIntentShare(string: String?) {
try {
val intent = Intent()
intent.action = Intent.ACTION_SEND
intent.putExtra(Intent.EXTRA_TEXT, string)
intent.type = "text/plain"
binding.root.context?.startActivity(intent)
} catch (e: Exception) {
showToast()
Timber.e(e)
}
}
private fun browseMaintainer() = this.findNavController()
.navigate(
InfoResultFragmentDirections
.actionInfoResultFragmentToSearchResultFragment(
getMaintainer()!!,
FieldEnum.MAINTAINER.toString(),
SortEnum.PACKAGE_NAME.toString()
)
)
private fun showToast() = Toast.makeText(
binding.root.context,
binding.root.context.resources.getString(R.string.something_went_wrong),
Toast.LENGTH_SHORT
).show()
} | gpl-3.0 | bb4466878bf89b3eff622b75a0e0405d | 37.650735 | 102 | 0.609589 | 4.891577 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/network/Req.kt | 1 | 950 | package eu.kanade.tachiyomi.data.network
import okhttp3.*
import java.util.concurrent.TimeUnit
private val DEFAULT_CACHE_CONTROL = CacheControl.Builder().maxAge(10, TimeUnit.MINUTES).build()
private val DEFAULT_HEADERS = Headers.Builder().build()
private val DEFAULT_BODY: RequestBody = FormBody.Builder().build()
@JvmOverloads
fun get(url: String,
headers: Headers = DEFAULT_HEADERS,
cache: CacheControl = DEFAULT_CACHE_CONTROL): Request {
return Request.Builder()
.url(url)
.headers(headers)
.cacheControl(cache)
.build()
}
@JvmOverloads
fun post(url: String,
headers: Headers = DEFAULT_HEADERS,
body: RequestBody = DEFAULT_BODY,
cache: CacheControl = DEFAULT_CACHE_CONTROL): Request {
return Request.Builder()
.url(url)
.post(body)
.headers(headers)
.cacheControl(cache)
.build()
}
| apache-2.0 | 74eedc1d1987a9984868c389be6f9831 | 26.941176 | 95 | 0.637895 | 4.298643 | false | false | false | false |
Balthair94/KotlinPokedex | app/src/main/java/baltamon/mx/kotlinpokedex/adapters/TabPokemonFragmentAdapter.kt | 1 | 1468 | package baltamon.mx.kotlinpokedex.adapters
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import baltamon.mx.kotlinpokedex.fragments.PokemonAbilitiesFragment
import baltamon.mx.kotlinpokedex.fragments.PokemonAboutFragment
import baltamon.mx.kotlinpokedex.fragments.PokemonMovesFragment
import baltamon.mx.kotlinpokedex.models.NamedAPIResource
import baltamon.mx.kotlinpokedex.models.Pokemon
/**
* Created by Baltazar Rodriguez on 28/05/2017.
*/
class TabPokemonFragmentAdapter(fm: FragmentManager, val pokemon: Pokemon) : FragmentPagerAdapter(fm) {
val titles = arrayOf("About", "Abilities", "Moves")
override fun getItem(position: Int): Fragment =
when (position) {
0 -> PokemonAboutFragment.newInstance(pokemon)
1 -> {
val abilities: ArrayList<NamedAPIResource> = ArrayList()
pokemon.abilities.mapTo(abilities) { it.ability }
PokemonAbilitiesFragment.newInstance(abilities)
}
else -> {
val moves: ArrayList<NamedAPIResource> = ArrayList()
pokemon.moves.mapTo(moves) { it.move }
PokemonMovesFragment.newInstance(moves)
}
}
override fun getPageTitle(position: Int): CharSequence = titles[position]
override fun getCount(): Int = 3
} | mit | ce2f89a250b5d2c6ebf60a1f6c11d148 | 39.805556 | 103 | 0.677793 | 4.781759 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/tags/TagsDialogListener.kt | 1 | 3342 | /*
Copyright (c) 2021 Tarek Mohamed Abdalla <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.dialogs.tags
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentResultListener
import com.ichi2.utils.KotlinCleanup
import java.util.ArrayList
@KotlinCleanup("make selectedTags and indeterminateTags non-null")
interface TagsDialogListener {
/**
* Called when [TagsDialog] finished with selecting tags.
*
* @param selectedTags the list of checked tags
* @param indeterminateTags a list of tags which can checked or unchecked, should be ignored if not expected
* determining if tags in this list is checked or not is done by looking at the list of
* previous tags. if the tag is found in both previous and indeterminate, it should be kept
* otherwise it should be removed @see [TagsUtil.getUpdatedTags]
* @param option selection radio option, should be ignored if not expected
*/
fun onSelectedTags(selectedTags: List<String>, indeterminateTags: List<String>, option: Int)
fun <F> F.registerFragmentResultReceiver() where F : Fragment, F : TagsDialogListener {
parentFragmentManager.setFragmentResultListener(
ON_SELECTED_TAGS_KEY, this,
FragmentResultListener { _: String?, bundle: Bundle ->
val selectedTags: List<String> = bundle.getStringArrayList(ON_SELECTED_TAGS__SELECTED_TAGS)!!
val indeterminateTags: List<String> = bundle.getStringArrayList(ON_SELECTED_TAGS__INDETERMINATE_TAGS)!!
val option = bundle.getInt(ON_SELECTED_TAGS__OPTION)
onSelectedTags(selectedTags, indeterminateTags, option)
}
)
}
companion object {
fun createFragmentResultSender(fragmentManager: FragmentManager) = object : TagsDialogListener {
override fun onSelectedTags(selectedTags: List<String>, indeterminateTags: List<String>, option: Int) {
val bundle = Bundle().apply {
putStringArrayList(ON_SELECTED_TAGS__SELECTED_TAGS, ArrayList(selectedTags))
putStringArrayList(ON_SELECTED_TAGS__INDETERMINATE_TAGS, ArrayList(indeterminateTags))
putInt(ON_SELECTED_TAGS__OPTION, option)
}
fragmentManager.setFragmentResult(ON_SELECTED_TAGS_KEY, bundle)
}
}
const val ON_SELECTED_TAGS_KEY = "ON_SELECTED_TAGS_KEY"
const val ON_SELECTED_TAGS__SELECTED_TAGS = "SELECTED_TAGS"
const val ON_SELECTED_TAGS__INDETERMINATE_TAGS = "INDETERMINATE_TAGS"
const val ON_SELECTED_TAGS__OPTION = "OPTION"
}
}
| gpl-3.0 | bd1c8cf010cadf69d07f688e8cdf241c | 48.880597 | 119 | 0.708259 | 4.687237 | false | false | false | false |
bertilxi/Chilly_Willy_Delivery | mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/model/Review.kt | 1 | 1385 | package dam.isi.frsf.utn.edu.ar.delivery.model
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class Review(
@SerializedName("rating")
@Expose
var rating: Int = 0,
@SerializedName("comment")
@Expose
var comment: String = "",
@SerializedName("img")
@Expose
var img: String = ""
) : Parcelable {
fun withRating(rating: Int): Review {
this.rating = rating
return this
}
fun withComment(comment: String): Review {
this.comment = comment
return this
}
fun withImg(img: String): Review {
this.img = img
return this
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<Review> = object : Parcelable.Creator<Review> {
override fun createFromParcel(source: Parcel): Review = Review(source)
override fun newArray(size: Int): Array<Review?> = arrayOfNulls(size)
}
}
constructor(source: Parcel) : this(
source.readInt(),
source.readString(),
source.readString()
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(rating)
dest.writeString(comment)
dest.writeString(img)
}
} | mit | 240efcd5987441e95dc139be17d74497 | 24.666667 | 97 | 0.621661 | 4.341693 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/persistence/comments/CommentsDao.kt | 2 | 10158 | package org.wordpress.android.fluxc.persistence.comments
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
typealias CommentEntityList = List<CommentEntity>
@Dao
abstract class CommentsDao {
// Public methods
@Transaction
open suspend fun insertOrUpdateComment(comment: CommentEntity): Long {
return insertOrUpdateCommentInternal(comment)
}
@Transaction
open suspend fun insertOrUpdateCommentForResult(comment: CommentEntity): CommentEntityList {
val entityId = insertOrUpdateCommentInternal(comment)
return getCommentById(entityId)
}
@Transaction
open suspend fun getFilteredComments(localSiteId: Int, statuses: List<String>): CommentEntityList {
return getFilteredCommentsInternal(localSiteId, statuses, statuses.isNotEmpty())
}
@Transaction
open suspend fun getCommentsByLocalSiteId(
localSiteId: Int,
statuses: List<String>,
limit: Int,
orderAscending: Boolean
): CommentEntityList {
return getCommentsByLocalSiteIdInternal(
localSiteId = localSiteId,
filterByStatuses = statuses.isNotEmpty(),
statuses = statuses,
limit = limit,
orderAscending = orderAscending
)
}
@Transaction
open suspend fun deleteComment(comment: CommentEntity): Int {
val result = deleteById(comment.id)
return if (result > 0) {
result
} else {
deleteByLocalSiteAndRemoteIds(comment.localSiteId, comment.remoteCommentId)
}
}
@Transaction
open suspend fun removeGapsFromTheTop(
localSiteId: Int,
statuses: List<String>,
remoteIds: List<Long>,
startOfRange: Long
): Int {
return removeGapsFromTheTopInternal(
localSiteId = localSiteId,
filterByStatuses = statuses.isNotEmpty(),
statuses = statuses,
filterByIds = remoteIds.isNotEmpty(),
remoteIds = remoteIds,
startOfRange = startOfRange
)
}
@Transaction
open suspend fun removeGapsFromTheBottom(
localSiteId: Int,
statuses: List<String>,
remoteIds: List<Long>,
endOfRange: Long
): Int {
return removeGapsFromTheBottomInternal(
localSiteId = localSiteId,
filterByStatuses = statuses.isNotEmpty(),
statuses = statuses,
filterByIds = remoteIds.isNotEmpty(),
remoteIds = remoteIds,
endOfRange = endOfRange
)
}
@Transaction
open suspend fun removeGapsFromTheMiddle(
localSiteId: Int,
statuses: List<String>,
remoteIds: List<Long>,
startOfRange: Long,
endOfRange: Long
): Int {
return removeGapsFromTheMiddleInternal(
localSiteId = localSiteId,
filterByStatuses = statuses.isNotEmpty(),
statuses = statuses,
filterByIds = remoteIds.isNotEmpty(),
remoteIds = remoteIds,
startOfRange = startOfRange,
endOfRange = endOfRange
)
}
@Query("SELECT * FROM Comments WHERE id = :localId LIMIT 1")
abstract suspend fun getCommentById(localId: Long): CommentEntityList
@Query("SELECT * FROM Comments WHERE localSiteId = :localSiteId AND remoteCommentId = :remoteCommentId")
abstract suspend fun getCommentsByLocalSiteAndRemoteCommentId(
localSiteId: Int,
remoteCommentId: Long
): CommentEntityList
@Transaction
open suspend fun appendOrUpdateComments(comments: CommentEntityList): Int {
val affectedIdList = insertOrUpdateCommentsInternal(comments)
return affectedIdList.size
}
@Transaction
open suspend fun clearAllBySiteIdAndFilters(localSiteId: Int, statuses: List<String>): Int {
return clearAllBySiteIdAndFiltersInternal(
localSiteId = localSiteId,
filterByStatuses = statuses.isNotEmpty(),
statuses = statuses
)
}
// Protected methods
@Insert(onConflict = OnConflictStrategy.REPLACE)
protected abstract fun insert(comment: CommentEntity): Long
@Update
protected abstract fun update(comment: CommentEntity): Int
@Query("""
SELECT * FROM Comments WHERE localSiteId = :localSiteId
AND CASE WHEN :filterByStatuses = 1 THEN status IN (:statuses) ELSE 1 END
ORDER BY datePublished DESC
""")
protected abstract fun getFilteredCommentsInternal(
localSiteId: Int,
statuses: List<String>,
filterByStatuses: Boolean
): CommentEntityList
@Query("""
SELECT * FROM Comments
WHERE localSiteId = :localSiteId
AND CASE WHEN (:filterByStatuses = 1) THEN (status IN (:statuses)) ELSE 1 END
ORDER BY
CASE WHEN :orderAscending = 1 THEN datePublished END ASC,
CASE WHEN :orderAscending = 0 THEN datePublished END DESC
LIMIT CASE WHEN :limit > 0 THEN :limit ELSE -1 END
""")
protected abstract fun getCommentsByLocalSiteIdInternal(
localSiteId: Int,
filterByStatuses: Boolean,
statuses: List<String>,
limit: Int,
orderAscending: Boolean
): CommentEntityList
@Query("""
DELETE FROM Comments
WHERE localSiteId = :localSiteId
AND CASE WHEN (:filterByStatuses = 1) THEN (status IN (:statuses)) ELSE 1 END
""")
protected abstract fun clearAllBySiteIdAndFiltersInternal(
localSiteId: Int,
filterByStatuses: Boolean,
statuses: List<String>
): Int
@Query("""
DELETE FROM Comments
WHERE localSiteId = :localSiteId
AND CASE WHEN (:filterByStatuses = 1) THEN (status IN (:statuses)) ELSE 1 END
AND CASE WHEN (:filterByIds = 1) THEN (remoteCommentId NOT IN (:remoteIds)) ELSE 1 END
AND publishedTimestamp >= :startOfRange
""")
@Suppress("LongParameterList")
protected abstract fun removeGapsFromTheTopInternal(
localSiteId: Int,
filterByStatuses: Boolean,
statuses: List<String>,
filterByIds: Boolean,
remoteIds: List<Long>,
startOfRange: Long
): Int
@Query("""
DELETE FROM Comments
WHERE localSiteId = :localSiteId
AND CASE WHEN (:filterByStatuses = 1) THEN (status IN (:statuses)) ELSE 1 END
AND CASE WHEN (:filterByIds = 1) THEN (remoteCommentId NOT IN (:remoteIds)) ELSE 1 END
AND publishedTimestamp <= :endOfRange
""")
@Suppress("LongParameterList")
protected abstract fun removeGapsFromTheBottomInternal(
localSiteId: Int,
filterByStatuses: Boolean,
statuses: List<String>,
filterByIds: Boolean,
remoteIds: List<Long>,
endOfRange: Long
): Int
@Query("""
DELETE FROM Comments
WHERE localSiteId = :localSiteId
AND CASE WHEN (:filterByStatuses = 1) THEN (status IN (:statuses)) ELSE 1 END
AND CASE WHEN (:filterByIds = 1) THEN (remoteCommentId NOT IN (:remoteIds)) ELSE 1 END
AND publishedTimestamp <= :startOfRange
AND publishedTimestamp >= :endOfRange
""")
@Suppress("LongParameterList")
protected abstract fun removeGapsFromTheMiddleInternal(
localSiteId: Int,
filterByStatuses: Boolean,
statuses: List<String>,
filterByIds: Boolean,
remoteIds: List<Long>,
startOfRange: Long,
endOfRange: Long
): Int
@Query("DELETE FROM Comments WHERE id = :commentId")
protected abstract fun deleteById(commentId: Long): Int
@Query("DELETE FROM Comments WHERE localSiteId = :localSiteId AND remoteCommentId = :remoteCommentId")
protected abstract fun deleteByLocalSiteAndRemoteIds(localSiteId: Int, remoteCommentId: Long): Int
// Private methods
private suspend fun insertOrUpdateCommentsInternal(comments: CommentEntityList): List<Long> {
return comments.map { comment ->
insertOrUpdateCommentInternal(comment)
}
}
private suspend fun insertOrUpdateCommentInternal(comment: CommentEntity): Long {
val commentByLocalId = getCommentById(comment.id)
val matchingComments = if (commentByLocalId.isEmpty()) {
getCommentsByLocalSiteAndRemoteCommentId(comment.localSiteId, comment.remoteCommentId)
} else {
commentByLocalId
}
return if (matchingComments.isEmpty()) {
insert(comment)
} else {
// We are forcing the id of the matching comment so the update can
// act on the expected entity
val matchingComment = matchingComments.first()
update(comment.copy(id = matchingComment.id))
matchingComment.id
}
}
@Entity(
tableName = "Comments"
)
data class CommentEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val remoteCommentId: Long,
val remotePostId: Long,
val localSiteId: Int,
val remoteSiteId: Long,
val authorUrl: String?,
val authorName: String?,
val authorEmail: String?,
val authorProfileImageUrl: String?,
val authorId: Long,
val postTitle: String?,
val status: String?,
val datePublished: String?,
val publishedTimestamp: Long,
val content: String?,
val url: String?,
val hasParent: Boolean,
val parentId: Long,
val iLike: Boolean
) {
@Ignore
@Suppress("DataClassShouldBeImmutable")
var level: Int = 0
}
companion object {
const val EMPTY_ID = -1L
}
}
| gpl-2.0 | f394116a3d8e472f73109a9faa35de86 | 32.196078 | 108 | 0.639988 | 5.246901 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/item/inventory/ExtendedInventoryColumn.kt | 1 | 1503 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.item.inventory
import org.lanternpowered.api.util.uncheckedCast
import kotlin.contracts.contract
typealias InventoryColumn = org.spongepowered.api.item.inventory.type.InventoryColumn
/**
* Gets the normal column inventories as an extended column inventories.
*/
inline fun List<InventoryColumn>.fix(): List<ExtendedInventoryColumn> =
this.uncheckedCast()
/**
* Gets the normal column inventory as an extended column inventory.
*/
inline fun InventoryColumn.fix(): ExtendedInventoryColumn {
contract { returns() implies (this@fix is ExtendedInventoryColumn) }
return this as ExtendedInventoryColumn
}
/**
* Gets the normal column inventory as an extended column inventory.
*/
@Deprecated(message = "Redundant call.", replaceWith = ReplaceWith(""))
inline fun ExtendedInventoryColumn.fix(): ExtendedInventoryColumn = this
/**
* An extended version of [InventoryColumn].
*/
interface ExtendedInventoryColumn : InventoryColumn, ExtendedInventory2D {
@Deprecated(message = "Is always 1 for columns.", replaceWith = ReplaceWith("1"))
override val width: Int
get() = 1
}
| mit | b293b9211b3f2a84a2fcc19fadefadf3 | 30.3125 | 85 | 0.744511 | 4.210084 | false | false | false | false |
sabi0/intellij-community | community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/model/ProjectsWithKotlin.kt | 1 | 27278 | // 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.ide.projectWizard.kotlin.model
import com.intellij.openapi.application.PathManager
import com.intellij.testGuiFramework.fixtures.JDialogFixture
import com.intellij.testGuiFramework.framework.Timeouts.defaultTimeout
import com.intellij.testGuiFramework.framework.GuiTestUtil.fileSearchAndReplace
import com.intellij.testGuiFramework.impl.*
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntil
import com.intellij.testGuiFramework.util.*
import com.intellij.testGuiFramework.util.scenarios.*
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.timing.Timeout
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import org.hamcrest.core.Is.`is` as Matcher_Is
/**
* Creates a Java project with a specified framework
* @param projectPath full path where the new project should be created
* last item in the path is considered as a new project name
* @param framework framework name, if empty - no framework should be selected
*/
fun KotlinGuiTestCase.createJavaProject(
projectPath: String,
framework: LibrariesSet = emptySet()) {
welcomePageDialogModel.createNewProject()
newProjectDialogModel.assertGroupPresent(NewProjectDialogModel.Groups.Kotlin)
newProjectDialogModel.createJavaProject(projectPath, framework)
waitAMoment()
}
/**
* Creates a Gradle project with a specified framework
* @param projectPath full path where the new project should be created with project name
* @param group groupid of created gradle project
* @param artifact artifactid of created gradle project
* @param framework framework name, if empty - no framework should be selected
* Note: debugged only with Kotlin frameworks
*/
fun KotlinGuiTestCase.createGradleProject(
projectPath: String,
gradleOptions: NewProjectDialogModel.GradleProjectOptions
) {
welcomePageDialogModel.createNewProject()
newProjectDialogModel.assertGroupPresent(NewProjectDialogModel.Groups.Kotlin)
newProjectDialogModel.createGradleProject(projectPath, gradleOptions)
}
/**
* Creates a Maven project with a specified archetype
* @param projectPath full path where the new project should be created with project name
* @param artifact artifactid of created gradle project
* @param archetype archetype name, if empty - no archetype should be selected
* @param kotlinVersion version of chosen archetype
* Note: debugged only with Kotlin frameworks
*/
fun KotlinGuiTestCase.createMavenProject(
projectPath: String,
artifact: String,
archetype: String = "",
kotlinVersion: String = ""
) {
welcomePageDialogModel.createNewProject()
newProjectDialogModel.assertGroupPresent(NewProjectDialogModel.Groups.Kotlin)
val mavenOptions = NewProjectDialogModel.MavenProjectOptions(
artifact = artifact,
useArchetype = archetype.isNotEmpty(),
archetypeGroup = "org.jetbrains.kotlin:, $archetype",
archetypeVersion = "$archetype, :$kotlinVersion"
)
newProjectDialogModel.createMavenProject(projectPath, mavenOptions)
}
/**
* Creates a KOtlin project with a specified framework
* @param projectPath full path where the new project should be created
* last item in the path is considered as a new project name
* @param kotlinKind kind of Kotlin project JVM or JS
*/
fun KotlinGuiTestCase.createKotlinProject(
projectPath: String,
kotlinKind: KotlinKind) {
welcomePageDialogModel.createNewProject()
newProjectDialogModel.assertGroupPresent(NewProjectDialogModel.Groups.Kotlin)
newProjectDialogModel.createKotlinProject(projectPath, kotlinLibs.getValue(kotlinKind).kotlinProject.frameworkName)
}
/**
* Configure Kotlin JVM in a java project
* @param libInPlugin
* - true - the kotlin specific jar files are taken from plugin
* - false - needed jar files are created in the `lib` folder within the project folder
* */
fun KotlinGuiTestCase.configureKotlinJvm(libInPlugin: Boolean) {
ideFrame {
waitAMoment(3000)
logTestStep("Open 'Configure Kotlin in Project' dialog")
invokeMainMenu("ConfigureKotlinInProject")
dialog("Create Kotlin Java Runtime Library") {
if (libInPlugin) {
logUIStep("Select `Use library from plugin` option")
radioButton("Use library from plugin").select()
}
logUIStep("Close 'Configure Kotlin in Project' dialog with OK")
button("OK").click()
}
waitAMoment()
}
}
/**
* Configure Kotlin JS in a project
* @param libInPlugin
* - true - the kotlin specific jar files are taken from plugin
* - false - needed jar files are created in the `lib` folder within the project folder
* */
fun KotlinGuiTestCase.configureKotlinJs(libInPlugin: Boolean) {
ideFrame {
waitAMoment()
logTestStep("Open 'Configure Kotlin (JavaScript) in Project' dialog")
invokeMainMenu("ConfigureKotlinJsInProject")
dialog("Create Kotlin JavaScript Library") {
if (libInPlugin) {
logUIStep("Select `Use library from plugin` option")
radioButton("Use library from plugin").select()
}
logUIStep("Close 'Configure Kotlin in Project' dialog with OK")
button("OK").click()
}
waitAMoment()
}
}
/**
* As list of kotlin versions shown in the configure dialog is filled up from the internet
* sometimes it's not loaded. In such cases another attempt is performed.
* @param logText - logged text
* @param menuTitle - invoked menu ID
* @param dialogTitle - title of the configuring dialog (all dialogs are the same, but titles)
* @param kotlinVersion - kotlin version as it should be added to build.gradle/pom.xml
* @param module - if empty - all modules should be configured
* else a single module with the specified name should be configured
* */
fun KotlinGuiTestCase.configureKotlinFromGradleMaven(logText: String,
menuTitle: String,
dialogTitle: String,
kotlinVersion: String,
module: String) {
var result: Boolean = false
val maxAttempts = 3
ideFrame {
var counter = 0
do {
try {
logTestStep("$logText. Attempt #${counter + 1}")
waitAMoment()
invokeMainMenu(menuTitle)
result = configureKotlinFromGradleMavenSelectValues(dialogTitle, kotlinVersion, module)
counter++
}
catch (e: ComponentLookupException) {}
}
while (!result && counter < maxAttempts)
waitAMoment()
}
assert(result) { "Version $kotlinVersion not found after $maxAttempts attempts" }
}
/**
* Configure Kotlin JVM in a project based on gradle/maven
* @param dialogTitle - title of the configuring dialog (all dialogs are the same, but titles)
* @param kotlinVersion - kotlin version as it should be added to build.gradle/pom.xml
* @param module - if empty - all modules should be configured
* else a single module with the specified name should be configured
* @return true if configuration passed correctly, false in case of any errors, for example
* if required [kotlinVersion] is absent in the versions list.
* TODO: add setting of specified module name and kotlin version
* */
fun KotlinGuiTestCase.configureKotlinFromGradleMavenSelectValues(
dialogTitle: String,
kotlinVersion: String,
module: String = ""): Boolean {
var result = false
dialog(dialogTitle) {
if (module.isEmpty()) {
logUIStep("Select `All modules` option")
radioButton("All modules").select()
}
else {
logUIStep("Select `Single module` option")
radioButton("Single module:").select()
}
waitUntil("Wait for button OK is enabled") { button("OK").isEnabled }
val cmb = combobox("Kotlin compiler and runtime version:")
if (cmb.listItems().contains(kotlinVersion)) {
logTestStep("Select kotlin version `$kotlinVersion`")
if (cmb.selectedItem() != kotlinVersion) {
cmb
.expand()
.selectItem(kotlinVersion)
logInfo("Combobox `Kotlin compiler and runtime version`: current selected is ${cmb.selectedItem()} ")
}
logUIStep("Close Configure Kotlin dialog with OK")
button("OK").click()
result = true
}
else {
logUIStep("Close Configure Kotlin dialog with Cancel")
button("Cancel").click()
}
}
return result
}
fun KotlinGuiTestCase.configureKotlinJvmFromGradle(
kotlinVersion: String,
module: String = "") {
configureKotlinFromGradleMaven(
logText = "Open `Configure Kotlin with Java with Gradle` dialog",
menuTitle = "ConfigureKotlinInProject",
dialogTitle = "Configure Kotlin with Java with Gradle",
kotlinVersion = kotlinVersion,
module = module)
}
fun KotlinGuiTestCase.configureKotlinJsFromGradle(
kotlinVersion: String,
module: String = "") {
configureKotlinFromGradleMaven(
logText = "Open `Configure Kotlin with JavaScript with Gradle` dialog",
menuTitle = "ConfigureKotlinJsInProject",
dialogTitle = "Configure Kotlin with JavaScript with Gradle",
kotlinVersion = kotlinVersion,
module = module)
}
fun KotlinGuiTestCase.configureKotlinJvmFromMaven(
kotlinVersion: String,
module: String = "") {
configureKotlinFromGradleMaven(
logText = "Open `Configure Kotlin with Java with Maven` dialog",
menuTitle = "ConfigureKotlinInProject",
dialogTitle = "Configure Kotlin with Java with Maven",
kotlinVersion = kotlinVersion,
module = module)
}
fun KotlinGuiTestCase.configureKotlinJsFromMaven(
kotlinVersion: String,
module: String = "") {
configureKotlinFromGradleMaven(
logText = "Open `Configure Kotlin with JavaScript with Maven` dialog",
menuTitle = "ConfigureKotlinJsInProject",
dialogTitle = "Configure Kotlin with JavaScript with Maven",
kotlinVersion = kotlinVersion,
module = module)
}
/**
* Opens Project Structure dialog and Library tab
* Checks that an appropriate Kotlin library is created with a certain set of jar files
* what are expected to be taken from the project folder
* @param projectPath full path to the project
* @param kotlinKind kotlin kind (JVM or JS)
* */
fun ProjectStructureDialogScenarios.checkKotlinLibsInStructureFromProject(
projectPath: String,
kotlinKind: KotlinKind) {
val expectedJars = getKotlinLibInProject(projectPath)
.map { projectPath + File.separator + "lib" + File.separator + it }
val expectedLibName = kotlinLibs[kotlinKind]!!.kotlinProject.libName!!
openProjectStructureAndCheck {
projectStructureDialogModel.checkLibrariesFromIDEA(
expectedLibName,
expectedJars
)
}
}
/**
* Opens Project Structure dialog and Library tab
* Checks that an appropriate Kotlin library is created with a certain set of jar files
* what are expected to be taken from the plugin
* @param kotlinKind kotlin kind (JVM or JS)
* */
fun ProjectStructureDialogScenarios.checkKotlinLibsInStructureFromPlugin(
kotlinKind: KotlinKind,
kotlinVersion: String) {
val expectedLibName = kotlinLibs[kotlinKind]!!.kotlinProject.libName!!
val configPath = PathManager.getConfigPath().normalizeSeparator()
val expectedJars = kotlinLibs[kotlinKind]!!
.kotlinProject
.jars
.getJars(kotlinVersion)
.map { configPath + pathKotlinInConfig + File.separator + it }
openProjectStructureAndCheck {
projectStructureDialogModel.checkLibrariesFromIDEA(
expectedLibName,
expectedJars
)
}
}
/**
* Checks that a certain set of jar files is copied to the project folder
* @param projectPath full path to the project folder
* @param kotlinKind kotlin kind (JVM or JS)
* */
fun KotlinGuiTestCase.checkKotlinLibInProject(projectPath: String,
kotlinKind: KotlinKind,
kotlinVersion: String) {
val expectedLibs = kotlinLibs[kotlinKind]?.kotlinProject?.jars?.getJars(kotlinVersion) ?: return
val actualLibs = getKotlinLibInProject(projectPath)
expectedLibs.forEach {
logInfo("check if expected '$it' is present")
// collector.checkThat( actualLibs.contains(it), Matcher_Is(true) ) { "Expected, but absent file: $it" }
assert(actualLibs.contains(it)) { "Expected, but absent file: $it" }
}
actualLibs.forEach {
logInfo("check if existing '$it' is expected")
// collector.checkThat( expectedLibs.contains(it), Matcher_Is(true) ) { "Unexpected file: $it" }
assert(expectedLibs.contains(it)) { "Unexpected file: $it" }
}
}
fun KotlinGuiTestCase.createKotlinFile(
projectName: String,
packageName: String = "src",
fileName: String) {
ideFrame {
waitAMoment()
logTestStep("Create a Kotlin file `$fileName`")
toolwindow(id = "Project") {
projectView {
val treePath = listOf(projectName, *packageName.split("/", "").toTypedArray()).toTypedArray()
logUIStep("Click on the path: ")
treePath.forEach { logInfo(" $it") }
path(*treePath).click()
waitAMoment()
logUIStep("Invoke menu kotlin -> new file and open `New Kotlin File/Class` dialog")
invokeMainMenu("Kotlin.NewFile")
}
}
dialog("New Kotlin File/Class") {
logUIStep("Fill `Name` with `$fileName`")
textfield("Name:").click()
typeText(fileName)
logUIStep("Close `New Kotlin File/Class` dialog with OK")
button("OK").click()
}
waitAMoment()
}
}
fun KotlinGuiTestCase.makeTestRoot(projectPath: String, testRoot: String) {
ideFrame {
projectView {
path(projectPath, testRoot).doubleClick()
path(projectPath, testRoot).rightClick()
}
popup("Mark Directory as", "Test Sources Root")
}
}
fun KotlinGuiTestCase.editorSearchAndReplace(isRegex: Boolean, isReplaceAll: Boolean, search: String, vararg replace: String) {
ideFrame {
editor {
logTestStep("Change `$search` with `${replace.joinToString(" \\n ")}` in the currently open editor")
// Magic number to click to the file
// Problem: on HighDPI monitor moveTo(1) sometimes doesn't click to the file
waitAMoment()
moveTo(1)
waitAMoment()
shortcut(Modifier.CONTROL + Key.R)
if (checkbox("Regex").isSelected != isRegex) {
logUIStep("Change state of `Regex` option")
checkbox("Regex").click()
if (checkbox("Regex").isSelected != isRegex) {
logUIStep("Change state of `Regex` option. Attempt #2")
checkbox("Regex").click()
}
}
logUIStep("Search field: type `$search`")
typeText(search)
shortcut(Key.TAB)
for ((ind, str) in replace.withIndex()) {
logUIStep("Replace field: type `$str`")
typeText(str)
if (ind < replace.size - 1) {
logUIStep("Replace field: press Ctrl+Shift+Enter to add a new line")
shortcut(
Modifier.CONTROL + Modifier.SHIFT + Key.ENTER)
}
}
}
if (isReplaceAll)
button("Replace all").click()
else
button("Replace").click()
logUIStep("Close Search and Replace banner with Cancel")
shortcut(Key.ESCAPE)
// TODO: Remove Ctrl+Home after GUI-73 fixing
logUIStep("Put text cursor to the begin")
shortcut(Modifier.CONTROL + Key.HOME)
editorClearSearchAndReplace()
}
}
fun KotlinGuiTestCase.editorClearSearchAndReplace() {
ideFrame {
editor {
logTestStep("Clear search and replace fields in the currently open editor")
waitAMoment()
moveTo(1)
waitAMoment()
shortcut(Modifier.CONTROL + Key.R)
shortcut(Key.DELETE)
shortcut(Key.TAB)
shortcut(Key.DELETE)
}
logUIStep("Close Search and Replace banner with Cancel")
shortcut(Key.ESCAPE)
}
}
fun KotlinGuiTestCase.addDevRepositoryToBuildGradle(fileName: Path, isKotlinDslUsed: Boolean) {
val mavenCentral = "mavenCentral()"
val urlGDsl = "maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }"
val urlKDsl = "maven { setUrl (\"https://dl.bintray.com/kotlin/kotlin-dev/\") }"
if (isKotlinDslUsed)
fileSearchAndReplace(fileName = fileName) {
if(it.contains(mavenCentral))
listOf(mavenCentral, urlKDsl).joinToString(separator = "\n")
else it
}
else
fileSearchAndReplace(fileName = fileName) {
if(it.contains(mavenCentral))
listOf(mavenCentral, urlGDsl).joinToString(separator = "\n")
else it
}
}
fun KotlinGuiTestCase.addDevRepositoryToPomXml(fileName: Path) {
val searchedLine = """</dependencies>"""
val changingLine = """
<repositories>
<repository>
<id>kotlin-dev</id>
<url>https://dl.bintray.com/kotlin/kotlin-dev</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>kotlin-dev</id>
<url>https://dl.bintray.com/kotlin/kotlin-dev</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
""".split("\n").toTypedArray()
fileSearchAndReplace(fileName = fileName) {
if(it.contains(searchedLine))
listOf(searchedLine, *changingLine).joinToString(separator = "\n")
else it
}
}
fun KotlinGuiTestCase.changeKotlinVersionInBuildGradle(fileName: Path,
isKotlinDslUsed: Boolean,
kotlinVersion: String) {
fileSearchAndReplace( fileName = fileName){
if (it.contains("kotlin")){
val regex = """(id|kotlin)\s?\(?[\'\"](.*)[\'\"]\)? version [\'\"](.*)[\'\"]"""
.trimIndent()
.toRegex(RegexOption.IGNORE_CASE)
if(regex.find(it) != null)
it.replace(regex.find(it)!!.groupValues[3], kotlinVersion)
else it
}
else it
}
}
fun KotlinGuiTestCase.changeKotlinVersionInPomXml(fileName: Path, kotlinVersion: String) {
val oldVersion = "<kotlin\\.version>.+<\\/kotlin\\.version>"
val newVersion = "<kotlin.version>$kotlinVersion</kotlin.version>"
fileSearchAndReplace(fileName = fileName) {
if(it.contains(oldVersion.toRegex(RegexOption.IGNORE_CASE)))
newVersion
else it
}
}
fun KotlinGuiTestCase.openFileFromProjectView(vararg fileName: String) {
ideFrame {
projectView {
logTestStep("Open ${fileName.toList()}")
path(*fileName).click()
shortcut(Key.RIGHT)
path(*fileName).click()
logUIStep("clicked on the path ${fileName.toList()} and going to double click it")
waitAMoment()
path(*fileName).doubleClick()
}
}
}
fun KotlinGuiTestCase.openBuildGradle(isKotlinDslUsed: Boolean, vararg projectName: String) {
val buildGradleName = "build.gradle${if (isKotlinDslUsed) ".kts" else ""}"
openFileFromProjectView(*projectName, buildGradleName)
}
fun KotlinGuiTestCase.openPomXml(vararg projectName: String) {
openFileFromProjectView(*projectName, "pom.xml")
}
fun KotlinGuiTestCase.editSettingsGradle(){
// if project is configured to old Kotlin version, it must be released and no changes are required in the settings.gradle file
if (!KotlinTestProperties.isActualKotlinUsed()) return
val fileName = Paths.get(projectFolder, "settings.gradle")
if (KotlinTestProperties.isArtifactOnlyInDevRep) addDevRepositoryToBuildGradle(fileName, isKotlinDslUsed = false)
}
fun KotlinGuiTestCase.editBuildGradle(
kotlinVersion: String,
isKotlinDslUsed: Boolean = false,
vararg projectName: String = emptyArray()) {
// if project is configured to old Kotlin version, it must be released and no changes are required in the build.gradle file
if (!KotlinTestProperties.isActualKotlinUsed()) return
val fileName = Paths.get(projectFolder, *projectName , "build.gradle${if (isKotlinDslUsed) ".kts" else ""}")
logTestStep("Going to edit $fileName")
if (KotlinTestProperties.isArtifactOnlyInDevRep) addDevRepositoryToBuildGradle(fileName, isKotlinDslUsed)
if (!KotlinTestProperties.isArtifactPresentInConfigureDialog && KotlinTestProperties.kotlin_plugin_version_main != kotlinVersion)
changeKotlinVersionInBuildGradle(fileName, isKotlinDslUsed, kotlinVersion)
}
fun KotlinGuiTestCase.editPomXml(kotlinVersion: String,
kotlinKind: KotlinKind,
vararg projectName: String = emptyArray()) {
// if project is configured to old Kotlin version, it must be released and no changes are required in the pom.xml file
if (!KotlinTestProperties.isActualKotlinUsed()) return
val fileName = Paths.get(projectFolder, *projectName, "pom.xml")
logTestStep("Going to edit $fileName")
if (KotlinTestProperties.isArtifactOnlyInDevRep) addDevRepositoryToPomXml(fileName)
if (!KotlinTestProperties.isArtifactPresentInConfigureDialog && KotlinTestProperties.kotlin_plugin_version_main != kotlinVersion)
changeKotlinVersionInPomXml(fileName, kotlinVersion)
}
fun getVersionFromString(versionString: String): LanguageVersion {
val match = """^\d+\.\d+""".toRegex().find(versionString) ?: throw IllegalArgumentException(
"Incorrect version of Kotlin artifact '$versionString'")
val result = match.groups[0]!!.value
return LanguageVersion.valueFromString(result)
}
fun KotlinGuiTestCase.checkFacetState(facet: FacetStructure) {
fun <T> checkValueWithLog(title: String, expectedValue: T, actualValue: T) {
val message = "Option: '$title', expected: '$expectedValue', actual: '$actualValue'"
logInfo(message)
assert(actualValue == expectedValue) { message }
}
dialogWithoutClosing("Project Structure") {
fun checkCombobox(title: String, expectedValue: String) {
checkValueWithLog(title, expectedValue, actualValue = combobox(title).selectedItem() ?: "")
}
fun checkCheckbox(title: String, expectedValue: Boolean) {
checkValueWithLog(title, expectedValue, actualValue = checkbox(title).target().isSelected)
}
fun checkTextfield(title: String, expectedValue: String) {
checkValueWithLog(title, expectedValue, actualValue = textfield(title).text() ?: "")
}
checkCombobox("Target platform: ", facet.targetPlatform.toString())
checkCheckbox("Report compiler warnings", facet.reportCompilerWarnings)
checkCombobox("Language version", facet.languageVersion.toString())
checkCombobox("API version", facet.apiVersion.toString())
checkTextfield("Additional command line parameters:", facet.cmdParameters)
if (facet.jvmOptions != null) {
checkTextfield("Script template classes:", facet.jvmOptions.templateClasses)
checkTextfield("Script templates classpath:", facet.jvmOptions.templatesClassPath)
}
if (facet.jsOptions != null) {
checkCheckbox("Generate source maps", facet.jsOptions.generateSourceMap)
checkTextfield("Add prefix to paths in source map:", facet.jsOptions.sourceMapPrefix)
checkCombobox("Embed source code into source map:", facet.jsOptions.embedSourceCode2Map.toString())
checkTextfield("File to prepend to generated code:", facet.jsOptions.fileToPrepend)
checkTextfield("File to append to generated code:", facet.jsOptions.fileToAppend)
checkCombobox("Module kind:", facet.jsOptions.moduleKind.toString())
checkCheckbox("Copy library runtime files", facet.jsOptions.copyLibraryRuntimeFiles)
checkTextfield("Destination directory", facet.jsOptions.destinationDirectory)
val runtimeLibs = checkbox("Copy library runtime files").target().isSelected
val destDirEnabled = textfield("Destination directory").isEnabled
assert(
runtimeLibs == destDirEnabled) { "Option: 'Destination directory', expected enabled stated: '$runtimeLibs', actual: '$destDirEnabled'" }
}
}
}
// TODO: remove it after GUI-59 fixing
fun KotlinGuiTestCase.dialogWithoutClosing(title: String? = null,
ignoreCaseTitle: Boolean = false,
timeout: Timeout = defaultTimeout,
func: JDialogFixture.() -> Unit) {
val dialog = dialog(title, ignoreCaseTitle, timeout)
func(dialog)
}
fun KotlinGuiTestCase.saveAndCloseCurrentEditor() {
ideFrame {
editor {
logTestStep("Going to save and close currently opened file")
shortcut(Modifier.CONTROL + Key.S)
shortcut(Modifier.CONTROL + Key.F4)
}
}
}
fun KotlinGuiTestCase.testCreateGradleAndConfigureKotlin(
kotlinKind: KotlinKind,
kotlinVersion: String,
project: ProjectProperties,
expectedFacet: FacetStructure,
gradleOptions: NewProjectDialogModel.GradleProjectOptions) {
if (!isIdeFrameRun()) return
val extraTimeOut = 4000L
createGradleProject(
projectPath = projectFolder,
gradleOptions = gradleOptions)
waitAMoment(extraTimeOut)
when (kotlinKind) {
KotlinKind.JVM -> configureKotlinJvmFromGradle(kotlinVersion)
KotlinKind.JS -> configureKotlinJsFromGradle(kotlinVersion)
else -> throw IllegalStateException("Cannot configure to Kotlin/Common kind.")
}
waitAMoment(extraTimeOut)
saveAndCloseCurrentEditor()
editSettingsGradle()
editBuildGradle(
kotlinVersion = kotlinVersion,
isKotlinDslUsed = gradleOptions.useKotlinDsl
)
waitAMoment(extraTimeOut)
gradleReimport()
waitAMoment(extraTimeOut)
projectStructureDialogScenarios.checkGradleExplicitModuleGroups(
project = project,
kotlinVersion = kotlinVersion,
projectName = gradleOptions.artifact,
expectedFacet = expectedFacet
)
}
fun ProjectStructureDialogScenarios.checkGradleExplicitModuleGroups(
project: ProjectProperties,
kotlinVersion: String,
projectName: String,
expectedFacet: FacetStructure
) {
openProjectStructureAndCheck {
projectStructureDialogModel.checkLibrariesFromMavenGradle(
buildSystem = BuildSystem.Gradle,
kotlinVersion = kotlinVersion,
expectedJars = project.jars.getJars(kotlinVersion)
)
projectStructureDialogModel.checkFacetInOneModule(
expectedFacet,
"$projectName", "${projectName}_main", "Kotlin"
)
projectStructureDialogModel.checkFacetInOneModule(
expectedFacet,
"$projectName", "${projectName}_test", "Kotlin"
)
}
}
fun KotlinGuiTestCase.createKotlinMPProject(
projectPath: String,
moduleName: String,
mppProjectStructure: NewProjectDialogModel.MppProjectStructure,
setOfMPPModules: Set<KotlinKind>
) {
assert(setOfMPPModules.contains(KotlinKind.Common)) { "At least common MPP module should be specified" }
logTestStep("Create new MPP project with modules $setOfMPPModules")
welcomePageDialogModel.createNewProject()
newProjectDialogModel.assertGroupPresent(NewProjectDialogModel.Groups.Kotlin)
newProjectDialogModel.createKotlinMPProject(
projectPath = projectPath,
moduleName = moduleName,
mppProjectStructure = mppProjectStructure,
isJvmIncluded = setOfMPPModules.contains(KotlinKind.JVM),
isJsIncluded = setOfMPPModules.contains(KotlinKind.JS)
)
} | apache-2.0 | ff1ee2fa3d03e1b51ddf7492d7f7237f | 37.152448 | 144 | 0.709546 | 4.608549 | false | true | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/queries/StreamMeasurements.kt | 1 | 4971 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.queries
import com.google.cloud.spanner.Statement
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filter
import org.wfanet.measurement.gcloud.common.toGcloudTimestamp
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.bind
import org.wfanet.measurement.internal.kingdom.Measurement
import org.wfanet.measurement.internal.kingdom.StreamMeasurementsRequest
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementReader
class StreamMeasurements(
view: Measurement.View,
private val requestFilter: StreamMeasurementsRequest.Filter,
limit: Int = 0
) : SpannerQuery<MeasurementReader.Result, MeasurementReader.Result>() {
override val reader =
MeasurementReader(view).fillStatementBuilder {
appendWhereClause(requestFilter)
when (view) {
Measurement.View.COMPUTATION ->
appendClause("ORDER BY UpdateTime ASC, ExternalComputationId ASC")
Measurement.View.DEFAULT ->
appendClause("ORDER BY UpdateTime ASC, ExternalMeasurementId ASC")
Measurement.View.UNRECOGNIZED -> error("Unrecognized View")
}
if (limit > 0) {
appendClause("LIMIT @$LIMIT_PARAM")
bind(LIMIT_PARAM to limit.toLong())
}
}
private fun Statement.Builder.appendWhereClause(filter: StreamMeasurementsRequest.Filter) {
val conjuncts = mutableListOf<String>()
if (filter.externalMeasurementConsumerId != 0L) {
conjuncts.add("ExternalMeasurementConsumerId = @$EXTERNAL_MEASUREMENT_CONSUMER_ID_PARAM")
bind(EXTERNAL_MEASUREMENT_CONSUMER_ID_PARAM to filter.externalMeasurementConsumerId)
}
if (filter.externalMeasurementConsumerCertificateId != 0L) {
conjuncts.add(
"ExternalMeasurementConsumerCertificateId = " +
"@$EXTERNAL_MEASUREMENT_CONSUMER_CERTIFICATE_ID_PARAM"
)
bind(
EXTERNAL_MEASUREMENT_CONSUMER_CERTIFICATE_ID_PARAM to
filter.externalMeasurementConsumerCertificateId
)
}
if (filter.statesValueList.isNotEmpty()) {
conjuncts.add("Measurements.State IN UNNEST(@$STATES_PARAM)")
bind(STATES_PARAM).toInt64Array(filter.statesValueList.map { it.toLong() })
}
if (filter.hasUpdatedAfter()) {
if (filter.hasExternalMeasurementIdAfter()) {
conjuncts.add(
"""
((UpdateTime > @$UPDATED_AFTER)
OR (UpdateTime = @$UPDATED_AFTER
AND ExternalMeasurementId > @$EXTERNAL_MEASUREMENT_ID_AFTER))
"""
.trimIndent()
)
bind(EXTERNAL_MEASUREMENT_ID_AFTER).to(filter.externalMeasurementIdAfter)
} else if (filter.hasExternalComputationIdAfter()) {
conjuncts.add(
"""
((UpdateTime > @$UPDATED_AFTER)
OR (UpdateTime = @$UPDATED_AFTER
AND ExternalComputationId > @$EXTERNAL_COMPUTATION_ID_AFTER))
"""
.trimIndent()
)
bind(EXTERNAL_COMPUTATION_ID_AFTER).to(filter.externalComputationIdAfter)
} else {
error("external_measurement_id_after or external_measurement_id_after required")
}
bind(UPDATED_AFTER to filter.updatedAfter.toGcloudTimestamp())
}
if (conjuncts.isEmpty()) {
return
}
appendClause("WHERE ")
append(conjuncts.joinToString(" AND "))
}
override fun Flow<MeasurementReader.Result>.transform(): Flow<MeasurementReader.Result> {
// TODO(@tristanvuong): determine how to do this in the SQL query instead
if (requestFilter.externalDuchyId.isBlank()) {
return this
}
return filter { value: MeasurementReader.Result ->
value.measurement.computationParticipantsList
.map { it.externalDuchyId }
.contains(requestFilter.externalDuchyId)
}
}
companion object {
const val LIMIT_PARAM = "limit"
const val EXTERNAL_MEASUREMENT_CONSUMER_ID_PARAM = "externalMeasurementConsumerId"
const val EXTERNAL_MEASUREMENT_CONSUMER_CERTIFICATE_ID_PARAM =
"externalMeasurementConsumerCertificateId"
const val UPDATED_AFTER = "updatedAfter"
const val STATES_PARAM = "states"
const val EXTERNAL_MEASUREMENT_ID_AFTER = "externalMeasurementIdAfter"
const val EXTERNAL_COMPUTATION_ID_AFTER = "externalComputationIdAfter"
}
}
| apache-2.0 | e0c175d9b2158727052e239847c4c6c4 | 37.238462 | 95 | 0.71032 | 4.466307 | false | false | false | false |
cempo/SimpleTodoList | app/src/main/java/com/makeevapps/simpletodolist/ui/dialog/AlertDialog.kt | 1 | 3627 | package com.makeevapps.simpletodolist.ui.dialog
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import com.afollestad.materialdialogs.MaterialDialog
import com.makeevapps.simpletodolist.R
import com.orhanobut.logger.Logger
object AlertDialog {
@SuppressLint("StaticFieldLeak")
private var dialog: MaterialDialog? = null
private var mHandler: Handler? = null
@Synchronized
fun showPermissionRationaleDialog(context: Context, permissionName: String,
positiveCallback: MaterialDialog.SingleButtonCallback?) {
val title = R.string.permission_rationale_title
val text = R.string.permission_rationale_text
val buttonText = R.string.settings
showDialog(context, title, text, buttonText, positiveCallback, null)
}
@Synchronized
fun showCancelChangesDialog(context: Context, permissionName: String,
positiveCallback: MaterialDialog.SingleButtonCallback?) {
val title = R.string.permission_rationale_title
val text = R.string.permission_rationale_text
val buttonText = R.string.settings
showDialog(context, title, text, buttonText, positiveCallback, null)
}
@Synchronized
fun showDialog(context: Context, titleResId: Int, textResId: Int, buttonTextResId: Int,
positiveCallback: MaterialDialog.SingleButtonCallback?,
onDismissListener: DialogInterface.OnDismissListener?) {
var title = ""
if (titleResId != 0) {
title = context.getString(titleResId)
}
var text = ""
if (textResId != 0) {
text = context.getString(textResId)
}
var buttonText = ""
if (textResId != 0) {
buttonText = context.getString(buttonTextResId)
}
showDialog(context, title, text, buttonText, positiveCallback, onDismissListener)
}
@Synchronized
fun showDialog(context: Context?, title: String, text: String,
positiveButtonText: String,
positiveCallback: MaterialDialog.SingleButtonCallback?,
onDismissListener: DialogInterface.OnDismissListener?) {
dismissDialog()
if (context != null) {
val builder = MaterialDialog.Builder(context)
if (!TextUtils.isEmpty(title)) {
builder.title(title)
}
if (!TextUtils.isEmpty(text)) {
builder.content(text)
}
if (positiveCallback != null) {
builder.positiveText(positiveButtonText)
builder.onPositive(positiveCallback)
}
builder.negativeText(R.string.cancel)
if (onDismissListener != null) {
builder.dismissListener(onDismissListener)
}
if (mHandler == null)
mHandler = Handler(Looper.getMainLooper())
mHandler!!.post {
try {
dialog = builder.show()
} catch (e: Exception) {
Logger.e("Show error dialog: $e")
}
}
}
}
@Synchronized
fun dismissDialog() {
if (dialog != null && dialog!!.isShowing) {
try {
dialog!!.dismiss()
} catch (e: IllegalArgumentException) {
Logger.e("Dismiss error dialog: $e")
}
}
}
} | mit | beafefbf564209256896dba0cfb6568d | 32.284404 | 95 | 0.598566 | 5.318182 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/SeasonDetailsActivity.kt | 1 | 4605 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import dagger.android.AndroidInjection
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.instantiate
import net.simonvt.cathode.common.util.FragmentStack.StackEntry
import net.simonvt.cathode.ui.show.EpisodeFragment
import net.simonvt.cathode.ui.show.SeasonFragment
import net.simonvt.cathode.ui.show.SeasonViewModel
import net.simonvt.cathode.ui.show.ShowFragment
import timber.log.Timber
import java.util.ArrayList
import javax.inject.Inject
class SeasonDetailsActivity : NavigationListenerActivity() {
private var seasonId: Long = -1L
private var showId: Long = -1L
private var seasonNumber: Int = -1
@Inject
lateinit var viewModelFactory: CathodeViewModelFactory
private lateinit var viewModel: SeasonViewModel
override fun onCreate(inState: Bundle?) {
setTheme(R.style.Theme)
super.onCreate(inState)
AndroidInjection.inject(this)
setContentView(R.layout.activity_details)
seasonId = intent.getLongExtra(EXTRA_ID, -1L)
if (seasonId == -1L) {
Timber.e(Exception("Invalid season ID"))
finish()
} else {
if (inState == null) {
val fragment = supportFragmentManager.instantiate(
SeasonFragment::class.java,
SeasonFragment.getArgs(seasonId, null, seasonNumber, LibraryType.WATCHED)
)
supportFragmentManager.beginTransaction()
.add(R.id.content, fragment, SeasonFragment.getTag(seasonId))
.commit()
}
viewModel = ViewModelProviders.of(this, viewModelFactory).get(SeasonViewModel::class.java)
viewModel.setSeasonId(seasonId)
viewModel.season.observe(this, Observer {
showId = it.showId
seasonNumber = it.season
})
}
}
override fun onHomeClicked() {
if (showId == -1L) return
val stack = ArrayList<StackEntry>()
val showEntry = StackEntry(
ShowFragment::class.java,
ShowFragment.getTag(showId),
ShowFragment.getArgs(showId, null, null, LibraryType.WATCHED)
)
stack.add(showEntry)
val i = Intent(this, HomeActivity::class.java)
i.action = HomeActivity.ACTION_REPLACE_STACK
i.putParcelableArrayListExtra(HomeActivity.EXTRA_STACK_ENTRIES, stack)
startActivity(i)
finish()
}
override fun onDisplayEpisode(episodeId: Long, showTitle: String?) {
if (showId == -1L) return
val stack = ArrayList<StackEntry>()
val showEntry = StackEntry(
ShowFragment::class.java,
ShowFragment.getTag(showId),
ShowFragment.getArgs(showId, null, null, LibraryType.WATCHED)
)
stack.add(showEntry)
val seasonEntry = StackEntry(
SeasonFragment::class.java,
SeasonFragment.getTag(seasonId),
SeasonFragment.getArgs(seasonId, null, -1, LibraryType.WATCHED)
)
stack.add(seasonEntry)
val episodeEntry = StackEntry(
EpisodeFragment::class.java,
EpisodeFragment.getTag(episodeId),
EpisodeFragment.getArgs(showId, null)
)
stack.add(episodeEntry)
val i = Intent(this, HomeActivity::class.java)
i.action = HomeActivity.ACTION_REPLACE_STACK
i.putParcelableArrayListExtra(HomeActivity.EXTRA_STACK_ENTRIES, stack)
startActivity(i)
finish()
}
companion object {
const val EXTRA_ID = "net.simonvt.cathode.ui.SeasonDetailsActivity.id"
@JvmStatic
fun createUri(seasonId: Long): Uri {
return Uri.parse("cathode://season/$seasonId")
}
fun createIntent(context: Context, uri: Uri): Intent? {
val idSegment = uri.pathSegments[0]
val id = if (!idSegment.isNullOrEmpty()) idSegment.toLong() else -1L
if (id > -1L) {
val intent = Intent(context, SeasonDetailsActivity::class.java)
intent.putExtra(EXTRA_ID, id)
return intent
}
return null
}
}
}
| apache-2.0 | 5cc19d33bb3b692fc3f9685538af36e4 | 29.296053 | 96 | 0.710532 | 4.163653 | false | false | false | false |
TWiStErRob/TWiStErRob | LeetCode2020April/week1/src/test/kotlin/net/twisterrob/challenges/leetcode2020april/week1/happy_number/HasRepeatingElementTest.kt | 1 | 2461 | package net.twisterrob.challenges.leetcode2020april.week1.happy_number
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.TestFactory
class HasRepeatingElementTest {
@TestFactory fun `distinct sequences don't have repeating elements`() = arrayOf(
hasRepeatingElementTest(false, 1),
hasRepeatingElementTest(false, 1, 2),
hasRepeatingElementTest(false, 1, 2, 3),
hasRepeatingElementTest(false, 1, 2, 3, 4),
hasRepeatingElementTest(false, 1, 2, 3, 4, 5),
)
@TestFactory fun `uniform sequences have repeating elements`() = arrayOf(
hasRepeatingElementTest(true, 1, 1),
hasRepeatingElementTest(true, 1, 1, 1),
hasRepeatingElementTest(true, 1, 1, 1, 1),
hasRepeatingElementTest(true, 1, 1, 1, 1, 1, 1),
hasRepeatingElementTest(true, 1, 2, 1, 2, 1, 2),
hasRepeatingElementTest(true, 1, 2, 3, 1, 2, 3, 1, 2, 3),
)
@TestFactory fun `alternating sequences have repeating elements`() = arrayOf(
hasRepeatingElementTest(true, 1, 2, 1, 2),
hasRepeatingElementTest(true, 1, 2, 1, 2, 1, 2),
hasRepeatingElementTest(true, 1, 2, 1, 2, 1, 2, 1, 2),
)
@TestFactory fun `repeating sequences have repeating elements`() = arrayOf(
hasRepeatingElementTest(true, 1, 2, 3, 1, 2, 3),
hasRepeatingElementTest(true, 1, 2, 3, 1, 2, 3, 1, 2, 3),
hasRepeatingElementTest(true, 1, 2, 3, 4, 1, 2, 3, 4),
hasRepeatingElementTest(true, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
)
@TestFactory fun `infinite repeating sequences have repeating elements`() = arrayOf(
hasRepeatingElementTest(true, generateSequence(0) { 1 }),
hasRepeatingElementTest(true, generateSequence(0, object : Function1<Int, Int> {
private var flag = false
override fun invoke(ignored: Int): Int {
flag = !flag
return if (flag) 1 else 2
}
})),
)
private fun hasRepeatingElementTest(hasRepeating: Boolean, vararg elements: Int) =
dynamicTest("sequence of ${elements.toList()} has repeating elements: $hasRepeating") {
testHasRepeatingElement(hasRepeating, elements.asSequence())
}
private fun hasRepeatingElementTest(hasRepeating: Boolean, input: Sequence<Int>) =
dynamicTest("sequence of ${input} has repeating elements: $hasRepeating") {
testHasRepeatingElement(hasRepeating, input)
}
private fun testHasRepeatingElement(hasRepeating: Boolean, input: Sequence<Int>) {
val result = input.hasRepeatingElement()
assertEquals(hasRepeating, result)
}
}
| unlicense | 50c7aa1e4fc9cda54ec09bbc6e9e77d9 | 36.861538 | 89 | 0.726128 | 3.371233 | false | true | false | false |
GuiyeC/Aerlink-for-Android | wear/src/main/java/com/codegy/aerlink/service/media/AMSContract.kt | 1 | 1283 | package com.codegy.aerlink.service.media
import android.content.Context
import com.codegy.aerlink.connection.CharacteristicIdentifier
import com.codegy.aerlink.service.ServiceContract
import com.codegy.aerlink.service.ServiceManager
import com.codegy.aerlink.utils.CommandHandler
import java.util.UUID
/**
* https://developer.apple.com/library/archive/documentation/CoreBluetooth/Reference/AppleMediaService_Reference/Introduction/Introduction.html
*/
object AMSContract: ServiceContract {
// AMS - Apple Media Service Profile
override val serviceUuid: UUID = UUID.fromString("89d3502b-0f36-433a-8ef4-c502ad55f8dc")
val remoteCommandCharacteristicUuid: UUID = UUID.fromString("9b3c81d8-57b1-4a8a-b8df-0e56f7ca51c2")
val entityUpdateCharacteristicUuid: UUID = UUID.fromString("2f7cabce-808d-411f-9a0c-bb92ba96c102")
val entityAttributeCharacteristicUuid: UUID = UUID.fromString("c6b2f38c-23ab-46d8-a6ab-a3a870bbd5d7")
override val characteristicsToSubscribe: List<CharacteristicIdentifier> = listOf(
CharacteristicIdentifier(serviceUuid, entityUpdateCharacteristicUuid)
)
override fun createManager(context: Context, commandHandler: CommandHandler): ServiceManager {
return MediaServiceManager(context, commandHandler)
}
} | mit | d9f08672709b7fda90f09698389c66db | 46.555556 | 143 | 0.806703 | 3.634561 | false | false | false | false |
GeoffreyMetais/vlc-android | application/television/src/main/java/org/videolan/television/viewmodel/MediaBrowserViewModel.kt | 1 | 2248 | package org.videolan.television.viewmodel
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.vlc.providers.medialibrary.*
import org.videolan.resources.CATEGORY_ALBUMS
import org.videolan.resources.CATEGORY_ARTISTS
import org.videolan.resources.CATEGORY_GENRES
import org.videolan.resources.CATEGORY_VIDEOS
import org.videolan.vlc.viewmodels.MedialibraryViewModel
import org.videolan.vlc.viewmodels.tv.TvBrowserModel
@ExperimentalCoroutinesApi
class MediaBrowserViewModel(context: Context, val category: Long, val parent : MediaLibraryItem?) : MedialibraryViewModel(context), TvBrowserModel<MediaLibraryItem> {
override var nbColumns = 0
override var currentItem: MediaLibraryItem? = parent
override val provider = when (category) {
CATEGORY_ALBUMS -> AlbumsProvider(parent, context, this)
CATEGORY_ARTISTS -> ArtistsProvider(context, this, true)
CATEGORY_GENRES -> GenresProvider(context, this)
CATEGORY_VIDEOS -> VideosProvider(null, null, context, this)
else -> TracksProvider(null, context, this)
}
override val providers = arrayOf(provider)
init {
when(category){
CATEGORY_ALBUMS -> watchAlbums()
CATEGORY_ARTISTS -> watchArtists()
CATEGORY_GENRES -> watchGenres()
else -> watchMedia()
}
}
class Factory(private val context: Context, private val category: Long, private val parent : MediaLibraryItem?) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return MediaBrowserViewModel(context.applicationContext, category, parent) as T
}
}
}
@ExperimentalCoroutinesApi
fun Fragment.getMediaBrowserModel(category: Long, parent : MediaLibraryItem? = null) = ViewModelProviders.of(requireActivity(), MediaBrowserViewModel.Factory(requireContext(), category, parent)).get(MediaBrowserViewModel::class.java)
| gpl-2.0 | 6276203b3e15e5dc22924cde57364a41 | 41.415094 | 233 | 0.753559 | 4.919037 | false | false | false | false |
didi/DoraemonKit | Android/dokit-no-op/src/main/java/com/didichuxing/doraemonkit/DoKit.kt | 1 | 7775 | package com.didichuxing.doraemonkit
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.view.View
import com.didichuxing.doraemonkit.kit.AbstractKit
import com.didichuxing.doraemonkit.kit.core.*
import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.DokitExtInterceptor
import com.didichuxing.doraemonkit.kit.performance.PerformanceValueListener
import com.didichuxing.doraemonkit.kit.webdoor.WebDoorManager
import java.lang.NullPointerException
import kotlin.reflect.KClass
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:4/7/21-16:00
* 描 述:DoKit 入口类
* 修订历史:
* ================================================
*/
public class DoKit private constructor() {
companion object {
const val TAG = "DoKit"
/**
* 主icon是否处于显示状态
*/
@JvmStatic
val isMainIconShow: Boolean
get() = false
/**
* 显示主icon
*/
@JvmStatic
fun show() {
}
/**
* 直接显示工具面板页面
*/
@JvmStatic
fun showToolPanel() {
}
/**
* 直接隐藏工具面板
*/
@JvmStatic
fun hideToolPanel() {
}
/**
* 隐藏主icon
*/
@JvmStatic
fun hide() {
}
/**
* 启动悬浮窗
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
@JvmOverloads
fun launchFloating(
targetClass: Class<out AbsDokitView>,
mode: DoKitViewLaunchMode = DoKitViewLaunchMode.SINGLE_INSTANCE,
bundle: Bundle? = null
) {
}
/**
* 启动悬浮窗
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
@JvmOverloads
fun launchFloating(
targetClass: KClass<out AbsDokitView>,
mode: DoKitViewLaunchMode = DoKitViewLaunchMode.SINGLE_INSTANCE,
bundle: Bundle? = null
) {
}
/**
* 移除悬浮窗
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
fun removeFloating(targetClass: Class<out AbsDokitView>) {
}
/**
* 移除悬浮窗
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
fun removeFloating(targetClass: KClass<out AbsDokitView>) {
}
/**
* 移除悬浮窗
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
fun removeFloating(dokitView: AbsDokitView) {
}
/**
* 启动全屏页面
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
@JvmOverloads
fun launchFullScreen(
targetClass: Class<out BaseFragment>,
context: Context? = null,
bundle: Bundle? = null,
isSystemFragment: Boolean = false
) {
}
/**
* 启动全屏页面
* @JvmStatic:允许使用java的静态方法的方式调用
* @JvmOverloads :在有默认参数值的方法中使用@JvmOverloads注解,则Kotlin就会暴露多个重载方法。
*/
@JvmStatic
@JvmOverloads
fun launchFullScreen(
targetClass: KClass<out BaseFragment>,
context: Context? = null,
bundle: Bundle? = null,
isSystemFragment: Boolean = false
) {
}
@JvmStatic
fun <T : AbsDokitView> getDoKitView(
activity: Activity?,
clazz: Class<out T>
): T? {
return null
}
@JvmStatic
fun <T : AbsDokitView> getDoKitView(
activity: Activity?,
clazz: KClass<out T>
): T? {
return null
}
/**
* 发送自定义一机多控事件
*/
@JvmStatic
fun sendCustomEvent(
eventType: String,
view: View? = null,
param: Map<String, String>? = null
) {
}
/**
* 获取一机多控类型
*/
@JvmStatic
fun mcMode(): String {
return ""
}
}
class Builder(private val app: Application) {
private var productId: String = ""
private var mapKits: LinkedHashMap<String, List<AbstractKit>> = linkedMapOf()
private var listKits: List<AbstractKit> = arrayListOf()
init {
}
fun productId(productId: String): Builder {
return this
}
/**
* mapKits & listKits 二选一
*/
fun customKits(mapKits: LinkedHashMap<String, List<AbstractKit>>): Builder {
return this
}
/**
* mapKits & listKits 二选一
*/
fun customKits(listKits: List<AbstractKit>): Builder {
return this
}
/**
* H5任意门全局回调
*/
fun webDoorCallback(callback: WebDoorManager.WebDoorCallback): Builder {
return this
}
/**
* 禁用app信息上传开关,该上传信息只为做DoKit接入量的统计,如果用户需要保护app隐私,可调用该方法进行禁用
*/
fun disableUpload(): Builder {
return this
}
fun debug(debug: Boolean): Builder {
return this
}
/**
* 是否显示主入口icon
*/
fun alwaysShowMainIcon(alwaysShow: Boolean): Builder {
return this
}
/**
* 设置加密数据库密码
*/
fun databasePass(map: Map<String, String>): Builder {
return this
}
/**
* 设置文件管理助手http端口号
*/
fun fileManagerHttpPort(port: Int): Builder {
return this
}
/**
* 一机多控端口号
*/
fun mcWSPort(port: Int): Builder {
return this
}
/**
* 一机多控自定义拦截器
*/
fun mcClientProcess(interceptor: McClientProcessor): Builder {
return this
}
/**
*设置dokit的性能监控全局回调
*/
fun callBack(callback: DoKitCallBack): Builder {
return this
}
/**
* 设置扩展网络拦截器的代理对象
*/
fun netExtInterceptor(extInterceptorProxy: DokitExtInterceptor.DokitExtInterceptorProxy): Builder {
return this
}
fun build() {
}
}
}
| apache-2.0 | 64e14bef26af6045691d7fd63421ce7e | 22.274306 | 107 | 0.514098 | 4.226356 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/compose/TaskEditRow.kt | 1 | 1120 | package org.tasks.compose
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ContentAlpha
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.unit.dp
@Composable
fun TaskEditRow(
iconRes: Int = 0,
icon: @Composable () -> Unit = {
TaskEditIcon(
id = iconRes,
modifier = Modifier
.alpha(ContentAlpha.medium)
.padding(
start = 16.dp,
top = 20.dp,
end = 32.dp,
bottom = 20.dp
)
)
},
content: @Composable () -> Unit,
onClick: (() -> Unit)? = null,
) {
Row(modifier = Modifier
.fillMaxWidth()
.clickable(
enabled = onClick != null,
onClick = { onClick?.invoke() }
)
) {
icon()
content()
}
} | gpl-3.0 | e2e780cfa7d393263ce695e0051bfdf6 | 25.690476 | 54 | 0.575 | 4.462151 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/n69shu.kt | 1 | 2056 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
class N69shu : DslJsoupNovelContext() {init {
site {
name = "69书吧"
baseUrl = "https://www.69shu.com"
logo =
"http://tiebapic.baidu.com/forum/w%3D580/sign=9e34182a39dda3cc0be4b82831e93905/84431926cffc1e175f800d845d90f603728de9b0.jpg"
}
search {
post {
// https://www.69shu.com/modules/article/search.php?searchkey=%B6%BC%CA%D0&searchtype=all
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchkey" to it
"searchtype" to "all"
"page" to "1"
}
}
document {
single("^/txt/") {
name("div.booknav2 > h1 > a")
author("div.booknav2 > p:nth-child(2) > a")
}
items("div.newbox > ul > li") {
// 这有点迷,浏览器解析的是div > h3 > a,但jsoup解析出来是div > a > h3 > a
name("> div.newnav h3 > a")
author("> div.newnav > div.labelbox > label:nth-child(1)")
}
}
}
// https://www.69shu.com/txt/35934.htm
bookIdRegex = "/txt/(\\d+)"
detailPageTemplate = "/txt/%s.htm"
detail {
document {
novel {
name("div.booknav2 > h1 > a")
author("div.booknav2 > p:nth-child(2) > a")
}
image("div.bookimg2 > img")
update("div.booknav2 > p:nth-child(5)", format = "更新:yyyy-MM-dd")
introduction("div.navtxt > p:nth-child(1)")
}
}
// https://www.69shu.com/35934/
chaptersPageTemplate = "/%s/"
chapters {
document {
items("#catalog > ul > li > a")
}
}
// https://www.69shu.com/txt/35934/26013675
contentPageTemplate = "/txt/%s"
content {
document {
items("div.txtnav", block = ownLinesSplitWhitespace())
}
}
}
}
| gpl-3.0 | 8be1c6a0a22a6d8146d64bcb76b57cf5 | 29.892308 | 136 | 0.500498 | 3.37479 | false | false | false | false |
andela-kogunde/CheckSmarter | app/src/main/kotlin/com/andela/checksmarter/utilities/MsgBox.kt | 1 | 844 | package com.andela.checksmarter.utilities
import android.content.Context
import android.support.design.widget.Snackbar
import android.view.View
import android.widget.Toast
/**
* Created by CodeKenn on 02/05/16.
*/
object MsgBox {
private var toast: Toast? = null
private var snackbar: Snackbar? = null
fun show(context: Context, message: String) {
if (toast != null) {
toast!!.cancel()
}
toast = Toast.makeText(context, message, Toast.LENGTH_SHORT)
toast!!.show()
}
fun show(view: View, message: String, action: String, clickListener: View.OnClickListener) {
if (snackbar != null) {
snackbar!!.dismiss()
}
snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(action, clickListener)
snackbar!!.show()
}
}
| mit | 76c3f30ad3ffaf57c4264346dd10d7fa | 24.575758 | 102 | 0.643365 | 4.097087 | false | false | false | false |
vitaorganizer/vitaorganizer | src/com/soywiz/vitaorganizer/ext/ProcessBuilderExt.kt | 2 | 1537 | package com.soywiz.vitaorganizer.ext
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.charset.Charset
fun runCmd(vararg args: String): ProcessResult = runCmd(args.toList())
fun runCmd(args: List<String>): ProcessResult = Runtime.getRuntime().exec(args.toTypedArray()).waitAndGetOutput()
val Process.isAliveJava6: Boolean
get() {
try {
exitValue()
return false
} catch (e: IllegalThreadStateException) {
return true
}
}
fun Process.waitAndGetOutput(): ProcessResult {
val outArray = ByteArrayOutputStream()
val errArray = ByteArrayOutputStream()
val out = this.inputStream
val err = this.errorStream
while (this.isAliveJava6) {
outArray.write(out.readAvailable())
errArray.write(err.readAvailable())
Thread.sleep(1L)
}
val exitCode = this.waitFor()
// Probably these two lines are not needed!
outArray.write(out.readAvailable())
errArray.write(err.readAvailable())
return ProcessResult(outArray.toByteArray(), errArray.toByteArray(), exitCode)
}
fun InputStream.readAvailable(): ByteArray {
val available = this.available()
if (available == 0) return byteArrayOf()
val data = ByteArray(available)
val read = this.read(data)
return data.sliceArray(0 until read)
}
class ProcessResult(val outputBytes: ByteArray, val errorBytes: ByteArray, val exitCode: Int) {
val output = outputBytes.toString(Charset.defaultCharset())
val error = errorBytes.toString(Charset.defaultCharset())
val outputError = output + error
val success: Boolean get() = exitCode == 0
} | gpl-3.0 | 62092846ff39b0a772725b5cf79089d9 | 27.481481 | 113 | 0.756018 | 3.739659 | false | false | false | false |
SpectraLogic/ds3_autogen | ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/response/BaseResponseGenerator.kt | 2 | 10086 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.generators.response
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Request
import com.spectralogic.ds3autogen.api.models.apispec.Ds3ResponseCode
import com.spectralogic.ds3autogen.go.models.response.Response
import com.spectralogic.ds3autogen.go.models.response.ResponseCode
import com.spectralogic.ds3autogen.go.utils.goIndent
import com.spectralogic.ds3autogen.utils.ConverterUtil.hasContent
import com.spectralogic.ds3autogen.utils.ConverterUtil.isEmpty
import com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil
import com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil.removePath
import com.spectralogic.ds3autogen.utils.ResponsePayloadUtil
import com.spectralogic.ds3autogen.utils.collections.GuavaCollectors
import java.util.stream.Collectors
open class BaseResponseGenerator : ResponseModelGenerator<Response>, ResponseModelGeneratorUtil {
/** Status codes are considered errors at this value and higher */
private val ERROR_THRESHOLD = 300
override fun generate(ds3Request: Ds3Request): Response {
val name = NormalizingContractNamesUtil.toResponseName(ds3Request.name)
val payloadStruct = toResponsePayloadStruct(ds3Request.ds3ResponseCodes)
val expectedCodes = toExpectedStatusCodes(ds3Request.ds3ResponseCodes)
val parseResponseMethod = toParseResponseMethod(name, payloadStruct, ds3Request.ds3ResponseCodes)
val responseCodes = toResponseCodeList(ds3Request.ds3ResponseCodes, name)
return Response(name, payloadStruct, expectedCodes, parseResponseMethod, responseCodes)
}
/**
* Creates the Go code for the response parse method if one is needed (i.e. there is a response payload
* which is defined by a Ds3Type). Else an empty string is returned.
*/
fun toParseResponseMethod(name: String, payloadStruct: String, ds3ResponseCodes: ImmutableList<Ds3ResponseCode>?): String {
if (isEmpty(ds3ResponseCodes) || !ResponsePayloadUtil.hasResponsePayload(ds3ResponseCodes)) {
return ""
}
val elementName = removePath(getResponsePayload(ds3ResponseCodes))
if (elementName == "String" || elementName == "java.lang.String") {
return ""
}
val modelName = name.decapitalize()
val dereference = toDereferenceResponsePayload(payloadStruct)
return "func ($modelName *$name) parse(webResponse WebResponse) error {\n" +
goIndent(1) + " return parseResponsePayload(webResponse, $dereference$modelName.$elementName)\n" +
"}"
}
/**
* Determines if a response payload needs to be de-referenced (i.e. not a pointer), or if
* it needs de-referencing in order to be parsed. Returns an ampersand '&' if de-referencing
* is needed, else it returns an empty string.
*/
fun toDereferenceResponsePayload(payloadStruct: String): String {
if (payloadStruct.contains("*")) {
return ""
}
return "&"
}
/**
* Converts a list of Ds3ResponseCodes into a list of ResponseCode models
*/
fun toResponseCodeList(ds3ResponseCodes: ImmutableList<Ds3ResponseCode>?, responseName: String): ImmutableList<ResponseCode> {
if (isEmpty(ds3ResponseCodes)) {
throw IllegalArgumentException("There must be at least one non-error response code")
}
return ds3ResponseCodes!!.stream()
.filter{ code -> code.code < ERROR_THRESHOLD }
.map { code -> toResponseCode(code, responseName) }
.collect(GuavaCollectors.immutableList())
}
/**
* Converts a Ds3ResponseCode into a ResponseCode model which contains the Go
* code for parsing the specified response.
*/
override fun toResponseCode(ds3ResponseCode: Ds3ResponseCode, responseName: String): ResponseCode {
return toStandardResponseCode(ds3ResponseCode, responseName)
}
/**
* Converts a Ds3ResponseCode into one of the standard ResponseCode configurations
*/
fun toStandardResponseCode(ds3ResponseCode: Ds3ResponseCode, responseName: String): ResponseCode {
if (isEmpty(ds3ResponseCode.ds3ResponseTypes)) {
throw IllegalArgumentException("Ds3ResponseCode does not have any response types " + ds3ResponseCode.code)
}
if (ds3ResponseCode.ds3ResponseTypes!![0].type.equals("null", ignoreCase = true)) {
return toNullPayloadResponseCode(ds3ResponseCode.code, responseName)
}
if (ds3ResponseCode.ds3ResponseTypes!![0].type.equals("java.lang.String", ignoreCase = true)) {
return toStringPayloadResponseCode(ds3ResponseCode.code, responseName)
}
return toPayloadResponseCode(ds3ResponseCode.code, responseName)
}
/**
* Creates the Go code for returning an empty response when there is no payload
*/
fun toNullPayloadResponseCode(code: Int, responseName: String): ResponseCode {
return ResponseCode(code, "return &$responseName{Headers: webResponse.Header()}, nil")
}
/**
* Creates the Go code for returning a string response payload
*/
fun toStringPayloadResponseCode(code: Int, responseName: String): ResponseCode {
val parseResponse = "content, err := getResponseBodyAsString(webResponse)\n" +
goIndent(2) + "if err != nil {\n" +
goIndent(3) + "return nil, err\n" +
goIndent(2) + "}\n" +
goIndent(2) + "return &$responseName{Content: content, Headers: webResponse.Header()}, nil"
return ResponseCode(code, parseResponse)
}
/**
* Creates the Go code for parsing a response with a payload
*/
fun toPayloadResponseCode(code: Int, responseName: String): ResponseCode {
val parseResponse = "var body $responseName\n" +
goIndent(2) + "if err := body.parse(webResponse); err != nil {\n" +
goIndent(3) + "return nil, err\n" +
goIndent(2) + "}\n" +
goIndent(2) + "body.Headers = webResponse.Header()\n" +
goIndent(2) + "return &body, nil"
return ResponseCode(code, parseResponse)
}
/**
* Retrieves the comma separated list of expected status codes
*/
fun toExpectedStatusCodes(responseCodes: ImmutableList<Ds3ResponseCode>?): String {
if (isEmpty(responseCodes)) {
return ""
}
return responseCodes!!.stream()
.filter { code -> code.code < ERROR_THRESHOLD }
.map { code -> code.code.toString() }
.collect(Collectors.joining(", "))
}
/**
* Retrieves the content of the response struct, which assumes a spectra defined
* Ds3Type.
*/
override fun toResponsePayloadStruct(expectedResponseCodes: ImmutableList<Ds3ResponseCode>?): String {
if (isEmpty(expectedResponseCodes)) {
throw IllegalArgumentException("Expected at least one response payload")
}
val responsePayloadType = getResponsePayload(expectedResponseCodes)
// Check if response payload is a string
if (responsePayloadType.equals("java.lang.String", ignoreCase = true)
|| responsePayloadType.equals("string", ignoreCase = true)) {
return "Content string"
}
val responseName = removePath(responsePayloadType)
val responseType = toResponsePayloadType(responsePayloadType, expectedResponseCodes)
return "$responseName $responseType"
}
/**
* Determines if a response payload is a struct or a pointer to a struct. When there
* are multiple response codes, then the type should be a pointer to a struct.
*/
fun toResponsePayloadType(responsePayload: String, responseCodes: ImmutableList<Ds3ResponseCode>?): String {
if (isEmpty(responseCodes)) {
throw IllegalArgumentException("Expected at least one response code")
}
if (responseCodes!!.filter { code -> code.code < ERROR_THRESHOLD }.size == 1) {
return removePath(responsePayload)
}
return "*" + removePath(responsePayload)
}
/**
* Retreives the response payload type. There should be exactly one possible response payload
* per command, and if not, an exception is thrown.
*/
fun getResponsePayload(ds3ResponseCodes: ImmutableList<Ds3ResponseCode>?): String {
if (isEmpty(ds3ResponseCodes)) {
throw IllegalArgumentException("There must exist at least one non-error response code")
}
val codeWithPayload = ds3ResponseCodes!!.stream()
.filter{ code -> code.code < ERROR_THRESHOLD
&& hasContent(code.ds3ResponseTypes)
&& !code.ds3ResponseTypes!![0].type.equals("null", ignoreCase = true) }
.collect(GuavaCollectors.immutableList())
when(codeWithPayload.size) {
1 -> return codeWithPayload[0].ds3ResponseTypes!![0].type
else -> throw IllegalArgumentException("Expected 1 response type with payload, but found " + codeWithPayload.size)
}
}
}
| apache-2.0 | 3bcc8f69fee8f005a05765946bdff8b8 | 45.054795 | 130 | 0.670038 | 4.671607 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/Directives.kt | 1 | 958 | package graphql
import graphql.introspection.Introspection.DirectiveLocation.*
import graphql.schema.GraphQLNonNull
import graphql.schema.newDirective
import graphql.schema.newDirective
val IncludeDirective = newDirective {
name = "include"
description = "Directs the executor to include this field or fragment only when the `if` argument is true"
argument {
name = "if"
description = "Include when true."
type = GraphQLNonNull(GraphQLBoolean)
}
locations += FRAGMENT_SPREAD
locations += INLINE_FRAGMENT
locations += FIELD
}
val SkipDirective = newDirective {
name = "skip"
description = "Directs the executor to skip this field or fragment when the `if`'argument is true."
argument {
name = "if"
description = "Skipped when true."
type = GraphQLNonNull(GraphQLBoolean)
}
locations += FRAGMENT_SPREAD
locations += INLINE_FRAGMENT
locations += FIELD
}
| mit | 9937fef0b88602024083d486ee9ebfca | 28.9375 | 110 | 0.697286 | 4.561905 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/MinecraftSettings.kt | 1 | 3007 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.editor.markup.EffectType
@State(name = "MinecraftSettings", storages = [Storage("minecraft_dev.xml")])
class MinecraftSettings : PersistentStateComponent<MinecraftSettings.State> {
data class State(
var isShowProjectPlatformIcons: Boolean = true,
var isShowEventListenerGutterIcons: Boolean = true,
var isShowChatColorGutterIcons: Boolean = true,
var isShowChatColorUnderlines: Boolean = false,
var underlineType: UnderlineType = UnderlineType.DOTTED
)
private var state = State()
override fun getState(): State {
return state
}
override fun loadState(state: State) {
this.state = state
}
// State mappings
var isShowProjectPlatformIcons: Boolean
get() = state.isShowProjectPlatformIcons
set(showProjectPlatformIcons) {
state.isShowProjectPlatformIcons = showProjectPlatformIcons
}
var isShowEventListenerGutterIcons: Boolean
get() = state.isShowEventListenerGutterIcons
set(showEventListenerGutterIcons) {
state.isShowEventListenerGutterIcons = showEventListenerGutterIcons
}
var isShowChatColorGutterIcons: Boolean
get() = state.isShowChatColorGutterIcons
set(showChatColorGutterIcons) {
state.isShowChatColorGutterIcons = showChatColorGutterIcons
}
var isShowChatColorUnderlines: Boolean
get() = state.isShowChatColorUnderlines
set(showChatColorUnderlines) {
state.isShowChatColorUnderlines = showChatColorUnderlines
}
var underlineType: UnderlineType
get() = state.underlineType
set(underlineType) {
state.underlineType = underlineType
}
val underlineTypeIndex: Int
get() {
val type = underlineType
return UnderlineType.values().indices.firstOrNull { type == UnderlineType.values()[it] } ?: 0
}
enum class UnderlineType(private val regular: String, val effectType: EffectType) {
NORMAL("Normal", EffectType.LINE_UNDERSCORE),
BOLD("Bold", EffectType.BOLD_LINE_UNDERSCORE),
DOTTED("Dotted", EffectType.BOLD_DOTTED_LINE),
BOXED("Boxed", EffectType.BOXED),
ROUNDED_BOXED("Rounded Boxed", EffectType.ROUNDED_BOX),
WAVED("Waved", EffectType.WAVE_UNDERSCORE);
override fun toString(): String {
return regular
}
}
companion object {
val instance: MinecraftSettings
get() = ApplicationManager.getApplication().getService(MinecraftSettings::class.java)
}
}
| mit | e83e0073edb700e030cf6532c350aa96 | 30.652632 | 105 | 0.687729 | 5.350534 | false | false | false | false |
agrosner/KBinding | kbinding/src/main/java/com/andrewgrosner/kbinding/bindings/OneWayToSource.kt | 1 | 3460 | package com.andrewgrosner.kbinding.bindings
import android.view.View
import android.widget.CompoundButton
import android.widget.DatePicker
import android.widget.RatingBar
import android.widget.SeekBar
import android.widget.TextView
import android.widget.TimePicker
import com.andrewgrosner.kbinding.BindingRegister
import com.andrewgrosner.kbinding.ObservableField
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.Calendar
fun <Data> BindingRegister<Data>.bind(v: TextView) = bind(v, OnTextChangedRegister())
fun <Data> BindingRegister<Data>.bind(v: CompoundButton) = bind(v, OnCheckedChangeRegister())
fun <Data> BindingRegister<Data>.bind(v: DatePicker, initialValue: Calendar = Calendar.getInstance()) = bind(v, OnDateChangedRegister(initialValue))
fun <Data> BindingRegister<Data>.bind(v: TimePicker) = bind(v, OnTimeChangedRegister())
fun <Data> BindingRegister<Data>.bind(v: RatingBar) = bind(v, OnRatingBarChangedRegister())
fun <Data> BindingRegister<Data>.bind(v: SeekBar) = bind(v, OnSeekBarChangedRegister())
class ViewBinder<Data, V : View, Output>(val view: V,
val viewRegister: ViewRegister<V, Output>,
val component: BindingRegister<Data>)
fun <Data, V : View, Output, Input> ViewBinder<Data, V, Output>.onNullable(bindingExpression: BindingExpression<Output?, Input?>) = OneWayToSourceExpression(this, bindingExpression)
fun <Data, V : View, Output> ViewBinder<Data, V, Output>.onSelf() = onNullable { it }
class OneWayToSourceExpression<Data, Input, Output, V : View>
internal constructor(val viewBinder: ViewBinder<Data, V, Output>,
val bindingExpression: BindingExpression<Output?, Input?>) {
fun to(propertySetter: (Data?, Input?, V) -> Unit) = OneWayToSource(this, propertySetter)
}
inline fun <Data, Input, Output, V : View>
OneWayToSourceExpression<Data, Input, Output, V>.toObservable(
crossinline function: (Data) -> ObservableField<Input>) =
to { viewModel, input, _ ->
if (viewModel != null) {
val field = function(viewModel)
field.value = input ?: field.defaultValue
}
}
class OneWayToSource<Data, Input, Output, V : View>
internal constructor(
val expression: OneWayToSourceExpression<Data, Input, Output, V>,
val propertySetter: (Data?, Input?, V) -> Unit,
val bindingExpression: BindingExpression<Output?, Input?> = expression.bindingExpression,
val view: V = expression.viewBinder.view,
val viewRegister: ViewRegister<V, Output> = expression.viewBinder.viewRegister) : Binding {
private val component
get() = expression.viewBinder.component
init {
component.registerBinding(this)
}
override fun bind() {
viewRegister.register(view, { output ->
GlobalScope.launch {
async { propertySetter(component.viewModel, bindingExpression(output), view) }.await()
}
})
notifyValueChange()
}
override fun unbind() {
unbindInternal()
component.unregisterBinding(this)
}
internal fun unbindInternal() {
viewRegister.deregister(view)
}
override fun notifyValueChange() {
propertySetter(component.viewModel, bindingExpression(viewRegister.getValue(view)), view)
}
}
| mit | f49cb2088a7e0569b486dc43b92c9cb2 | 38.770115 | 181 | 0.692775 | 4.308842 | false | false | false | false |
alaminopu/IST-Syllabus | app/src/main/java/org/istbd/IST_Syllabus/bottombar/BottomNavItemLayout.kt | 1 | 2647 | package org.istbd.IST_Syllabus
import androidx.annotation.FloatRange
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.*
import com.google.android.material.math.MathUtils
@Composable
fun BottomNavItemLayout(
icon: @Composable BoxScope.() -> Unit,
text: @Composable BoxScope.() -> Unit,
@FloatRange(from = 0.0, to = 1.0) animationProgress: Float
) {
Layout(
content = {
IconBox(icon)
val scale = MathUtils.lerp(0.6f, 1f, animationProgress)
TextBox(animationProgress, scale, text)
}
) { measurables, constraints ->
val iconPlaceable = measurables.first { it.layoutId == "icon" }.measure(constraints)
val textPlaceable = measurables.first { it.layoutId == "text" }.measure(constraints)
placeTextAndIcon(
textPlaceable,
iconPlaceable,
constraints.maxWidth,
constraints.maxHeight,
animationProgress
)
}
}
@Composable
private fun TextBox(
animationProgress: Float,
scale: Float,
text: @Composable() (BoxScope.() -> Unit)
) {
Box(
modifier = Modifier
.layoutId("text")
.padding(horizontal = TextIconSpacing)
.graphicsLayer {
alpha = animationProgress
scaleX = scale
scaleY = scale
transformOrigin = BottomNavLabelTransformOrigin
},
content = text
)
}
@Composable
private fun IconBox(icon: @Composable() (BoxScope.() -> Unit)) {
Box(
modifier = Modifier
.layoutId("icon")
.padding(horizontal = TextIconSpacing),
content = icon
)
}
fun MeasureScope.placeTextAndIcon(
textPlaceable: Placeable,
iconPlaceable: Placeable,
width: Int,
height: Int,
@FloatRange(from = 0.0, to = 1.0) animationProgress: Float
): MeasureResult {
val iconY = (height - iconPlaceable.height) / 2
val textY = (height - textPlaceable.height) / 2
val textWidth = textPlaceable.width * animationProgress
val iconX = (width - textWidth - iconPlaceable.width) / 2
val textX = iconX + iconPlaceable.width
return layout(width, height) {
iconPlaceable.placeRelative(iconX.toInt(), iconY)
if (animationProgress != 0f) {
textPlaceable.placeRelative(textX.toInt(), textY)
}
}
}
| gpl-2.0 | 5cd30154a21a7dead4ecdd4ca621c2e6 | 28.741573 | 92 | 0.640348 | 4.38245 | false | false | false | false |
cashapp/sqldelight | sqldelight-gradle-plugin/src/test/integration/src/test/java/app/cash/sqldelight/integration/IntegrationTests.kt | 1 | 6456 | package app.cash.sqldelight.integration
import app.cash.sqldelight.ColumnAdapter
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver.Companion.IN_MEMORY
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.File
import java.util.Arrays
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.SECONDS
class IntegrationTests {
private lateinit var queryWrapper: QueryWrapper
private lateinit var personQueries: PersonQueries
private lateinit var keywordsQueries: SqliteKeywordsQueries
private lateinit var nullableTypesQueries: NullableTypesQueries
private lateinit var bigTableQueries: BigTableQueries
private lateinit var varargsQueries: VarargsQueries
private lateinit var groupedStatementQueries: GroupedStatementQueries
private object listAdapter : ColumnAdapter<List<String>, String> {
override fun decode(databaseValue: String): List<String> = databaseValue.split(",")
override fun encode(value: List<String>): String = value.joinToString(",")
}
@Before fun before() {
val database = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
QueryWrapper.Schema.create(database)
queryWrapper = QueryWrapper(database, NullableTypes.Adapter(listAdapter))
personQueries = queryWrapper.personQueries
keywordsQueries = queryWrapper.sqliteKeywordsQueries
nullableTypesQueries = queryWrapper.nullableTypesQueries
bigTableQueries = queryWrapper.bigTableQueries
varargsQueries = queryWrapper.varargsQueries
groupedStatementQueries = queryWrapper.groupedStatementQueries
}
@After fun after() {
File("test.db").delete()
}
@Test fun indexedArgs() {
// ?1 is the only arg
val person = personQueries.equivalentNames("Bob").executeAsOne()
assertThat(person).isEqualTo(Person(4, "Bob", "Bob"))
}
@Test fun startIndexAtTwo() {
// ?2 is the only arg
val person = personQueries.equivalentNames2("Bob").executeAsOne()
assertThat(person).isEqualTo(Person(4, "Bob", "Bob"))
}
@Test fun namedIndexArgs() {
// :name is the only arg
val person = personQueries.equivalentNamesNamed("Bob").executeAsOne()
assertThat(person).isEqualTo(Person(4, "Bob", "Bob"))
}
@Test fun indexedArgLast() {
// First arg declared is ?, second arg declared is ?1.
val person = personQueries.indexedArgLast("Bob").executeAsOne()
assertThat(person).isEqualTo(Person(4, "Bob", "Bob"))
}
@Test fun indexedArgLastTwo() {
// First arg declared is ?, second arg declared is ?2.
val person = personQueries.indexedArgLast2("Alec", "Strong").executeAsOne()
assertThat(person).isEqualTo(Person(1, "Alec", "Strong"))
}
@Test fun nameIn() {
val people = personQueries.nameIn(Arrays.asList("Alec", "Matt", "Jake")).executeAsList()
assertThat(people).hasSize(3)
}
@Test fun sqliteKeywordQuery() {
val keywords = keywordsQueries.selectAll().executeAsOne()
assertThat(keywords).isEqualTo(Group(1, 10, 20))
}
@Test fun compiledStatement() {
keywordsQueries.insertStmt(11, 21)
keywordsQueries.insertStmt(12, 22)
var current: Long = 10
for (group in keywordsQueries.selectAll().executeAsList()) {
assertThat(group.where_).isEqualTo(current++)
}
assertThat(current).isEqualTo(13)
}
@Test
@Throws(InterruptedException::class)
fun compiledStatementAcrossThread() {
keywordsQueries.insertStmt(11, 21)
val latch = CountDownLatch(1)
Thread(
object : Runnable {
override fun run() {
try {
keywordsQueries.insertStmt(12, 22)
} finally {
latch.countDown()
}
}
},
).start()
assertTrue(latch.await(10, SECONDS))
var current: Long = 10
for (group in keywordsQueries.selectAll().executeAsList()) {
assertThat(group.where_).isEqualTo(current++)
}
assertThat(current).isEqualTo(13)
}
@Test
fun nullableColumnsUseAdapterProperly() {
val cool = NullableTypes(listOf("Alec", "Matt", "Jake"), "Cool")
val notCool = NullableTypes(null, "Not Cool")
val nulled = NullableTypes(null, null)
nullableTypesQueries.insertNullableType(cool)
nullableTypesQueries.insertNullableType(notCool)
nullableTypesQueries.insertNullableType(nulled)
assertThat(nullableTypesQueries.selectAll().executeAsList())
.containsExactly(cool, notCool, nulled)
}
@Test fun multipleNameIn() {
val people = personQueries.multipleNameIn(listOf("Alec", "Jesse"), listOf("Wharton", "Precious")).executeAsList()
assertThat(people).hasSize(3)
}
@Test fun bigTable() {
val bigTable = BigTable(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
)
bigTableQueries.insert(bigTable)
assertThat(bigTableQueries.select().executeAsOne()).isEqualTo(bigTable)
}
@Test fun varargs() {
varargsQueries.insert(MyTable(1, 1, 10))
varargsQueries.insert(MyTable(2, 2, 10))
varargsQueries.insert(MyTable(3, 3, 10))
assertThat(varargsQueries.select(setOf(1, 2), 10).executeAsList()).containsExactly(
MyTable(1, 1, 10),
MyTable(2, 2, 10),
)
}
@Test fun groupedStatement() {
groupedStatementQueries.upsert(col0 = "1", col1 = "1", col2 = 1, col3 = 10)
groupedStatementQueries.upsert(col0 = "2", col1 = "2", col2 = 1, col3 = 20)
groupedStatementQueries.upsert(col0 = "1", col1 = "1", col2 = 0, col3 = 11)
assertThat(groupedStatementQueries.selectAll().executeAsList()).containsExactly(
Bug("2", "2", 1, 20),
Bug("1", "1", 0, 11),
)
}
@Test fun groupedStatementWithReturn() {
assertThat(
personQueries.insertAndReturn(first_name = "Bob", last_name = "Ross").executeAsOne(),
).isEqualTo(
InsertAndReturn(
first_name = "Bob",
last_name = "Ross",
),
)
}
@Test fun views() {
queryWrapper.viewQueries.insert(TableForView(42, 42L))
assertThat(
queryWrapper.viewQueries.get().executeAsOne(),
).isEqualTo(
TableForView(
id = 42,
foo = 42L,
),
)
assertThat(
queryWrapper.viewQueries.getView2().executeAsOne(),
).isEqualTo(
TableForView(
id = 42,
foo = 42L,
),
)
}
}
| apache-2.0 | 1b80dca2f58fe3dccf11b4350872676c | 30.188406 | 117 | 0.686029 | 3.997523 | false | true | false | false |
jitsi/jicofo | jicofo-common/src/main/kotlin/org/jitsi/jicofo/conference/source/EndpointSourceSet.kt | 1 | 11424 | /*
* Copyright @ 2021 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.conference.source
import org.jitsi.utils.MediaType
import org.jitsi.utils.MediaType.AUDIO
import org.jitsi.utils.MediaType.VIDEO
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.xmpp.extensions.colibri.SourcePacketExtension
import org.jitsi.xmpp.extensions.jingle.ContentPacketExtension
import org.jitsi.xmpp.extensions.jingle.RtpDescriptionPacketExtension
import org.jitsi.xmpp.extensions.jingle.SourceGroupPacketExtension
import org.json.simple.JSONArray
import java.lang.IllegalArgumentException
import kotlin.jvm.Throws
/** A set of [Source]s and [SsrcGroup]s, usually associated with an endpoint. */
data class EndpointSourceSet(
val sources: Set<Source> = emptySet(),
val ssrcGroups: Set<SsrcGroup> = emptySet(),
) {
constructor(source: Source) : this(setOf(source))
constructor(ssrcGroup: SsrcGroup) : this(ssrcGroups = setOf(ssrcGroup))
/**
* Whether this set of sources is empty.
* Note: it is not clear whether it makes sense to describe any [SsrcGroup]s without corresponding sources, but
* for this representation we allow it.
*/
fun isEmpty() = sources.isEmpty() && ssrcGroups.isEmpty()
/**
* Whether there are any audio sources in this set.
*/
val hasAudio: Boolean by lazy { sources.any { it.mediaType == AUDIO } }
/**
* Whether there are any video sources in this set.
*/
val hasVideo: Boolean by lazy { sources.any { it.mediaType == VIDEO } }
/**
* Creates a list of Jingle [ContentPacketExtension]s that describe the sources in this [EndpointSourceSet].
*/
fun toJingle(owner: String? = null): List<ContentPacketExtension> = toJingle(mutableMapOf(), owner)
val audioSsrcs: Set<Long> by lazy { getSsrcs(AUDIO) }
val videoSsrcs: Set<Long> by lazy { getSsrcs(VIDEO) }
private fun getSsrcs(mediaType: MediaType) = sources.filter { it.mediaType == mediaType }.map { it.ssrc }.toSet()
/**
* A concise string more suitable for logging. This may be slow for large sets.
*/
override fun toString() = "[audio=$audioSsrcs, video=$videoSsrcs, groups=$ssrcGroups]"
/**
* Get a new [EndpointSourceSet] by stripping all simulcast-related SSRCs and groups except for the first SSRC in
* a simulcast group. This assumes that the first SSRC in the simulcast group and its associated RTX SSRC are the only
* SSRCs that receivers of simulcast streams need to know about, i.e. that jitsi-videobridge uses that SSRC as the
* target SSRC when rewriting streams.
*/
val stripSimulcast: EndpointSourceSet by lazy {
doStripSimulcast()
}
/**
* A compact JSON representation of this [EndpointSourceSet] (optimized for size). This is done ad-hoc instead of
* using e.g. jackson because the format is substantially different than the natural representation of
* [EndpointSourceSet], we only need serialization support (no parsing) and to keep it separated from the main code.
*
* The JSON is an array of up to four elements, with index 0 encoding the video sources, index 1 encoding the video
* source groups, index 2 encoding the audio sources, and index 3 encoding the audio source groups. Trailing empty
* elements may be skipped, e.g. if there are no audio source groups the list will only have 3 elements.
*
* Each element is itself a JSON array of the `compactJson` representation of the sources or SSRC groups.
*
* For example, an [EndpointSourceSet] with video sources 1, 2 grouped in a Fid group and an audio source 3 may be
* encoded as:
* [
* // Array of video sources
* [
* {"s": 1},
* {"s": 2}
* ],
* // Array of video SSRC groups
* [
* ["f", 1, 2]
* ],
* // Array of audio sources
* [
* {"s": 3}
* ]
* // Empty array of audio SSRC groups not present.
* ]
*/
val compactJson: String by lazy {
buildString {
append("[[")
sources.filter { it.mediaType == VIDEO }.forEachIndexed { i, source ->
if (i > 0) append(",")
append(source.compactJson)
}
append("],[")
ssrcGroups.filter { it.mediaType == VIDEO }.forEachIndexed { i, ssrcGroup ->
if (i > 0) append(",")
append(ssrcGroup.compactJson)
}
append("],[")
sources.filter { it.mediaType == AUDIO }.forEachIndexed { i, source ->
if (i > 0) append(",")
append(source.compactJson)
}
append("]")
if (ssrcGroups.any { it.mediaType == AUDIO }) {
append(",[")
ssrcGroups.filter { it.mediaType == AUDIO }.forEachIndexed { i, ssrcGroup ->
if (i > 0) append(",")
append(ssrcGroup.compactJson)
}
append("]")
}
append("]")
}
}
/** Expanded JSON format used for debugging. */
fun toJson() = OrderedJsonObject().apply {
put(
"sources",
JSONArray().apply {
sources.forEach { add(it.toJson()) }
}
)
put(
"groups",
JSONArray().apply {
ssrcGroups.forEach { add(it.toJson()) }
}
)
}
companion object {
/** An [EndpointSourceSet] instance with no sources or source groups */
@JvmField
val EMPTY = EndpointSourceSet()
/**
* Parses a list of Jingle [ContentPacketExtension]s into an [EndpointSourceSet].
*
* @throws IllegalArgumentException if the media type of any of the contents is invalid, or the semantics of
* any of the SSRC groups is invalid.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun fromJingle(
contents: List<ContentPacketExtension>
): EndpointSourceSet {
val sources = mutableSetOf<Source>()
val ssrcGroups = mutableSetOf<SsrcGroup>()
contents.forEach { content ->
val rtpDesc: RtpDescriptionPacketExtension? =
content.getFirstChildOfType(RtpDescriptionPacketExtension::class.java)
val mediaTypeString = if (rtpDesc != null) rtpDesc.media else content.name
val mediaType = MediaType.parseString(mediaTypeString)
// The previous code looked for [SourcePacketExtension] as children of both the "content" and
// "description" elements, so this is reproduced here. I don't know which one is correct and/or used.
rtpDesc?.let {
rtpDesc.getChildExtensionsOfType(SourcePacketExtension::class.java).forEach { spe ->
sources.add(Source(mediaType, spe))
}
rtpDesc.getChildExtensionsOfType(SourceGroupPacketExtension::class.java).forEach { sgpe ->
ssrcGroups.add(SsrcGroup.fromPacketExtension(sgpe, mediaType))
}
}
content.getChildExtensionsOfType(SourcePacketExtension::class.java).forEach { spe ->
sources.add(Source(mediaType, spe))
}
}
return EndpointSourceSet(sources, ssrcGroups)
}
}
}
/**
* Populates a list of Jingle [ContentPacketExtension]s with extensions that describe the sources in this
* [EndpointSourceSet]. Creates new [ContentPacketExtension] if necessary, returns the [ContentPacketExtension]s
* as a list.
*/
fun EndpointSourceSet.toJingle(
contentMap: MutableMap<MediaType, ContentPacketExtension>,
owner: String?
): List<ContentPacketExtension> {
sources.forEach { source ->
val content = contentMap.computeIfAbsent(source.mediaType) {
ContentPacketExtension().apply { name = source.mediaType.toString() }
}
val rtpDesc = content.getOrCreateRtpDescription()
rtpDesc.addChildExtension(source.toPacketExtension(owner))
}
ssrcGroups.forEach { ssrcGroup ->
val content = contentMap.computeIfAbsent(ssrcGroup.mediaType) {
ContentPacketExtension().apply { name = ssrcGroup.mediaType.toString() }
}
val rtpDesc = content.getOrCreateRtpDescription()
rtpDesc.addChildExtension(ssrcGroup.toPacketExtension())
}
return contentMap.values.toList()
}
/**
* Returns the [RtpDescriptionPacketExtension] child of this [ContentPacketExtension], creating it if it doesn't
* exist.
*/
private fun ContentPacketExtension.getOrCreateRtpDescription() =
getChildExtension(RtpDescriptionPacketExtension::class.java) ?: RtpDescriptionPacketExtension().apply {
media = name
[email protected](this)
}
operator fun EndpointSourceSet?.plus(other: EndpointSourceSet?): EndpointSourceSet =
when {
this == null && other == null -> EndpointSourceSet.EMPTY
this == null -> other!!
other == null -> this
else -> EndpointSourceSet(
sources + other.sources,
ssrcGroups + other.ssrcGroups
)
}
operator fun EndpointSourceSet.minus(other: EndpointSourceSet): EndpointSourceSet =
EndpointSourceSet(sources - other.sources, ssrcGroups - other.ssrcGroups)
operator fun EndpointSourceSet.plus(sources: Set<Source>) =
EndpointSourceSet(this.sources + sources, this.ssrcGroups)
operator fun EndpointSourceSet.plus(source: Source) =
EndpointSourceSet(this.sources + source, this.ssrcGroups)
operator fun EndpointSourceSet.plus(ssrcGroup: SsrcGroup) =
EndpointSourceSet(this.sources, this.ssrcGroups + ssrcGroup)
private fun EndpointSourceSet.doStripSimulcast(): EndpointSourceSet {
val groupsToRemove = mutableSetOf<SsrcGroup>()
val ssrcsToRemove = mutableSetOf<Long>()
ssrcGroups.filter { it.semantics == SsrcGroupSemantics.Sim }.forEach { simGroup ->
groupsToRemove.add(simGroup)
simGroup.ssrcs.forEachIndexed { index: Int, ssrc: Long ->
if (index > 0) ssrcsToRemove.add(ssrc)
}
}
ssrcGroups.filter { it.semantics == SsrcGroupSemantics.Fid }.forEach { fidGroup ->
if (fidGroup.ssrcs.size != 2) {
throw IllegalArgumentException("Invalid FID group, has ${fidGroup.ssrcs.size} ssrcs.")
}
if (ssrcsToRemove.contains(fidGroup.ssrcs[0])) {
ssrcsToRemove.add(fidGroup.ssrcs[1])
groupsToRemove.add(fidGroup)
}
}
return EndpointSourceSet(
sources.filter { !ssrcsToRemove.contains(it.ssrc) }.toSet(),
ssrcGroups - groupsToRemove
)
}
| apache-2.0 | 4dc13e988ffeac6a2593cd068b29e421 | 38.804878 | 122 | 0.641106 | 4.573259 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-github/retroapollo-android/src/main/java/com/bennyhuo/retroapollo/RetroApollo.kt | 2 | 2611 | package com.bennyhuo.retroapollo
import com.apollographql.apollo.ApolloClient
import com.bennyhuo.retroapollo.CallAdapter.Factory
import com.bennyhuo.retroapollo.utils.Utils
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.lang.reflect.Type
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass
class RetroApollo private constructor(val apolloClient: ApolloClient, val callAdapterFactories: List<Factory>){
class Builder {
private var apolloClient: ApolloClient? = null
fun apolloClient(apolloClient: ApolloClient): Builder {
this.apolloClient = apolloClient
return this
}
private val callAdapterFactories = arrayListOf<Factory>(ApolloCallAdapterFactory())
fun addCallAdapterFactory(callAdapterFactory: Factory): Builder {
callAdapterFactories.add(callAdapterFactory)
return this
}
fun build() = apolloClient?.let {
RetroApollo(it, callAdapterFactories)
}?: throw IllegalStateException("ApolloClient cannot be null.")
}
private val serviceMethodCache = ConcurrentHashMap<Method, ApolloServiceMethod<*>>()
fun <T: Any> createGraphQLService(serviceClass: KClass<T>): T {
Utils.validateServiceInterface(serviceClass.java)
return Proxy.newProxyInstance(serviceClass.java.classLoader, arrayOf(serviceClass.java),
object: InvocationHandler{
override fun invoke(proxy: Any, method: Method, args: Array<Any>?): Any {
if(method.declaringClass == Any::class.java){
return method.invoke(this, args)
}
return loadServiceMethod(method)(args)
}
}) as T
}
fun loadServiceMethod(method: Method): ApolloServiceMethod<*>{
var serviceMethod = serviceMethodCache[method]
if(serviceMethod == null){
synchronized(serviceMethodCache){
serviceMethod = serviceMethodCache[method] ?: ApolloServiceMethod.Builder(this, method).build().also {
serviceMethodCache[method] = it
}
}
}
return serviceMethod!!
}
fun getCallAdapter(type: Type): CallAdapter<Any, Any>? {
for(callAdapterFactory in callAdapterFactories){
val callAdapter = callAdapterFactory.get(type)
return callAdapter as? CallAdapter<Any, Any> ?: continue
}
return null
}
} | apache-2.0 | 244deae700829f9972c7ca09b1ead284 | 36.314286 | 118 | 0.652624 | 5.211577 | false | false | false | false |
panpf/sketch | sketch-gif-koral/src/main/java/com/github/panpf/sketch/decode/GifDrawableDrawableDecoder.kt | 1 | 6461 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.decode
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import androidx.annotation.WorkerThread
import androidx.exifinterface.media.ExifInterface
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.datasource.DataSource
import com.github.panpf.sketch.decode.internal.ImageFormat
import com.github.panpf.sketch.decode.internal.calculateSampleSize
import com.github.panpf.sketch.decode.internal.createInSampledTransformed
import com.github.panpf.sketch.decode.internal.isGif
import com.github.panpf.sketch.drawable.GifDrawableWrapperDrawable
import com.github.panpf.sketch.drawable.SketchAnimatableDrawable
import com.github.panpf.sketch.fetch.FetchResult
import com.github.panpf.sketch.request.ANIMATION_REPEAT_INFINITE
import com.github.panpf.sketch.request.animatable2CompatCallbackOf
import com.github.panpf.sketch.request.animatedTransformation
import com.github.panpf.sketch.request.animationEndCallback
import com.github.panpf.sketch.request.animationStartCallback
import com.github.panpf.sketch.request.internal.RequestContext
import com.github.panpf.sketch.request.repeatCount
import com.github.panpf.sketch.util.Size
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import pl.droidsonroids.gif.GifInfoHandleHelper
import pl.droidsonroids.gif.GifOptions
import pl.droidsonroids.gif.transforms.Transform
/**
* Only the following attributes are supported:
*
* resize.size
*
* resize.precision: It is always LESS_PIXELS
*
* repeatCount
*
* animatedTransformation
*
* onAnimationStart
*
* onAnimationEnd
*/
class GifDrawableDrawableDecoder(
private val requestContext: RequestContext,
private val dataSource: DataSource,
) : DrawableDecoder {
@WorkerThread
override suspend fun decode(): DrawableDecodeResult {
val request = requestContext.request
val gifInfoHandleHelper = GifInfoHandleHelper(dataSource)
val imageWidth = gifInfoHandleHelper.width
val imageHeight = gifInfoHandleHelper.height
val resizeSize = requestContext.resizeSize
val inSampleSize = calculateSampleSize(
Size(imageWidth, imageHeight),
Size(resizeSize.width, resizeSize.height)
)
gifInfoHandleHelper.setOptions(GifOptions().apply {
setInSampleSize(inSampleSize)
})
val gifDrawable = gifInfoHandleHelper.createGifDrawable().apply {
loopCount =
(request.repeatCount ?: ANIMATION_REPEAT_INFINITE).takeIf { it != -1 } ?: 0
// Set the animated transformation to be applied on each frame.
val transformation = request.animatedTransformation
if (transformation != null) {
transform = object : Transform {
override fun onBoundsChange(bounds: Rect?) {
}
override fun onDraw(canvas: Canvas, paint: Paint?, buffer: Bitmap?) {
transformation.transform(canvas)
}
}
}
}
val transformedList =
if (inSampleSize != 1) listOf(createInSampledTransformed(inSampleSize)) else null
val imageInfo = ImageInfo(
imageWidth,
imageHeight,
ImageFormat.GIF.mimeType,
ExifInterface.ORIENTATION_UNDEFINED
)
val animatableDrawable = SketchAnimatableDrawable(
animatableDrawable = GifDrawableWrapperDrawable(gifDrawable),
imageUri = request.uriString,
requestKey = requestContext.key,
requestCacheKey = requestContext.cacheKey,
imageInfo = imageInfo,
dataFrom = dataSource.dataFrom,
transformedList = transformedList,
extras = null,
).apply {
// Set the start and end animation callbacks if any one is supplied through the request.
val onStart = request.animationStartCallback
val onEnd = request.animationEndCallback
if (onStart != null || onEnd != null) {
withContext(Dispatchers.Main) {
registerAnimationCallback(animatable2CompatCallbackOf(onStart, onEnd))
}
}
}
return DrawableDecodeResult(
drawable = animatableDrawable,
imageInfo = animatableDrawable.imageInfo,
dataFrom = animatableDrawable.dataFrom,
transformedList = animatableDrawable.transformedList,
extras = animatableDrawable.extras,
)
}
class Factory : DrawableDecoder.Factory {
override fun create(
sketch: Sketch,
requestContext: RequestContext,
fetchResult: FetchResult
): GifDrawableDrawableDecoder? {
if (!requestContext.request.disallowAnimatedImage) {
val imageFormat = ImageFormat.parseMimeType(fetchResult.mimeType)
// Some sites disguise the suffix of a GIF file as a JPEG, which must be identified by the file header
val isGif =
if (imageFormat == null) fetchResult.headerBytes.isGif() else imageFormat == ImageFormat.GIF
if (isGif) {
return GifDrawableDrawableDecoder(requestContext, fetchResult.dataSource)
}
}
return null
}
override fun toString(): String = "GifDrawableDrawableDecoder"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return true
}
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
} | apache-2.0 | 58a737e542ca554dc0c6375bc12e866d | 37.694611 | 118 | 0.67683 | 5.131851 | false | false | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/PaymentSessionActivity.kt | 1 | 12696 | package com.stripe.example.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.stripe.android.CustomerSession
import com.stripe.android.PaymentSession
import com.stripe.android.PaymentSessionConfig
import com.stripe.android.PaymentSessionData
import com.stripe.android.core.StripeError
import com.stripe.android.model.Address
import com.stripe.android.model.Customer
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.ShippingInformation
import com.stripe.android.model.ShippingMethod
import com.stripe.android.view.BillingAddressFields
import com.stripe.android.view.PaymentUtils
import com.stripe.example.R
import com.stripe.example.databinding.PaymentSessionActivityBinding
import java.util.Currency
import java.util.Locale
/**
* An example activity that handles working with a [PaymentSession], allowing you to collect
* information needed to request payment for the current customer.
*/
class PaymentSessionActivity : AppCompatActivity() {
private val viewBinding: PaymentSessionActivityBinding by lazy {
PaymentSessionActivityBinding.inflate(layoutInflater)
}
private val viewModel: ActivityViewModel by viewModels()
private val customerSession: CustomerSession by lazy {
CustomerSession.getInstance()
}
private lateinit var paymentSession: PaymentSession
private val notSelectedText: String by lazy {
getString(R.string.not_selected)
}
private val snackbarController: SnackbarController by lazy {
SnackbarController(viewBinding.coordinator)
}
private var paymentSessionData: PaymentSessionData? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
paymentSession = createPaymentSession(savedInstanceState == null)
viewBinding.selectPaymentMethodButton.setOnClickListener {
paymentSession.presentPaymentMethodSelection()
}
viewBinding.startPaymentFlowButton.setOnClickListener {
paymentSession.presentShippingFlow()
}
viewModel.paymentSessionDataResult.observe(
this,
{ result ->
result.fold(
onSuccess = {
onPaymentSessionDataChanged(it)
},
onFailure = {
snackbarController.show(it.message.orEmpty())
}
)
}
)
viewModel.customerResult.observe(
this,
{ result ->
result.fold(
onSuccess = {
onCustomerRetrieved()
},
onFailure = {
hideProgressBar()
}
)
}
)
viewModel.isProcessing.observe(
this,
{ isCommunicating ->
when (isCommunicating) {
true -> disableUi()
false -> enableUi()
}
}
)
}
private fun createPaymentSession(
shouldPrefetchCustomer: Boolean = false
): PaymentSession {
if (shouldPrefetchCustomer) {
disableUi()
} else {
enableUi()
}
return PaymentSession(
activity = this,
config = PaymentSessionConfig.Builder()
.setPaymentMethodsFooter(R.layout.add_payment_method_footer)
.setAddPaymentMethodFooter(R.layout.add_payment_method_footer)
.setPrepopulatedShippingInfo(EXAMPLE_SHIPPING_INFO)
.setHiddenShippingInfoFields()
// Optionally specify the `PaymentMethod.Type` values to use.
// Defaults to `PaymentMethod.Type.Card`
.setPaymentMethodTypes(listOf(PaymentMethod.Type.Card))
.setShouldShowGooglePay(true)
.setAllowedShippingCountryCodes(setOf("US", "CA"))
.setShippingInformationValidator(ShippingInformationValidator())
.setShippingMethodsFactory(ShippingMethodsFactory())
.setWindowFlags(WindowManager.LayoutParams.FLAG_SECURE)
.setBillingAddressFields(BillingAddressFields.PostalCode)
.setShouldPrefetchCustomer(shouldPrefetchCustomer)
.setCanDeletePaymentMethods(true)
.build()
).also {
it.init(listener = viewModel.paymentSessionListener)
it.setCartTotal(2000L)
}
}
private fun createPaymentMethodDescription(data: PaymentSessionData): String {
val paymentMethod = data.paymentMethod
return when {
paymentMethod != null -> {
paymentMethod.card?.let { card ->
"${card.brand} ending in ${card.last4}"
} ?: paymentMethod.type?.code.orEmpty()
}
data.useGooglePay -> {
"Use Google Pay"
}
else -> {
notSelectedText
}
}
}
private fun createShippingInfoDescription(shippingInformation: ShippingInformation?): String {
return if (shippingInformation != null) {
listOfNotNull(
shippingInformation.name,
shippingInformation.address?.line1,
shippingInformation.address?.line2,
shippingInformation.address?.city,
shippingInformation.address?.state,
shippingInformation.address?.country,
shippingInformation.address?.postalCode,
shippingInformation.phone
).joinToString("\n")
} else {
notSelectedText
}
}
private fun createShippingMethodDescription(shippingMethod: ShippingMethod?): String {
return if (shippingMethod != null) {
listOfNotNull(
shippingMethod.label,
shippingMethod.detail,
PaymentUtils.formatPriceStringUsingFree(
shippingMethod.amount,
Currency.getInstance("USD"),
"Free"
)
).joinToString("\n")
} else {
notSelectedText
}
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
paymentSession.handlePaymentData(requestCode, resultCode, data ?: Intent())
}
private fun onPaymentSessionDataChanged(
data: PaymentSessionData
) {
paymentSessionData = data
disableUi()
customerSession.retrieveCurrentCustomer(viewModel.customerSessionListener)
}
private fun enableUi() {
hideProgressBar()
viewBinding.selectPaymentMethodButton.isEnabled = true
viewBinding.startPaymentFlowButton.isEnabled = true
}
private fun disableUi() {
viewBinding.progressBar.visibility = View.VISIBLE
viewBinding.selectPaymentMethodButton.isEnabled = false
viewBinding.startPaymentFlowButton.isEnabled = false
}
private fun onCustomerRetrieved() {
enableUi()
paymentSessionData?.let { paymentSessionData ->
viewBinding.readyToCharge.setCompoundDrawablesRelativeWithIntrinsicBounds(
VectorDrawableCompat.create(
resources,
when (paymentSessionData.isPaymentReadyToCharge) {
true -> R.drawable.ic_check
false -> R.drawable.ic_cancel
},
null
),
null,
null,
null
)
viewBinding.paymentMethod.text =
createPaymentMethodDescription(paymentSessionData)
viewBinding.shippingInfo.text =
createShippingInfoDescription(paymentSessionData.shippingInformation)
viewBinding.shippingMethod.text =
createShippingMethodDescription(paymentSessionData.shippingMethod)
}
}
private class ShippingInformationValidator : PaymentSessionConfig.ShippingInformationValidator {
override fun isValid(shippingInformation: ShippingInformation): Boolean {
return setOf(Locale.US.country, Locale.CANADA.country)
.contains(shippingInformation.address?.country.orEmpty())
}
override fun getErrorMessage(shippingInformation: ShippingInformation): String {
return "The country must be US or Canada."
}
}
private class ShippingMethodsFactory : PaymentSessionConfig.ShippingMethodsFactory {
override fun create(
shippingInformation: ShippingInformation
): List<ShippingMethod> {
return when (shippingInformation.address?.country) {
"CA" -> SHIPPING_METHODS_CA
else -> SHIPPING_METHODS_US
}
}
}
private fun hideProgressBar() {
viewBinding.progressBar.visibility = View.INVISIBLE
}
internal class ActivityViewModel : ViewModel() {
val isProcessing = MutableLiveData<Boolean>()
val paymentSessionDataResult = MutableLiveData<Result<PaymentSessionData>>()
val customerResult = MutableLiveData<Result<Customer>>()
val customerSessionListener: CustomerSession.CustomerRetrievalListener by lazy {
object : CustomerSession.CustomerRetrievalListener {
init {
BackgroundTaskTracker.onStart()
}
override fun onCustomerRetrieved(customer: Customer) {
BackgroundTaskTracker.onStop()
customerResult.value = Result.success(customer)
}
override fun onError(
errorCode: Int,
errorMessage: String,
stripeError: StripeError?
) {
BackgroundTaskTracker.onStop()
customerResult.value = Result.failure(RuntimeException())
}
}
}
val paymentSessionListener: PaymentSession.PaymentSessionListener by lazy {
object : PaymentSession.PaymentSessionListener {
override fun onCommunicatingStateChanged(isCommunicating: Boolean) {
if (isCommunicating) {
BackgroundTaskTracker.onStart()
}
isProcessing.value = isCommunicating
}
override fun onError(errorCode: Int, errorMessage: String) {
BackgroundTaskTracker.onStop()
paymentSessionDataResult.value = Result.failure(RuntimeException(errorMessage))
}
override fun onPaymentSessionDataChanged(data: PaymentSessionData) {
BackgroundTaskTracker.onStop()
paymentSessionDataResult.value = Result.success(data)
}
}
}
}
private companion object {
private val EXAMPLE_SHIPPING_INFO = ShippingInformation(
Address.Builder()
.setCity("San Francisco")
.setCountry("US")
.setLine1("123 Market St")
.setLine2("#345")
.setPostalCode("94107")
.setState("CA")
.build(),
"Jenny Rosen",
"(555) 555-5555"
)
private val SHIPPING_METHODS_CA = listOf(
ShippingMethod(
"Canada Post",
"canada-post",
599,
"CAD",
"Arrives in 3-5 days"
)
)
private val SHIPPING_METHODS_US = listOf(
ShippingMethod(
"UPS Ground",
"ups-ground",
599,
"USD",
"Arrives in 3-5 days"
),
ShippingMethod(
"FedEx Overnight",
"fedex",
1499,
"USD",
"Arrives tomorrow"
)
)
}
}
| mit | 60c9a6eeae9e3de6f59ee207c431ed33 | 34.071823 | 100 | 0.589792 | 5.971778 | false | false | false | false |
micabytes/lib_game | src/main/java/com/micabytes/gfx/BitmapSurfaceRenderer.kt | 2 | 16709 | /*
* Copyright 2013 MicaByte Systems
*
* 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.micabytes.gfx
import android.graphics.*
import timber.log.Timber
import java.io.FilterInputStream
import java.io.IOException
import java.io.InputStream
/**
* GameSurfaceRendererBitmap is a renderer that handles the rendering of a background bitmap to the
* screen (e.g., a game map). It is able to do this even if the bitmap is too large to fit into
* memory. The game should subclass the renderer and extend the drawing methods to add other game
* elements.
*/
open class BitmapSurfaceRenderer : SurfaceRenderer {
private val TAG = BitmapSurfaceRenderer::class.java.name
private val CACHE_THREAD = "cacheThread"
private val DEFAULT_CONFIG: Bitmap.Config = Bitmap.Config.RGB_565
private val DEFAULT_SAMPLE_SIZE = 2
private val DEFAULT_MEM_USAGE = 20
private val DEFAULT_THRESHOLD = 0.75f
// BitmapRegionDecoder - this is the class that does the magic
private var decoder: BitmapRegionDecoder? = null
// The cached portion of the background image
private val cachedBitmap = CacheBitmap()
// The low resolution version of the background image
private var lowResBitmap: Bitmap? = null
/**
* Options for loading the bitmaps
*/
private val options = BitmapFactory.Options()
/**
* What is the down sample size for the sample image? 1=1/2, 2=1/4 3=1/8, etc
*/
private val sampleSize: Int
/**
* What percent of total memory should we use for the cache? The bigger the cache, the longer it
* takes to read -- 1.2 secs for 25%, 600ms for 10%, 500ms for 5%. User experience seems to be
* best for smaller values.
*/
@get:Synchronized
@set:Synchronized
private var memUsage: Int = 0
/**
* Threshold for using low resolution image
*/
private val lowResThreshold: Float
/**
* Calculated rect
*/
private val calculatedCacheWindowRect = Rect()
private constructor() : super() {
options.inPreferredConfig = DEFAULT_CONFIG
sampleSize = DEFAULT_SAMPLE_SIZE
memUsage = DEFAULT_MEM_USAGE
lowResThreshold = DEFAULT_THRESHOLD
}
protected constructor(config: Bitmap.Config, sample: Int, memUse: Int, threshold: Float) : super() {
options.inPreferredConfig = config
sampleSize = sample
memUsage = memUse
lowResThreshold = threshold
}
internal class FlushedInputStream(inputStream: InputStream) : FilterInputStream(inputStream) {
@Throws(IOException::class)
override fun skip(byteCount: Long): Long {
var totalBytesSkipped = 0L
while (totalBytesSkipped < byteCount) {
var bytesSkipped = `in`.skip(byteCount - totalBytesSkipped)
if (bytesSkipped == 0L) {
val bytes = read()
if (bytes < 0) {
break // we reached EOF
} else {
bytesSkipped = 1 // we read one byte
}
}
totalBytesSkipped += bytesSkipped
}
return totalBytesSkipped
}
}
/**
* Set the Background bitmap
*
* @param inputStream InputStream to the raw data of the bitmap
*/
@Throws(IOException::class)
fun setBitmap(inputStream: InputStream) {
val fixedInput = FlushedInputStream(inputStream)
val opt = BitmapFactory.Options()
decoder = BitmapRegionDecoder.newInstance(fixedInput, false)
fixedInput.reset()
// Grab the bounds of the background bitmap
opt.inPreferredConfig = DEFAULT_CONFIG
opt.inJustDecodeBounds = true
Timber.d(TAG, "Decode inputStream for Background Bitmap")
BitmapFactory.decodeStream(fixedInput, null, opt)
fixedInput.reset()
backgroundSize.set(opt.outWidth, opt.outHeight)
Timber.d(TAG, "Background Image: w=" + opt.outWidth + " h=" + opt.outHeight)
// Create the low resolution background
opt.inJustDecodeBounds = false
opt.inSampleSize = 1 shl sampleSize
lowResBitmap = BitmapFactory.decodeStream(fixedInput, null, opt)
Timber.d(TAG, "Low Res Image: w=" + lowResBitmap!!.width + " h=" + lowResBitmap!!.height)
// Initialize cache
if (cachedBitmap.state == CacheState.NOT_INITIALIZED) {
synchronized(cachedBitmap) {
cachedBitmap.state = CacheState.IS_INITIALIZED
}
}
}
override fun drawBase() {
cachedBitmap.draw(viewPort)
}
override fun drawLayer() {
// NOOP - override function and add game specific code
}
override fun drawFinal() {
// NOOP - override function and add game specific code
}
/**
* Starts the renderer
*/
override fun start() {
cachedBitmap.start()
}
/**
* Stops the renderer
*/
override fun stop() {
cachedBitmap.stop()
}
/**
* Suspend the renderer
*/
override fun suspend() {
cachedBitmap.suspend()
}
/**
* Suspend the renderer
*/
override fun resume() {
cachedBitmap.resume()
}
/**
* Invalidate the cache.
*/
fun invalidate() {
cachedBitmap.invalidate()
}
/**
* The current state of the cached bitmap
*/
internal enum class CacheState {
READY, NOT_INITIALIZED, IS_INITIALIZED, BEGIN_UPDATE, IS_UPDATING, DISABLED
}
/**
* The cached bitmap object. This object is continually kept up to date by CacheThread. If
* the object is locked, the background is updated using the low resolution background image
* instead
*/
internal inner class CacheBitmap {
/**
* The current position and dimensions of the cache within the background image
*/
internal val cacheWindow = Rect(0, 0, 0, 0)
/**
* The current state of the cache
*/
@get:Synchronized
@set:Synchronized
internal var state = CacheState.NOT_INITIALIZED
/**
* The currently cached bitmap
*/
internal var bitmap: Bitmap? = null
/**
* The cache bitmap loading thread
*/
private var cacheThread: CacheThread? = null
/**
* Used to hold the source Rect for bitmap drawing
*/
private val srcRect = Rect(0, 0, 0, 0)
/**
* Used to hold the dest Rect for bitmap drawing
*/
private val dstRect = Rect(0, 0, 0, 0)
private val dstSize = Point()
internal fun start() {
if (cacheThread != null) {
cacheThread!!.setRunning(false)
cacheThread!!.interrupt()
cacheThread = null
}
cacheThread = CacheThread(this)
cacheThread!!.name = CACHE_THREAD
cacheThread!!.start()
}
internal fun stop() {
cacheThread?.setRunning(false)
cacheThread?.interrupt()
var retry = true
while (retry) {
try {
cacheThread?.join()
retry = false
} catch (ignored: InterruptedException) {
// Wait until thread is dead
}
}
cacheThread = null
}
internal fun invalidate() {
state = CacheState.IS_INITIALIZED
cacheThread!!.interrupt()
}
fun suspend() {
state = CacheState.DISABLED
}
fun resume() {
if (state == CacheState.DISABLED) {
state = CacheState.IS_INITIALIZED
}
}
/**
* Draw the CacheBitmap on the viewport
*/
internal fun draw(p: ViewPort) {
if (cacheThread == null) return
var bmp: Bitmap? = null
when (state) {
CacheState.NOT_INITIALIZED -> {
// Error
Timber.e(TAG, "Attempting to update an uninitialized CacheBitmap")
return
}
CacheState.IS_INITIALIZED -> {
// Start data caching
state = CacheState.BEGIN_UPDATE
cacheThread!!.interrupt()
}
CacheState.BEGIN_UPDATE, CacheState.IS_UPDATING -> {
}
CacheState.DISABLED -> {
}
CacheState.READY -> if (bitmap == null || !cacheWindow.contains(p.window)) {
// No data loaded OR No cached data available
state = CacheState.BEGIN_UPDATE
cacheThread!!.interrupt()
} else {
bmp = bitmap
}
}// Currently updating; low resolution version used
// Use of high resolution version disabled
// Use the low resolution version if the cache is empty or scale factor is < threshold
if (bmp == null || zoom < lowResThreshold)
drawLowResolution()
else
drawHighResolution(bmp)
}
/**
* Use the high resolution cached bitmap for drawing
*/
private fun drawHighResolution(bmp: Bitmap?) {
val wSize = viewPort.window
if (bmp != null) {
synchronized(viewPort) {
val left = wSize.left - cacheWindow.left
val top = wSize.top - cacheWindow.top
val right = left + wSize.width()
val bottom = top + wSize.height()
viewPort.getPhysicalSize(dstSize)
srcRect.set(left, top, right, bottom)
dstRect.set(0, 0, dstSize.x, dstSize.y)
synchronized(viewPort.bitmapLock) {
val canvas = Canvas(viewPort.bitmap!!)
canvas.drawColor(Color.BLACK)
canvas.drawBitmap(bmp, srcRect, dstRect, null)
}
}
}
}
private fun drawLowResolution() {
if (state != CacheState.NOT_INITIALIZED) {
drawLowResolutionBackground()
}
}
/**
* This method fills the passed-in bitmap with sample data. This function must return data fast;
* this is our fall back solution in all the cases where the user is moving too fast for us to
* load the actual bitmap data from memory. The quality of the user experience rests on the speed
* of this function.
*/
private fun drawLowResolutionBackground() {
var w: Int
var h: Int
synchronized(viewPort.bitmapLock) {
if (viewPort.bitmap == null) return
w = viewPort.bitmap!!.width
h = viewPort.bitmap!!.height
}
val rect = viewPort.window
val left = rect.left shr sampleSize
val top = rect.top shr sampleSize
val right = rect.right shr sampleSize
val bottom = rect.bottom shr sampleSize
val sRect = Rect(left, top, right, bottom)
val dRect = Rect(0, 0, w, h)
// Draw to Canvas
synchronized(viewPort.bitmapLock) {
if (viewPort.bitmap != null && lowResBitmap != null) {
val canvas = Canvas(viewPort.bitmap!!)
canvas.drawBitmap(lowResBitmap!!, sRect, dRect, null)
}
}
}
}
/**
* This thread handles the background loading of the [CacheBitmap].
*
* The CacheThread
* starts an update when the [CacheBitmap.state] is [CacheState.BEGIN_UPDATE] and
* updates the bitmap given the current window.
*
* The CacheThread needs to be careful how it
* locks [CacheBitmap] in order to ensure the smoothest possible performance (loading can
* take a while).
*/
internal inner class CacheThread(private val cache: CacheBitmap) : Thread() {
private var running: Boolean = false
init {
name = CACHE_THREAD
}
override fun run() {
running = true
val viewportRect = Rect(0, 0, 0, 0)
while (running) {
// Wait until we are ready to go
while (running && cache.state != CacheState.BEGIN_UPDATE) {
try {
sleep(Integer.MAX_VALUE.toLong())
} catch (ignored: InterruptedException) {
// NOOP
}
}
if (!running) return
// Start Loading Timer
val startTime = System.currentTimeMillis()
// Load Data
var startLoading = false
synchronized(cache) {
if (cache.state == CacheState.BEGIN_UPDATE) {
cache.state = CacheState.IS_UPDATING
cache.bitmap = null
startLoading = true
}
}
if (startLoading) {
synchronized(viewPort) {
viewportRect.set(viewPort.window)
}
var continueLoading = false
synchronized(cache) {
if (cache.state == CacheState.IS_UPDATING) {
cache.cacheWindow.set(calculateCacheDimensions(viewportRect))
continueLoading = true
}
}
if (continueLoading) {
try {
val bitmap = loadCachedBitmap(cache.cacheWindow)
if (bitmap != null) {
synchronized(cache) {
if (cache.state == CacheState.IS_UPDATING) {
cache.bitmap = bitmap
cache.state = CacheState.READY
} else {
Timber.d(TAG, "Loading of background image cache aborted")
}
}
}
// End Loading Timer
val endTime = System.currentTimeMillis()
Timber.d("Loaded background image in ${(endTime - startTime)} ms")
} catch (ignored: OutOfMemoryError) {
Timber.w(TAG, "CacheThread out of memory")
// Out of memory ERROR detected. Lower the memory allocation
cacheBitmapOutOfMemoryError()
synchronized(cache) {
if (cache.state == CacheState.IS_UPDATING) {
cache.state = CacheState.BEGIN_UPDATE
}
}
}
}
}
}
}
/**
* Determine the dimensions of the CacheBitmap based on the current ViewPort.
*
* Minimum size is
* equal to the viewport; otherwise it is dimensioned relative to the available memory. [ ] is locked while the calculation is done, so this has to be fast.
*
* @param rect The dimensions of the current viewport
* @return The dimensions of the cache
*/
private fun calculateCacheDimensions(rect: Rect): Rect {
val bytesToUse = Runtime.getRuntime().maxMemory() * memUsage / 100
val sz = backgroundSize
val vw = rect.width()
val vh = rect.height()
// Calculate the margins within the memory budget
var tw = 0
var th = 0
var mw = tw
var mh = th
val bytesPerPixel = 4
while ((vw + tw) * (vh + th) * bytesPerPixel < bytesToUse) {
tw++
mw = tw
th++
mh = th
}
// Trim margins to image size
if (vw + mw > sz.x) mw = Math.max(0, sz.x - vw)
if (vh + mh > sz.y) mh = Math.max(0, sz.y - vh)
// Figure out the left & right based on the margin.
// LATER: THe logic here assumes that the viewport is <= our size.
// If that's not the case, then this logic breaks.
var left = rect.left - (mw shr 1)
var right = rect.right + (mw shr 1)
if (left < 0) {
right -= left // Adds the overage on the left side back to the right
left = 0
}
if (right > sz.x) {
left -= right - sz.x // Adds overage on right side back to left
right = sz.x
}
// Figure out the top & bottom based on the margin. We assume our viewport
// is <= our size. If that's not the case, then this logic breaks.
var top = rect.top - (mh shr 1)
var bottom = rect.bottom + (mh shr 1)
if (top < 0) {
bottom -= top // Adds the overage on the top back to the bottom
top = 0
}
if (bottom > sz.y) {
top -= bottom - sz.y // Adds overage on bottom back to top
bottom = sz.y
}
// Set the origin based on our new calculated values.
calculatedCacheWindowRect.set(left, top, right, bottom)
return calculatedCacheWindowRect
}
fun setRunning(r: Boolean) {
running = r
}
/**
* Loads the relevant slice of the background bitmap that needs to be kept in memory.
*
* The
* loading can take a long time depending on the size.
*
* @param rect The portion of the background bitmap to be cached
* @return The bitmap representing the requested area of the background
*/
private fun loadCachedBitmap(rect: Rect): Bitmap? {
return decoder!!.decodeRegion(rect, options)
}
/**
* This function tries to recover from an OutOfMemoryError in the CacheThread.
*/
private fun cacheBitmapOutOfMemoryError() {
if (memUsage > 0) memUsage -= 1
Timber.e(TAG, "OutOfMemory caught; reducing cache size to $memUsage percent.")
}
}
}
| apache-2.0 | 6fa2dc18886273335e4f13818ae3062f | 29.546618 | 160 | 0.613621 | 4.38902 | false | false | false | false |
AndroidX/androidx | work/work-runtime-ktx/src/main/java/androidx/work/CoroutineWorker.kt | 3 | 5187 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work
import android.content.Context
import androidx.work.impl.utils.futures.SettableFuture
import com.google.common.util.concurrent.ListenableFuture
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* A [ListenableWorker] implementation that provides interop with Kotlin Coroutines. Override
* the [doWork] function to do your suspending work.
* <p>
* By default, CoroutineWorker runs on [Dispatchers.Default]; this can be modified by
* overriding [coroutineContext].
* <p>
* A CoroutineWorker is given a maximum of ten minutes to finish its execution and return a
* [ListenableWorker.Result]. After this time has expired, the worker will be signalled to stop.
*/
public abstract class CoroutineWorker(
appContext: Context,
params: WorkerParameters
) : ListenableWorker(appContext, params) {
internal val job = Job()
internal val future: SettableFuture<Result> = SettableFuture.create()
init {
future.addListener(
Runnable {
if (future.isCancelled) {
job.cancel()
}
},
taskExecutor.serialTaskExecutor
)
}
/**
* The coroutine context on which [doWork] will run. By default, this is [Dispatchers.Default].
*/
@Deprecated(message = "use withContext(...) inside doWork() instead.")
public open val coroutineContext: CoroutineDispatcher = Dispatchers.Default
@Suppress("DEPRECATION")
public final override fun startWork(): ListenableFuture<Result> {
val coroutineScope = CoroutineScope(coroutineContext + job)
coroutineScope.launch {
try {
val result = doWork()
future.set(result)
} catch (t: Throwable) {
future.setException(t)
}
}
return future
}
/**
* A suspending method to do your work.
* <p>
* To specify which [CoroutineDispatcher] your work should run on, use `withContext()`
* within `doWork()`.
* If there is no other dispatcher declared, [Dispatchers.Default] will be used.
* <p>
* A CoroutineWorker is given a maximum of ten minutes to finish its execution and return a
* [ListenableWorker.Result]. After this time has expired, the worker will be signalled to
* stop.
*
* @return The [ListenableWorker.Result] of the result of the background work; note that
* dependent work will not execute if you return [ListenableWorker.Result.failure]
*/
public abstract suspend fun doWork(): Result
/**
* @return The [ForegroundInfo] instance if the [WorkRequest] is marked as expedited.
*
* @throws [IllegalStateException] when not overridden. Override this method when the
* corresponding [WorkRequest] is marked expedited.
*/
public open suspend fun getForegroundInfo(): ForegroundInfo {
throw IllegalStateException("Not implemented")
}
/**
* Updates the progress for the [CoroutineWorker]. This is a suspending function unlike the
* [setProgressAsync] API which returns a [ListenableFuture].
*
* @param data The progress [Data]
*/
public suspend fun setProgress(data: Data) {
setProgressAsync(data).await()
}
/**
* Makes the [CoroutineWorker] run in the context of a foreground [android.app.Service]. This
* is a suspending function unlike the [setForegroundAsync] API which returns a
* [ListenableFuture].
*
* Calling [setForeground] will throw an [IllegalStateException] if the process is subject to
* foreground service restrictions. Consider using [WorkRequest.Builder.setExpedited]
* and [getForegroundInfo] instead.
*
* @param foregroundInfo The [ForegroundInfo]
*/
public suspend fun setForeground(foregroundInfo: ForegroundInfo) {
setForegroundAsync(foregroundInfo).await()
}
@Suppress("DEPRECATION")
public final override fun getForegroundInfoAsync(): ListenableFuture<ForegroundInfo> {
val job = Job()
val scope = CoroutineScope(coroutineContext + job)
val jobFuture = JobListenableFuture<ForegroundInfo>(job)
scope.launch {
jobFuture.complete(getForegroundInfo())
}
return jobFuture
}
public final override fun onStopped() {
super.onStopped()
future.cancel(false)
}
}
| apache-2.0 | da5e053d9814d2374a7528dc666015b6 | 35.272727 | 99 | 0.681704 | 4.893396 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/fleets/FleetListSimple.kt | 1 | 3599 | package au.com.codeka.warworlds.client.game.fleets
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.game.build.BuildViewHelper.setDesignIcon
import au.com.codeka.warworlds.common.proto.Fleet
import au.com.codeka.warworlds.common.proto.Star
import au.com.codeka.warworlds.common.sim.DesignHelper
import java.util.*
import kotlin.math.roundToInt
/**
* Represents a simple list of fleets, shown inside a [LinearLayout].
*/
class FleetListSimple : LinearLayout {
private var star: Star? = null
private var fleets: MutableList<Fleet> = ArrayList()
private var fleetSelectedHandler: FleetSelectedHandler? = null
private var clickListener: OnClickListener? = null
/** An interface you can implement to filter the list of fleets we display in the list. */
interface FleetFilter {
fun showFleet(fleet: Fleet?): Boolean
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
orientation = VERTICAL
}
constructor(context: Context) : super(context) {
orientation = VERTICAL
}
fun setFleetSelectedHandler(handler: FleetSelectedHandler?) {
fleetSelectedHandler = handler
}
fun setStar(s: Star) {
setStar(s, s.fleets, null)
}
fun setStar(s: Star, f: FleetFilter?) {
setStar(s, s.fleets, f)
}
fun setStar(s: Star, f: List<Fleet>) {
setStar(s, f, null)
}
private fun setStar(s: Star, f: List<Fleet>, filter: FleetFilter?) {
star = s
fleets.clear()
for (fleet in f) {
if (fleet.state != Fleet.FLEET_STATE.MOVING && fleet.num_ships > 0.01f &&
(filter == null || filter.showFleet(fleet))) {
fleets.add(fleet)
}
}
refresh()
}
val numFleets: Int
get() = fleets.size
private fun refresh() {
if (clickListener == null) {
clickListener = OnClickListener { v: View ->
val fleet = v.tag as Fleet
if (fleetSelectedHandler != null) {
fleetSelectedHandler!!.onFleetSelected(fleet)
}
}
}
removeAllViews()
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
for (fleet in fleets) {
val rowView = getRowView(inflater, fleet)
addView(rowView)
}
}
private fun getRowView(inflater: LayoutInflater, fleet: Fleet): View {
val view = inflater.inflate(R.layout.ctrl_fleet_list_simple_row, this, false)
val design = DesignHelper.getDesign(fleet.design_type)
val icon = view.findViewById<ImageView>(R.id.fleet_icon)
val row1 = view.findViewById<TextView>(R.id.fleet_row1)
val row2 = view.findViewById<TextView>(R.id.fleet_row2)
val fuelLevel = view.findViewById<ProgressBar>(R.id.fuel_level)
val maxFuel = (design.fuel_size!! * fleet.num_ships).toInt()
if (fleet.fuel_amount >= maxFuel) {
fuelLevel.visibility = View.GONE
} else {
fuelLevel.visibility = View.VISIBLE
fuelLevel.max = maxFuel
fuelLevel.progress = (fleet.fuel_amount).roundToInt()
}
setDesignIcon(design, icon)
row1.text = FleetListHelper.getFleetName(fleet, design)
row2.text = FleetListHelper.getFleetStance(fleet)
view.setOnClickListener(clickListener)
view.tag = fleet
return view
}
interface FleetSelectedHandler {
fun onFleetSelected(fleet: Fleet?)
}
} | mit | 3a3ad874158952674c07c1f3049d32ab | 30.034483 | 94 | 0.703807 | 3.80444 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/docker/pull/DockerImageProgress.kt | 1 | 2106 | /*
Copyright 2017-2020 Charles Korn.
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 batect.docker.pull
import kotlin.math.roundToInt
data class DockerImageProgress(val currentOperation: String, val completedBytes: Long, val totalBytes: Long) {
fun toStringForDisplay(): String {
if (totalBytes == 0L) {
return when (completedBytes) {
0L -> currentOperation
else -> "$currentOperation: ${humaniseBytes(completedBytes)}"
}
}
val percentage = (completedBytes.toDouble() / totalBytes * 100).roundToInt()
return "$currentOperation: ${humaniseBytes(completedBytes)} of ${humaniseBytes(totalBytes)} ($percentage%)"
}
private fun humaniseBytes(bytes: Long): String = when {
bytes < oneKilobyte -> "$bytes B"
bytes < oneMegabyte -> "${formatFraction(bytes.toDouble() / oneKilobyte)} KB"
bytes < oneGigabyte -> "${formatFraction(bytes.toDouble() / oneMegabyte)} MB"
bytes < oneTerabyte -> "${formatFraction(bytes.toDouble() / oneGigabyte)} GB"
else -> "${formatFraction(bytes.toDouble() / oneTerabyte)} TB"
}
private fun formatFraction(value: Double) = String.format("%.1f", value)
companion object {
// The Docker client uses decimal prefixes (1 MB = 1000 KB), so so do we.
private const val oneKilobyte: Long = 1000
private const val oneMegabyte: Long = 1000 * oneKilobyte
private const val oneGigabyte: Long = 1000 * oneMegabyte
private const val oneTerabyte: Long = 1000 * oneGigabyte
}
}
| apache-2.0 | bb62fd31dedd6d7790cc62f53f867e4c | 39.5 | 115 | 0.674739 | 4.245968 | false | false | false | false |
androidx/androidx | wear/compose/integration-tests/macrobenchmark-target/src/main/java/androidx/wear/compose/integration/macrobenchmark/target/BaselineActivity.kt | 3 | 22469 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.integration.macrobenchmark.target
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import androidx.wear.compose.foundation.CurvedLayout
import androidx.wear.compose.foundation.CurvedModifier
import androidx.wear.compose.foundation.CurvedTextStyle
import androidx.wear.compose.foundation.basicCurvedText
import androidx.wear.compose.foundation.padding
import androidx.wear.compose.material.AppCard
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.Card
import androidx.wear.compose.material.Checkbox
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.CircularProgressIndicator
import androidx.wear.compose.material.CompactButton
import androidx.wear.compose.material.CompactChip
import androidx.wear.compose.material.ExperimentalWearMaterialApi
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.InlineSlider
import androidx.wear.compose.material.InlineSliderDefaults
import androidx.wear.compose.material.ListHeader
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.OutlinedButton
import androidx.wear.compose.material.OutlinedChip
import androidx.wear.compose.material.OutlinedCompactButton
import androidx.wear.compose.material.OutlinedCompactChip
import androidx.wear.compose.material.Picker
import androidx.wear.compose.material.PlaceholderDefaults
import androidx.wear.compose.material.PositionIndicator
import androidx.wear.compose.material.RadioButton
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.SplitToggleChip
import androidx.wear.compose.material.Stepper
import androidx.wear.compose.material.StepperDefaults
import androidx.wear.compose.material.Switch
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.TitleCard
import androidx.wear.compose.material.ToggleButton
import androidx.wear.compose.material.ToggleChip
import androidx.wear.compose.material.ToggleChipDefaults
import androidx.wear.compose.material.Vignette
import androidx.wear.compose.material.VignettePosition
import androidx.wear.compose.material.curvedText
import androidx.wear.compose.material.dialog.Alert
import androidx.wear.compose.material.dialog.Confirmation
import androidx.wear.compose.material.placeholder
import androidx.wear.compose.material.placeholderShimmer
import androidx.wear.compose.material.rememberPickerState
import androidx.wear.compose.material.rememberPlaceholderState
import androidx.wear.compose.material.scrollAway
import androidx.wear.compose.navigation.SwipeDismissableNavHost
import androidx.wear.compose.navigation.composable
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import kotlinx.coroutines.delay
private val ALERT_DIALOG = "alert-dialog"
private val CONFIRMATION_DIALOG = "confirmation-dialog"
private val BUTTONS = "buttons"
private val CARDS = "cards"
private val CHIPS = "chips"
private val RADIO_BUTTON = "radio-button"
private val CHECKBOX = "checkbox"
private val SWITCH = "switch"
private val DIALOGS = "dialogs"
private val PICKER = "picker"
private val PROGRESSINDICATORS = "progressindicators"
private val SLIDER = "slider"
private val START_INDEX = "start-index"
private val STEPPER = "stepper"
private val SWIPE_DISMISS = "swipe-dismiss"
private val PROGRESS_INDICATOR = "progress-indicator"
private val PROGRESS_INDICATOR_INDETERMINATE = "progress-indicator-indeterminate"
private val PLACEHOLDERS = "placeholders"
class BaselineActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberSwipeDismissableNavController()
val scrollState = rememberScrollState()
MaterialTheme {
Scaffold(
timeText = {
TimeText(
modifier = Modifier.scrollAway(scrollState = scrollState)
)
},
positionIndicator = { PositionIndicator(scrollState = scrollState) },
vignette = { Vignette(vignettePosition = VignettePosition.TopAndBottom) },
) {
SwipeDismissableNavHost(
navController = navController,
startDestination = START_INDEX,
modifier = Modifier
.background(MaterialTheme.colors.background)
.semantics { contentDescription = SWIPE_DISMISS }
) {
composable(START_INDEX) { StartIndex(navController, scrollState) }
composable(DIALOGS) {
Dialogs(navController)
}
composable(ALERT_DIALOG) {
Alert(
title = { Text("Alert") },
negativeButton = {},
positiveButton = {},
)
}
composable(CONFIRMATION_DIALOG) {
Confirmation(
onTimeout = { navController.popBackStack() },
content = { Text("Confirmation") },
)
}
composable(BUTTONS) { Buttons() }
composable(CARDS) { Cards() }
composable(CHIPS) { Chips() }
composable(PICKER) { Picker(scrollState) }
composable(PLACEHOLDERS) { Placeholders() }
composable(PROGRESSINDICATORS) { ProgressIndicators(navController) }
composable(PROGRESS_INDICATOR) {
CircularProgressIndicator(
modifier = Modifier.fillMaxSize(),
startAngle = 300f,
endAngle = 240f,
progress = 0.3f
)
}
composable(PROGRESS_INDICATOR_INDETERMINATE) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize(),
) {
CircularProgressIndicator()
}
}
composable(SLIDER) { Slider() }
composable(STEPPER) { Stepper() }
}
}
}
}
}
}
@Composable
fun StartIndex(navController: NavHostController, scrollState: ScrollState) {
Box {
CurvedTexts()
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(state = scrollState)
.padding(vertical = 32.dp)
.semantics { contentDescription = CONTENT_DESCRIPTION },
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Widget(navController, BUTTONS, "Btn", BUTTONS)
Widget(navController, CARDS, "Card", CARDS)
Widget(navController, PLACEHOLDERS, "Plc", PLACEHOLDERS)
}
Spacer(modifier = Modifier.height(4.dp))
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Widget(navController, CHIPS, "Chip", CHIPS)
Widget(navController, DIALOGS, "Dlg", DIALOGS)
Widget(navController, PICKER, "Pick", PICKER)
}
Spacer(modifier = Modifier.height(4.dp))
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Widget(navController, PROGRESSINDICATORS,
"Prog", PROGRESSINDICATORS)
Widget(navController, SLIDER, "Sldr", SLIDER)
Widget(navController, STEPPER, "Stpr", STEPPER)
}
}
}
}
@Composable
fun Dialogs(navController: NavHostController) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ListHeader { Text("Dialogs") }
CompactChip(
onClick = { navController.navigate(ALERT_DIALOG) },
colors = ChipDefaults.primaryChipColors(),
label = { Text(ALERT_DIALOG) },
modifier = Modifier.semantics {
contentDescription = ALERT_DIALOG
},
)
Spacer(Modifier.height(4.dp))
CompactChip(
onClick = { navController.navigate(CONFIRMATION_DIALOG) },
colors = ChipDefaults.primaryChipColors(),
label = { Text(CONFIRMATION_DIALOG) },
modifier = Modifier.semantics {
contentDescription = CONFIRMATION_DIALOG
},
)
}
}
@Composable
fun Buttons() {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
ListHeader { Text("Buttons") }
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Button(onClick = {}) { Text("B") }
OutlinedButton(onClick = {}) { Text("OB") }
}
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
CompactButton(onClick = {}) { Text("CB") }
OutlinedCompactButton(onClick = {}) { Text("OCB") }
}
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
ToggleButton(
checked = true,
onCheckedChange = {}) { Text("TB") }
}
}
}
@Composable
fun Cards() {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ListHeader { Text("Cards") }
Card(onClick = {}) { Text("Card") }
AppCard(onClick = {},
appName = { Text("AppName") }, title = {},
time = { Text("02:34") }) {
Text("AppCard")
}
TitleCard(onClick = {}, title = { Text("Title") }) {
Text("TitleCard")
}
}
}
@Composable
fun Chips() {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Chip(
modifier = Modifier.height(32.dp),
onClick = {},
colors = ChipDefaults.primaryChipColors(),
label = { Text("C") }
)
OutlinedChip(
modifier = Modifier.height(32.dp),
onClick = {},
label = { Text("OC") }
)
}
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
CompactChip(onClick = {}, label = { Text("CC") })
OutlinedCompactChip(onClick = {}, label = { Text("OCC") })
}
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
var radioState by remember { mutableStateOf(false) }
ToggleChip(
checked = radioState,
onCheckedChange = { radioState = !radioState },
label = { Text("R") },
toggleControl = {
Icon(
imageVector =
ToggleChipDefaults.radioIcon(checked = radioState),
contentDescription = null
)
}
)
var switchState by remember { mutableStateOf(false) }
ToggleChip(
checked = switchState,
onCheckedChange = { switchState = !switchState },
label = { Text("S") },
toggleControl = {
Icon(
imageVector =
ToggleChipDefaults.switchIcon(checked = switchState),
contentDescription = null
)
}
)
var checkboxState by remember { mutableStateOf(false) }
ToggleChip(
checked = checkboxState,
onCheckedChange = { checkboxState = !checkboxState },
label = { Text("C") },
toggleControl = {
Icon(
imageVector =
ToggleChipDefaults.checkboxIcon(checked = checkboxState),
contentDescription = null
)
}
)
}
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
var radioState by remember { mutableStateOf(false) }
ToggleChip(
checked = radioState,
onCheckedChange = { radioState = !radioState },
label = { Text("R") },
toggleControl = { RadioButton(selected = radioState) },
modifier = Modifier.semantics { contentDescription = RADIO_BUTTON },
)
var switchState by remember { mutableStateOf(false) }
ToggleChip(
checked = switchState,
onCheckedChange = { switchState = !switchState },
label = { Text("S") },
toggleControl = { Switch(checked = switchState) },
modifier = Modifier.semantics { contentDescription = SWITCH },
)
var checkboxState by remember { mutableStateOf(false) }
ToggleChip(
checked = checkboxState,
onCheckedChange = { checkboxState = !checkboxState },
label = { Text("C") },
toggleControl = { Checkbox(checked = checkboxState) },
modifier = Modifier.semantics { contentDescription = CHECKBOX },
)
}
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
SplitToggleChip(
checked = true,
onCheckedChange = {},
label = { Text("Split") },
onClick = {},
toggleControl = {
Icon(
imageVector =
ToggleChipDefaults.radioIcon(checked = true),
contentDescription = null
)
}
)
}
}
}
@Composable
fun Picker(scrollState: ScrollState) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(state = scrollState)
.padding(vertical = 16.dp)
.semantics { contentDescription = CONTENT_DESCRIPTION },
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ListHeader { Text("Pickers") }
val items = listOf("One", "Two", "Three", "Four", "Five")
val state = rememberPickerState(items.size)
val contentDescription by remember {
derivedStateOf { "${state.selectedOption + 1 }" }
}
Picker(
state = state,
contentDescription = contentDescription,
option = { Text(items[it]) },
modifier = Modifier.size(100.dp, 100.dp),
)
}
}
@OptIn(ExperimentalWearMaterialApi::class)
@Composable
fun Placeholders() {
var labelText by remember { mutableStateOf("") }
var iconContent: @Composable () -> Unit = { Checkbox(true) }
val chipPlaceholderState = rememberPlaceholderState {
labelText.isNotEmpty()
}
Chip(
onClick = { /* Do something */ },
enabled = true,
label = {
Text(
text = labelText,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.placeholder(chipPlaceholderState)
)
},
icon = {
Box(
modifier = Modifier
.size(ChipDefaults.IconSize)
.placeholder(chipPlaceholderState),
) {
iconContent()
}
},
colors = PlaceholderDefaults.placeholderChipColors(
originalChipColors = ChipDefaults.primaryChipColors(),
placeholderState = chipPlaceholderState
),
modifier = Modifier
.fillMaxWidth()
.placeholderShimmer(chipPlaceholderState)
)
LaunchedEffect(Unit) {
delay(50)
iconContent = { Switch(true) }
delay(1000)
labelText = "A label"
}
if (!chipPlaceholderState.isShowContent) {
LaunchedEffect(chipPlaceholderState) {
chipPlaceholderState.startPlaceholderAnimation()
}
}
}
@Composable
fun ProgressIndicators(navController: NavHostController) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ListHeader { Text("Progress Indicators") }
// Test both circular progress indicator with gap and spinning indicator.
CompactChip(
onClick = { navController.navigate(PROGRESS_INDICATOR) },
colors = ChipDefaults.primaryChipColors(),
label = { Text(PROGRESS_INDICATOR) },
modifier = Modifier.semantics {
contentDescription = PROGRESS_INDICATOR
},
)
Spacer(Modifier.height(4.dp))
CompactChip(
onClick = {
navController.navigate(
PROGRESS_INDICATOR_INDETERMINATE
)
},
colors = ChipDefaults.primaryChipColors(),
label = { Text(PROGRESS_INDICATOR_INDETERMINATE) },
modifier = Modifier.semantics {
contentDescription = PROGRESS_INDICATOR_INDETERMINATE
},
)
}
}
@Composable
fun Slider() {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ListHeader { Text("Sliders") }
var value by remember { mutableStateOf(4.5f) }
InlineSlider(
value = value,
onValueChange = { value = it },
increaseIcon = {
Icon(
InlineSliderDefaults.Increase,
"Increase"
)
},
decreaseIcon = {
Icon(
InlineSliderDefaults.Decrease,
"Decrease"
)
},
valueRange = 3f..6f,
steps = 5,
segmented = false
)
}
}
@Composable
fun Stepper() {
var value by remember { mutableStateOf(2f) }
Stepper(
value = value,
onValueChange = { value = it },
increaseIcon = { Icon(StepperDefaults.Increase, "Increase") },
decreaseIcon = { Icon(StepperDefaults.Decrease, "Decrease") },
valueRange = 1f..4f,
steps = 7
) { Text("Value: $value") }
}
@Composable
fun CurvedTexts() {
val background = MaterialTheme.colors.background
CurvedLayout(anchor = 235f) {
basicCurvedText(
"Basic",
CurvedTextStyle(
fontSize = 16.sp,
color = Color.White,
background = background
),
modifier = CurvedModifier.padding(2.dp)
)
}
CurvedLayout(anchor = 310f) {
curvedText(text = "Curved")
}
}
@Composable
fun Widget(navController: NavHostController, destination: String, text: String, desc: String) {
Button(
onClick = { navController.navigate(destination) },
modifier = Modifier.semantics { contentDescription = desc }
) {
Text(text)
}
}
| apache-2.0 | 6a5ee8be7ea322533c893ffd32891658 | 36.890388 | 95 | 0.588589 | 5.399904 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontWeight.kt | 3 | 4348 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.font
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.util.lerp
/**
* The thickness of the glyphs, in a range of [1, 1000].
*
* @param weight Font weight value in the range of [1, 1000]
*
* @see Font
* @see FontFamily
*/
@Immutable
class FontWeight(val weight: Int) : Comparable<FontWeight> {
companion object {
/** [Thin] */
@Stable
val W100 = FontWeight(100)
/** [ExtraLight] */
@Stable
val W200 = FontWeight(200)
/** [Light] */
@Stable
val W300 = FontWeight(300)
/** [Normal] / regular / plain */
@Stable
val W400 = FontWeight(400)
/** [Medium] */
@Stable
val W500 = FontWeight(500)
/** [SemiBold] */
@Stable
val W600 = FontWeight(600)
/** [Bold] */
@Stable
val W700 = FontWeight(700)
/** [ExtraBold] */
@Stable
val W800 = FontWeight(800)
/** [Black] */
@Stable
val W900 = FontWeight(900)
/** Alias for [W100] */
@Stable
val Thin = W100
/** Alias for [W200] */
@Stable
val ExtraLight = W200
/** Alias for [W300] */
@Stable
val Light = W300
/** The default font weight - alias for [W400] */
@Stable
val Normal = W400
/** Alias for [W500] */
@Stable
val Medium = W500
/** Alias for [W600] */
@Stable
val SemiBold = W600
/**
* A commonly used font weight that is heavier than normal - alias for [W700]
*/
@Stable
val Bold = W700
/** Alias for [W800] */
@Stable
val ExtraBold = W800
/** Alias for [W900] */
@Stable
val Black = W900
/** A list of all the font weights. */
internal val values: List<FontWeight> = listOf(
W100,
W200,
W300,
W400,
W500,
W600,
W700,
W800,
W900
)
}
init {
require(weight in 1..1000) {
"Font weight can be in range [1, 1000]. Current value: $weight"
}
}
override operator fun compareTo(other: FontWeight): Int {
return weight.compareTo(other.weight)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FontWeight) return false
if (weight != other.weight) return false
return true
}
override fun hashCode(): Int {
return weight
}
override fun toString(): String {
return "FontWeight(weight=$weight)"
}
}
/**
* Linearly interpolate between two font weights.
*
* The [fraction] argument represents position on the timeline, with 0.0 meaning
* that the interpolation has not started, returning [start] (or something
* equivalent to [start]), 1.0 meaning that the interpolation has finished,
* returning [stop] (or something equivalent to [stop]), and values in between
* meaning that the interpolation is at the relevant point on the timeline
* between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and
* 1.0, so negative values and values greater than 1.0 are valid (and can
* easily be generated by curves).
*
* Values for [fraction] are usually obtained from an [Animation<Float>], such as
* an `AnimationController`.
*/
fun lerp(start: FontWeight, stop: FontWeight, fraction: Float): FontWeight {
val weight = lerp(start.weight, stop.weight, fraction).coerceIn(1, 1000)
return FontWeight(weight)
}
| apache-2.0 | d71533417506ba1c973b1c7a280037b2 | 27.986667 | 85 | 0.589466 | 4.172745 | false | false | false | false |
sheungon/SotwtmSupportLib | lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/util/databinding/ActionBarHelpfulBindingAdapter.kt | 1 | 698 | package com.sotwtm.support.util.databinding
import androidx.databinding.BindingMethod
import androidx.databinding.BindingMethods
import androidx.appcompat.app.ActionBar
/**
* DataBinding methods and BindingMethods created for easier implementation for Android DataBinding.
* Implementation for [ActionBar]
*
* @author sheungon
*/
@BindingMethods(
BindingMethod(
type = ActionBar::class,
attribute = "setDisplayShowHomeEnabled",
method = "setDisplayShowHomeEnabled"
),
BindingMethod(
type = ActionBar::class,
attribute = "setDisplayHomeAsUpEnabled",
method = "setDisplayHomeAsUpEnabled"
)
)
object ActionBarHelpfulBindingAdapter | apache-2.0 | 46cadc6c1c4d244315a3eec23f1ffd81 | 26.96 | 100 | 0.74212 | 5.208955 | false | false | false | false |
Soya93/Extract-Refactoring | platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerPathHandler.kt | 2 | 4000 | /*
* Copyright 2000-2014 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.builtInWebServer
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.io.endsWithSlash
import com.intellij.openapi.util.io.getParentPath
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpResponseStatus
import org.jetbrains.io.Responses
import java.io.File
private class DefaultWebServerPathHandler : WebServerPathHandler() {
override fun process(path: String,
project: Project,
request: FullHttpRequest,
context: ChannelHandlerContext,
projectName: String,
decodedRawPath: String,
isCustomHost: Boolean): Boolean {
val channel = context.channel()
val pathToFileManager = WebServerPathToFileManager.getInstance(project)
var pathInfo = pathToFileManager.pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
pathInfo = pathToFileManager.doFindByRelativePath(path)
if (pathInfo == null) {
if (path.isEmpty()) {
Responses.sendStatus(HttpResponseStatus.NOT_FOUND, channel, "Index file doesn't exist.", request)
return true
}
else {
return false
}
}
pathToFileManager.pathToInfoCache.put(path, pathInfo)
}
var indexUsed = false
if (pathInfo.isDirectory()) {
if (!endsWithSlash(decodedRawPath)) {
redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path")
return true
}
var indexVirtualFile: VirtualFile? = null
var indexFile: File? = null
if (pathInfo.file == null) {
indexFile = findIndexFile(pathInfo.ioFile!!)
}
else {
indexVirtualFile = findIndexFile(pathInfo.file!!)
}
if (indexFile == null && indexVirtualFile == null) {
Responses.sendStatus(HttpResponseStatus.NOT_FOUND, channel, "Index file doesn't exist.", request)
return true
}
indexUsed = true
pathInfo = PathInfo(indexFile, indexVirtualFile, pathInfo.root, pathInfo.moduleName, pathInfo.isLibrary)
pathToFileManager.pathToInfoCache.put(path, pathInfo)
}
if (!indexUsed && !endsWithName(path, pathInfo.name)) {
if (endsWithSlash(decodedRawPath)) {
indexUsed = true
}
else {
// FallbackResource feature in action, /login requested, /index.php retrieved, we must not redirect /login to /login/
val parentPath = getParentPath(pathInfo.path)
if (parentPath != null && endsWithName(path, PathUtilRt.getFileName(parentPath))) {
redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path")
return true
}
}
}
val canonicalPath = if (indexUsed) "$path/${pathInfo.name}" else path
for (fileHandler in WebServerFileHandler.EP_NAME.extensions) {
LOG.catchAndLog {
if (fileHandler.process(pathInfo!!, canonicalPath, project, request, channel, if (isCustomHost) null else projectName)) {
return true
}
}
}
return false
}
} | apache-2.0 | 692da98866fa3e3d277e8b8dc2322308 | 36.392523 | 129 | 0.679 | 4.711425 | false | false | false | false |
sebasjm/deepdiff | src/main/kotlin/diff/equality/PairAbsolute.kt | 1 | 2136 | package diff.equality
import diff.patch.Coordinate
import diff.patch.Getter
import diff.patch.coords.RootCoordinate
import java.util.Objects
/**
* @author sebasjm <smarchano></smarchano>@primary.com.ar>
*/
class PairAbsolute<Type: Any>(private val before: Type?, private val after: Type?) : Pair<Type, Any> {
private val beforeGetter: Getter<Type>
private val afterGetter: Getter<Type>
private val type: Class<Type>?
private val coordinate = RootCoordinate<Type>()
init {
this.beforeGetter = if (before == null) Getter.nullObject as Getter<Type> else this.coordinate.getter(true, before)
this.afterGetter = if (after == null) Getter.nullObject as Getter<Type> else this.coordinate.getter(false, after)
this.type = afterGetter.get()?.javaClass ?: beforeGetter.get()?.javaClass
}
override fun sameObject(): Boolean {
return before === after
}
override fun sameClass(): Boolean {
return sameObject() || bothNotNull() && before?.javaClass == after?.javaClass
}
override fun bothNotNull(): Boolean {
return before != null && after != null
}
override fun coordinate(): Coordinate<Type, Any> {
return coordinate
}
override fun before(): Type? {
return before
}
override fun after(): Type? {
return after
}
override fun type(): Class<Type>? {
return type
}
override fun toString(): String {
return "abs_pair(before:$before,after:$after)"
}
override fun hashCode(): Int {
var hash = 3
hash = 97 * hash + Objects.hashCode(this.before)
hash = 97 * hash + Objects.hashCode(this.after)
return hash
}
override fun equals(obj: Any?): Boolean {
if (obj == null) {
return false
}
if (javaClass != obj.javaClass) {
return false
}
val other = obj as PairAbsolute<*>?
if (this.before != other!!.before) {
return false
}
if (this.after != other.after) {
return false
}
return true
}
}
| apache-2.0 | fc2ad9bd52960549a43db644c5c1dea3 | 25.37037 | 123 | 0.602528 | 4.315152 | false | false | false | false |
IRA-Team/VKPlayer | app/src/main/java/com/irateam/vkplayer/fragment/BaseAudioListFragment.kt | 1 | 7850 | /*
* Copyright (C) 2016 IRA-Team
*
* 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.irateam.vkplayer.fragment
import android.os.Bundle
import android.support.annotation.MenuRes
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SearchView
import android.view.*
import com.irateam.vkplayer.R
import com.irateam.vkplayer.adapter.BaseAudioRecyclerAdapter
import com.irateam.vkplayer.controller.PlayerController
import com.irateam.vkplayer.model.Audio
import com.irateam.vkplayer.player.Player
import com.irateam.vkplayer.util.Comparators
import com.irateam.vkplayer.util.EventBus
import com.irateam.vkplayer.util.extension.getViewById
import com.irateam.vkplayer.util.extension.slideInUp
import com.irateam.vkplayer.util.extension.slideOutDown
import java.util.*
abstract class BaseAudioListFragment : BaseFragment(),
ActionMode.Callback,
SearchView.OnQueryTextListener,
BackPressedListener,
BaseAudioRecyclerAdapter.CheckedListener {
protected abstract val adapter: BaseAudioRecyclerAdapter<out Audio, out RecyclerView.ViewHolder>
/**
* Views
*/
protected lateinit var recyclerView: RecyclerView
protected lateinit var refreshLayout: SwipeRefreshLayout
protected lateinit var emptyView: View
protected lateinit var sortModeHolder: View
/**
* Menus
*/
protected lateinit var menu: Menu
protected lateinit var searchView: SearchView
/**
* Action Mode
*/
protected var actionMode: ActionMode? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
/**
* Configure view components
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
recyclerView = view.getViewById(R.id.recycler_view)
configureRecyclerView()
refreshLayout = view.getViewById(R.id.refresh_layout)
configureRefreshLayout()
sortModeHolder = view.getViewById(R.id.sort_mode_holder)
configureSortModeHolder()
emptyView = view.getViewById(R.id.empty_view)
configureEmptyView()
}
override fun onStart() {
super.onStart()
EventBus.register(adapter)
}
override fun onStop() {
EventBus.unregister(adapter)
super.onStop()
}
/**
* Initialize menu variable and configure SearchView.
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
this.menu = menu
activity.menuInflater.inflate(getMenuResource(), menu)
val itemSearch = menu.findItem(R.id.action_search)
searchView = itemSearch.actionView as SearchView
searchView.setIconifiedByDefault(false)
searchView.setOnQueryTextListener(this)
}
/**
* Must return resource of menu that would be inflated
*/
@MenuRes
protected abstract fun getMenuResource(): Int
/**
* Dispatches select event of menu items that are common for any subclass
*/
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_sort -> {
startSortMode()
true
}
R.id.action_sort_done -> {
commitSortMode()
true
}
else -> false
}
/**
* Callback that notify about switching checked state of audio.
* Start ActionMode if set of checked audios not empty.
* If set of checked audios becomes empty ActionMode would be closed.
*/
override fun onChanged(audio: Audio, checked: HashSet<out Audio>) {
if (actionMode == null && checked.size > 0) {
actionMode = activity.startActionMode(this)
}
actionMode?.apply {
if (checked.isEmpty()) {
finish()
return
}
title = checked.size.toString()
}
}
/**
* Do nothing. Search process invokes by onQueryTextChange
*/
override fun onQueryTextSubmit(query: String) = false
/**
* Notify adapter about search query.
* All search logic should be provided by adapter.
*/
override fun onQueryTextChange(query: String): Boolean {
adapter.setSearchQuery(query)
return true
}
@MenuRes
protected abstract fun getActionModeMenuResource(): Int
/**
* Creates ActionMode and assign it to variable
*/
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
actionMode = mode
mode.menuInflater.inflate(getActionModeMenuResource(), menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
/**
* Dispatches select event of ActionMode menu items that are common for any subclasses.
* In the end finish ActionMode.
*/
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_play -> {
val audios = adapter.checkedAudios.toList()
Player.play(audios, audios[0])
}
R.id.action_play_next -> {
val audios = adapter.checkedAudios.toList()
Player.addToPlayNext(audios)
}
R.id.action_delete -> {
adapter.removeChecked()
}
R.id.action_add_to_queue -> {
Player.addToQueue(adapter.checkedAudios)
}
}
mode.finish()
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
adapter.clearChecked()
actionMode = null
}
override fun onBackPressed(): Boolean {
if (adapter.isSortMode()) {
revertSortMode()
return true
} else {
return false
}
}
private fun configureRecyclerView() {
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.itemAnimator = DefaultItemAnimator()
}
private fun configureRefreshLayout() {
refreshLayout.setColorSchemeResources(R.color.accent, R.color.primary)
refreshLayout.setOnRefreshListener {
actionMode?.finish()
if (adapter.isSortMode()) {
commitSortMode()
}
onRefresh()
}
}
open protected fun onRefresh() {
}
private fun configureSortModeHolder() {
sortModeHolder.apply {
findViewById(R.id.sort_by_title).setOnClickListener {
adapter.sort(Comparators.TITLE_COMPARATOR.
to(Comparators.TITLE_REVERSE_COMPARATOR))
}
findViewById(R.id.sort_by_artist).setOnClickListener {
adapter.sort(Comparators.ARTIST_COMPARATOR
.to(Comparators.ARTIST_REVERSE_COMPARATOR))
}
findViewById(R.id.sort_by_length).setOnClickListener {
adapter.sort(Comparators.LENGTH_COMPARATOR
.to(Comparators.LENGTH_REVERSE_COMPARATOR))
}
}
}
open protected fun configureEmptyView() {
}
private fun startSortMode() {
adapter.startSortMode()
configureStartSortMode()
}
private fun commitSortMode() {
adapter.commitSortMode()
configureFinishSortMode()
}
private fun revertSortMode() {
adapter.revertSortMode()
configureFinishSortMode()
}
private fun configureStartSortMode() {
activity.apply {
if (this is PlayerController.VisibilityController) {
hidePlayerController()
}
}
sortModeHolder.slideInUp()
menu.findItem(R.id.action_sort).isVisible = false
menu.findItem(R.id.action_sort_done).isVisible = true
}
private fun configureFinishSortMode() {
activity.apply {
if (Player.isReady && this is PlayerController.VisibilityController) {
showPlayerController()
}
}
sortModeHolder.slideOutDown()
menu.findItem(R.id.action_sort).isVisible = true
menu.findItem(R.id.action_sort_done).isVisible = false
}
} | apache-2.0 | 2e6a3196d83c2b91c480b0372a60489f | 24.163462 | 97 | 0.73758 | 3.842389 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | wordpress-comments/src/main/java/org/wordpress/aztec/plugins/wpcomments/toolbar/PageToolbarButton.kt | 1 | 2661 | package org.wordpress.aztec.plugins.wpcomments.toolbar
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ToggleButton
import androidx.appcompat.content.res.AppCompatResources
import org.wordpress.aztec.AztecText
import org.wordpress.aztec.Constants
import org.wordpress.aztec.plugins.IToolbarButton
import org.wordpress.aztec.plugins.wpcomments.R
import org.wordpress.aztec.plugins.wpcomments.spans.WordPressCommentSpan
import org.wordpress.aztec.spans.IAztecNestable
import org.wordpress.aztec.toolbar.AztecToolbar
import org.wordpress.aztec.toolbar.IToolbarAction
import org.wordpress.aztec.util.convertToButtonAccessibilityProperties
class PageToolbarButton(val visualEditor: AztecText) : IToolbarButton {
override val action: IToolbarAction = CommentsToolbarAction.PAGE
override val context = visualEditor.context!!
override fun toggle() {
visualEditor.removeInlineStylesFromRange(visualEditor.selectionStart, visualEditor.selectionEnd)
visualEditor.removeBlockStylesFromRange(visualEditor.selectionStart, visualEditor.selectionEnd, true)
val nestingLevel = IAztecNestable.getNestingLevelAt(visualEditor.editableText, visualEditor.selectionStart)
val span = WordPressCommentSpan(
WordPressCommentSpan.Comment.PAGE.html,
visualEditor.context,
AppCompatResources.getDrawable(visualEditor.context, R.drawable.img_page)!!,
nestingLevel,
visualEditor
)
val ssb = SpannableStringBuilder(Constants.MAGIC_STRING)
ssb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
val start = visualEditor.selectionStart
visualEditor.editableText.replace(start, visualEditor.selectionEnd, ssb)
val newSelectionPosition = visualEditor.editableText.indexOf(Constants.MAGIC_CHAR, start) + 1
visualEditor.setSelection(newSelectionPosition)
}
override fun matchesKeyShortcut(keyCode: Int, event: KeyEvent): Boolean {
return keyCode == KeyEvent.KEYCODE_P && event.isAltPressed && event.isCtrlPressed // Read More = Alt + Ctrl + P
}
override fun inflateButton(parent: ViewGroup) {
val rootView = LayoutInflater.from(context).inflate(R.layout.page_button, parent)
val button = rootView.findViewById<ToggleButton>(R.id.format_bar_button_page)
button.convertToButtonAccessibilityProperties()
}
override fun toolbarStateAboutToChange(toolbar: AztecToolbar, enable: Boolean) {
// no op
}
}
| mpl-2.0 | f149f045d630d7593b0ad38add6a34f1 | 41.919355 | 119 | 0.763998 | 4.718085 | false | false | false | false |
JackWHLiu/jackknife | bugskiller/src/main/java/com/lwh/jackknife/crash/policy/StoragePolicy.kt | 1 | 2460 | package com.lwh.jackknife.crash.policy
import android.annotation.TargetApi
import android.os.Build
import android.os.Environment
import android.util.Log
import com.lwh.jackknife.crash.group.CrashGroup
import com.lwh.jackknife.crash.CrashInfo
import com.lwh.jackknife.crash.group.DefaultCrashGroup
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
/**
* Save crash log information to SD card, please apply for storage permission by yourself.
* 把崩溃日志信息保存到SD卡,请自行申请存储权限。
*/
class StoragePolicy : CrashReportPolicy {
/**
* 由于Android11的机制,该方案被淘汰。
*/
@Deprecated("使用path替代")
private var folderName = ""//手机系统根目录保存日志文件夹的名称
private var path = ""
constructor(folderName: String = "jackknife", group: CrashGroup = DefaultCrashGroup(),
policy: CrashReportPolicy? = null) : super(
group,
policy
) {
this.folderName = folderName
}
constructor(folderName: String = "jackknife",
path: String = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).absolutePath}/${folderName}",
group: CrashGroup = DefaultCrashGroup(),
policy: CrashReportPolicy? = null) : super(
group,
policy
) {
this.folderName = folderName
this.path = path
}
override fun report(info: CrashInfo, group: CrashGroup) {
super.report(info, group)
try {
if (group.matches()) {
val simpleDateFormat = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss")
val time = simpleDateFormat.format(Date())
val folder = File(path)
folder.mkdirs()
val file = File(folder.absolutePath, "crash$time.txt")
if (!file.exists()) {
file.createNewFile()
}
val buffer = info.toString().trim { it <= ' ' }.toByteArray()
val fileOutputStream = FileOutputStream(file)
fileOutputStream.write(buffer, 0, buffer.size)
fileOutputStream.flush()
fileOutputStream.close()
}
} catch (e: IOException) {
Log.e("jackknife", "崩溃日志信息存储失败,$e")
}
}
} | gpl-3.0 | 4e27f0b0137a070a14969b0dde58d940 | 31.774648 | 142 | 0.615649 | 4.236794 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/explosm/src/eu/kanade/tachiyomi/extension/en/explosm/Explosm.kt | 1 | 4177 | package eu.kanade.tachiyomi.extension.en.explosm
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.text.SimpleDateFormat
import java.util.Locale
class Explosm : HttpSource() {
override val name = "Cyanide & Happiness"
override val baseUrl = "https://explosm.net"
override val lang = "en"
override val supportsLatest = false
override val client: OkHttpClient = network.cloudflareClient
private fun createManga(element: Element): SManga {
return SManga.create().apply {
initialized = true
title = "C&H ${element.attr("id").substringAfter("panel")}" // year
setUrlWithoutDomain(element.select("li a").first().attr("href")) // January
thumbnail_url = "https://vhx.imgix.net/vitalyuncensored/assets/13ea3806-5ebf-4987-bcf1-82af2b689f77/S2E4_Still1.jpg"
}
}
// Popular
override fun popularMangaRequest(page: Int): Request {
return (GET("$baseUrl/comics/archive", headers))
}
override fun popularMangaParse(response: Response): MangasPage {
val eachYearAsAManga = response.asJsoup().select("dd.accordion-navigation > div").map { createManga(it) }
return MangasPage(eachYearAsAManga, false)
}
// Latest
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used")
override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used")
// Search
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> = Observable.just(MangasPage(emptyList(), false))
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException("Not used")
override fun searchMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used")
// Details
override fun mangaDetailsParse(response: Response): SManga {
return createManga(response.asJsoup().select("div.content.active").first())
}
// Chapters
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
val januaryChapters = document.chaptersFromDocument() // should be at bottom of final returned list
// get the rest of the year
val chapters = document.select("div.content.active li:not(.active) a").reversed().map {
client.newCall(GET(it.attr("abs:href"), headers)).execute().asJsoup().chaptersFromDocument()
}.flatten()
return chapters + januaryChapters
}
private fun Document.chaptersFromDocument(): List<SChapter> {
return this.select("div.inner-wrap > div.row div.row.collapse").map { element ->
SChapter.create().apply {
setUrlWithoutDomain(element.select("a").attr("href"))
element.select("div#comic-author").text().let { cName ->
name = cName
date_upload = SimpleDateFormat("yyyy.MM.dd", Locale.getDefault())
.parse(cName.substringBefore(" "))?.time ?: 0L
}
}
}
}
// Pages
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
return Observable.just(listOf(Page(0, baseUrl + chapter.url)))
}
override fun pageListParse(response: Response): List<Page> = throw UnsupportedOperationException("Not used")
override fun imageUrlParse(response: Response): String {
return response.asJsoup().select("div#comic-wrap img").attr("abs:src")
}
override fun getFilterList() = FilterList()
}
| apache-2.0 | 700ee9487199ce778f5e6351c70a4ab1 | 35.640351 | 154 | 0.691166 | 4.501078 | false | false | false | false |
inorichi/tachiyomi-extensions | src/pt/opex/src/eu/kanade/tachiyomi/extension/pt/opex/OnePieceEx.kt | 1 | 10164 | package eu.kanade.tachiyomi.extension.pt.opex
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.util.Locale
import java.util.concurrent.TimeUnit
class OnePieceEx : ParsedHttpSource() {
override val name = "One Piece Ex"
override val baseUrl = "https://onepieceex.net"
override val lang = "pt-BR"
override val supportsLatest = false
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS))
.build()
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add("Accept", ACCEPT)
.add("Accept-Language", ACCEPT_LANGUAGE)
.add("Referer", "$baseUrl/mangas")
private val json: Json by injectLazy()
override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/mangas", headers)
override fun popularMangaParse(response: Response): MangasPage {
val mangaPage = super.popularMangaParse(response)
val mainManga = SManga.create().apply {
title = "One Piece"
thumbnail_url = MAIN_SERIES_THUMBNAIL
url = "/mangas/?type=main"
}
val sbsManga = SManga.create().apply {
title = "SBS"
thumbnail_url = DEFAULT_THUMBNAIL
url = "/mangas/?type=sbs"
}
val allMangas = listOf(mainManga, sbsManga) + mangaPage.mangas.toMutableList()
return MangasPage(allMangas, mangaPage.hasNextPage)
}
override fun popularMangaSelector(): String = "#post > div.volume"
override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply {
title = element.select("div.volume-nome h2").text() + " - " +
element.select("div.volume-nome h3").text()
thumbnail_url = THUMBNAIL_URL_MAP[title.toUpperCase(Locale.ROOT)] ?: DEFAULT_THUMBNAIL
val customUrl = "$baseUrl/mangas/".toHttpUrlOrNull()!!.newBuilder()
.addQueryParameter("type", "special")
.addQueryParameter("title", title)
.toString()
setUrlWithoutDomain(customUrl)
}
override fun popularMangaNextPageSelector(): String? = null
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return super.fetchSearchManga(page, query, filters)
.map { mangaPage ->
val filteredMangas = mangaPage.mangas.filter { m -> m.title.contains(query, true) }
MangasPage(filteredMangas, mangaPage.hasNextPage)
}
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = popularMangaRequest(page)
override fun searchMangaParse(response: Response): MangasPage = popularMangaParse(response)
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun searchMangaNextPageSelector(): String? = null
override fun mangaDetailsRequest(manga: SManga): Request {
val newHeaders = headersBuilder()
.set("Referer", "$baseUrl/")
.build()
return GET(baseUrl + manga.url, newHeaders)
}
override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply {
val mangaUrl = document.location().toHttpUrlOrNull()!!
when (mangaUrl.queryParameter("type")!!) {
"main" -> {
title = "One Piece"
author = "Eiichiro Oda"
genre = "Ação, Aventura, Comédia, Fantasia, Superpoderes"
status = SManga.ONGOING
description = "Um romance marítimo pelo \"One Piece\"!!! Estamos na Grande " +
"Era dos Piratas. Nela, muitos piratas lutam pelo tesouro deixado pelo " +
"lendário Rei dos Piratas G. Roger, o \"One Piece\". Luffy, um garoto " +
"que almeja ser pirata, embarca numa jornada com o sonho de se tornar " +
"o Rei dos Piratas!!! (Fonte: MANGA Plus)"
thumbnail_url = MAIN_SERIES_THUMBNAIL
}
"sbs" -> {
title = "SBS"
author = "Eiichiro Oda"
description = "O SBS é uma coluna especial encontrada na maioria dos " +
"tankobons da coleção, começando a partir do volume 4. É geralmente " +
"formatada como uma coluna direta de perguntas e respostas, com o " +
"Eiichiro Oda respondendo as cartas de fãs sobre uma grande variedade " +
"de assuntos. (Fonte: One Piece Wiki)"
thumbnail_url = DEFAULT_THUMBNAIL
}
"special" -> {
title = mangaUrl.queryParameter("title")!!
val volumeEl = document.select("#post > div.volume:contains(" + title.substringAfter(" - ") + ")").first()!!
author = if (title.contains("One Piece")) "Eiichiro Oda" else "OPEX"
description = volumeEl.select("li.resenha").text()
thumbnail_url = THUMBNAIL_URL_MAP[title.toUpperCase(Locale.ROOT)] ?: DEFAULT_THUMBNAIL
}
}
}
override fun chapterListRequest(manga: SManga): Request = mangaDetailsRequest(manga)
override fun chapterListParse(response: Response): List<SChapter> {
val mangaUrl = response.request.url
val mangaType = mangaUrl.queryParameter("type")!!
val selectorComplement = when (mangaType) {
"main" -> "#volumes"
"sbs" -> "#volumes div.volume header:contains(SBS)"
else -> "#post > div.volume:contains(" + mangaUrl.queryParameter("title")!!.substringAfter(" - ") + ")"
}
val chapterListSelector = selectorComplement + (if (mangaType == "sbs") "" else " " + chapterListSelector())
return response.asJsoup()
.select(chapterListSelector)
.map(::chapterFromElement)
.reversed()
}
override fun chapterListSelector() = "div.capitulos li.volume-capitulo"
override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply {
val mangaUrl = element.ownerDocument().location().toHttpUrlOrNull()!!
when (mangaUrl.queryParameter("type")!!) {
"main" -> {
name = element.select("span").first()!!.text()
setUrlWithoutDomain(element.select("a.online").first()!!.attr("abs:href"))
}
"sbs" -> {
name = element.select("div.volume-nome h2").first()!!.text()
setUrlWithoutDomain(element.select("header p.extra a:contains(SBS)").first()!!.attr("abs:href"))
}
"special" -> {
name = element.ownText()
setUrlWithoutDomain(element.select("a.online").first()!!.attr("abs:href"))
}
}
scanlator = [email protected]
}
override fun pageListParse(document: Document): List<Page> {
return document.select("script:containsData(paginasLista)").first()!!
.data()
.substringAfter("paginasLista = ")
.substringBefore(";")
.let { json.parseToJsonElement(it).jsonPrimitive.content }
.let { json.parseToJsonElement(it).jsonObject.entries }
.mapIndexed { i, entry ->
Page(i, document.location(), "$baseUrl/${entry.value.jsonPrimitive.content}")
}
}
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
val newHeaders = headersBuilder()
.set("Accept", ACCEPT_IMAGE)
.set("Referer", page.url)
.build()
return GET(page.imageUrl!!, newHeaders)
}
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used")
override fun latestUpdatesSelector() = throw UnsupportedOperationException("Not used")
override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used")
override fun latestUpdatesNextPageSelector() = throw UnsupportedOperationException("Not used")
companion object {
private const val ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9," +
"image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
private const val ACCEPT_IMAGE = "image/webp,image/apng,image/*,*/*;q=0.8"
private const val ACCEPT_LANGUAGE = "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6,gl;q=0.5"
private const val DEFAULT_THUMBNAIL = "https://onepieceex.net/mangareader/sbs/capa/preview/nao.jpg"
private const val MAIN_SERIES_THUMBNAIL = "https://onepieceex.net/mangareader/sbs/capa/preview/Volume_1.jpg"
private val THUMBNAIL_URL_MAP = mapOf(
"OPEX - DENSETSU NO SEKAI" to "https://onepieceex.net/mangareader/especiais/501/00.jpg",
"OPEX - ESPECIAIS" to "https://onepieceex.net/mangareader/especiais/27/00.jpg",
"ONE PIECE - ESPECIAIS DE ONE PIECE" to "https://onepieceex.net/mangareader/especiais/5/002.png",
"ONE PIECE - HISTÓRIAS DE CAPA" to "https://onepieceex.net/mangareader/mangas/428/00_c.jpg"
)
}
}
| apache-2.0 | e48bc320cf0ed8f65f7a791603c0dab3 | 41.476987 | 124 | 0.638495 | 4.281738 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/notifications/NotificationScheduler.kt | 1 | 8650 | package de.tum.`in`.tumcampusapp.component.notifications
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import de.tum.`in`.tumcampusapp.component.notifications.model.AppNotification
import de.tum.`in`.tumcampusapp.component.notifications.model.FutureNotification
import de.tum.`in`.tumcampusapp.component.notifications.model.InstantNotification
import de.tum.`in`.tumcampusapp.component.notifications.model.NotificationStore
import de.tum.`in`.tumcampusapp.component.notifications.persistence.ActiveAlarm
import de.tum.`in`.tumcampusapp.component.notifications.persistence.NotificationType
import de.tum.`in`.tumcampusapp.component.notifications.receivers.NotificationAlarmReceiver
import de.tum.`in`.tumcampusapp.component.notifications.receivers.NotificationReceiver
import de.tum.`in`.tumcampusapp.database.TcaDb
import de.tum.`in`.tumcampusapp.utils.Const
import org.jetbrains.anko.alarmManager
import org.jetbrains.anko.notificationManager
import org.joda.time.DateTime
import javax.inject.Inject
/**
* This class is responsible for scheduling notifications. This can either be a concrete notification
* or a potential notification, for instance scheduling an alarm 30 minutes before the end of a
* lecture to check for departures at nearby transit stops.
*
* @param context The used [Context]
*/
class NotificationScheduler @Inject constructor(private val context: Context) {
private val notificationManager = context.notificationManager
/**
* Schedules a list of [FutureNotification]s for the time specified by each notification.
*
* @param futureNotifications The list of [FutureNotification]s to schedule
*/
fun schedule(futureNotifications: List<FutureNotification>) {
futureNotifications
// Prevent excessive alarm scheduling
// Clients should be responsible enough to not exceed that amount
.take(maxRemainingAlarms(context))
.forEach { schedule(it) }
}
/**
* Schedules an [AppNotification]. Depending on the concrete class ([InstantNotification] or
* [FutureNotification]), it either directly displays the notification via [NotificationPresenter]
* or schedules it for later.
*
* @param notification The [AppNotification] to schedule
*/
fun schedule(notification: AppNotification) {
when (notification) {
is FutureNotification -> schedule(notification)
is InstantNotification -> NotificationPresenter.show(context, notification)
}
}
/**
* Schedules a [FutureNotification]. To prevent duplicates, it first gets any previous versions
* of this notification via [NotificationStore] and cancels them. Then, it schedules the new
* notification.
*
* @param notification The [FutureNotification] to schedule
*/
fun schedule(notification: FutureNotification) {
val persistentStore = NotificationStore.getInstance(context)
val scheduledNotification = persistentStore.find(notification)
scheduledNotification?.let {
// A notification for the same content has been scheduled before. We cancel the previous
// notification to prevent duplicates.
cancel(it.id, notification)
notificationManager.cancel(it.id.toInt())
}
val globalNotificationId = persistentStore.save(notification)
scheduleAlarm(notification, globalNotificationId)
}
/**
* Cancels a previously scheduled notification alarm. It uses the provided global notification
* ID and [FutureNotification] to re-create the [PendingIntent] and then uses it to cancel the
* alarm with the [AlarmManager].
*
* @param globalId The global ID of the notification as retrieved from [NotificationStore]
* @param notification The [FutureNotification] that is to be canceled
*/
fun cancel(globalId: Long, notification: FutureNotification) {
val pendingIntent = getAlarmIntent(notification, globalId)
pendingIntent.cancel()
context.alarmManager.cancel(pendingIntent)
}
/**
* Schedules alarms for a [NotificationType] at a number of [DateTime]s.
*
* @param type The [NotificationType] of the alarm
* @param times The [DateTime]s at which to alarm the [NotificationAlarmReceiver]
*/
fun scheduleAlarms(type: NotificationType, times: List<DateTime>) {
times.forEach { scheduleAlarm(type, it) }
}
/**
* Schedules an alarm for a [NotificationType] at a specific [DateTime]. At the time of the
* alarm, the [NotificationAlarmReceiver] will invoke the [NotificationProvider] to the
* [NotificationType] and allow it to display a notification.
*
* This is used for scheduling alarm for tuition fees and MVV departures. In case of the latter,
* we specify an alarm at the end of each lecture. In the TransportNotificationsProvider,
* we check whether or not this is the last lecture of the day. If so, we load departures at the
* nearest station and display them to the user.
*
* @param type The [NotificationType] of the alarm
* @param time The [DateTime] at which to alarm the [NotificationAlarmReceiver]
*/
fun scheduleAlarm(type: NotificationType, time: DateTime) {
val alarmIntent = getAlarmIntent(type)
val alarmManager = context.alarmManager
// If the same alarm has already been scheduled, we cancel it.
alarmIntent.cancel()
alarmManager.cancel(alarmIntent)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time.millis, alarmIntent)
}
/**
* Schedules a [FutureNotification] with the provided global notification ID.
*
* @param notification The [FutureNotification] to schedule
* @param globalId The notification's global ID in [NotificationStore] used for scheduling
*/
private fun scheduleAlarm(notification: FutureNotification, globalId: Long) {
val alarmIntent = getAlarmIntent(notification, globalId)
val alarmManager = context.alarmManager
alarmManager.setExact(AlarmManager.RTC_WAKEUP, notification.time.millis, alarmIntent)
addActiveAlarm(context, globalId)
}
/**
* Returns a [PendingIntent] that contains the [FutureNotification]'s ID and
* notification content.
*
* @param futureNotification The [FutureNotification] to schedule
* @param globalNotificationId The notification's global ID in [NotificationStore] used for scheduling
* @return The [PendingIntent] used for scheduling the notification
*/
private fun getAlarmIntent(
futureNotification: FutureNotification,
globalNotificationId: Long
): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
putExtra(Const.KEY_NOTIFICATION_ID, globalNotificationId.toInt())
putExtra(Const.KEY_NOTIFICATION, futureNotification.notification)
}
return PendingIntent.getBroadcast(context,
futureNotification.id, intent, PendingIntent.FLAG_CANCEL_CURRENT)
}
/**
* Returns a [PendingIntent] that contains the [NotificationType]'s ID. When the alarm goes off,
* the [NotificationType]'s associated [NotificationProvider] gets the opportunity to display
* a notification.
*
* @param type The [NotificationType] for which to schedule the alarm
* @return The [PendingIntent] used for scheduling the notification
*/
private fun getAlarmIntent(type: NotificationType): PendingIntent {
val intent = Intent(context, NotificationAlarmReceiver::class.java).apply {
putExtra(Const.KEY_NOTIFICATION_TYPE_ID, type.id)
}
return PendingIntent.getBroadcast(context, type.id, intent, PendingIntent.FLAG_CANCEL_CURRENT)
}
companion object {
private fun addActiveAlarm(context: Context, id: Long) {
TcaDb.getInstance(context)
.activeNotificationsDao()
.addActiveAlarm(ActiveAlarm(id))
}
fun removeActiveAlarm(context: Context, id: Long) {
TcaDb.getInstance(context)
.activeNotificationsDao()
.deleteActiveAlarm(ActiveAlarm(id))
}
@JvmStatic
fun maxRemainingAlarms(context: Context): Int {
return TcaDb.getInstance(context)
.activeNotificationsDao()
.maxAlarmsToSchedule()
}
}
} | gpl-3.0 | 719fd8cb1bd12ceae6fe15dd33d48713 | 42.913706 | 106 | 0.704971 | 5.014493 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/format/ProgressHandler.kt | 2 | 4352 | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
package assimp.format
import glm_.f
// ------------------------------------------------------------------------------------
/** @brief CPP-API: Abstract interface for custom progress report receivers.
*
* Each Importer instance maintains its own ProgressHandler. The default implementation provided by Assimp
* doesn't do anything at all. */
interface ProgressHandler {
// -------------------------------------------------------------------
/** @brief Progress callback.
* @param percentage An estimate of the current loading progress, in percent. Or -1f if such an estimate is not
* available.
*
* There are restriction on what you may do from within your implementation of this method: no exceptions may be
* thrown and no non-const Importer methods may be called. It is not generally possible to predict the number of
* callbacks fired during a single import.
*
* @return Return false to abort loading at the next possible occasion (loaders and Assimp are generally allowed to
* perform all needed cleanup tasks prior to returning control to the caller). If the loading is aborted,
* Importer.readFile() returns always null. */
fun update(percentage: Float = -1f): Boolean
// -------------------------------------------------------------------
/** @brief Progress callback for file loading steps
* @param numberOfSteps The number of total post-processing steps
* @param currentStep The index of the current post-processing step that will run, or equal to numberOfSteps if all
* of them has finished. This number is always strictly monotone increasing, although not necessarily linearly.
*
* @note This is currently only used at the start and the end of the file parsing. */
fun updateFileRead(currentStep: Int /*= 0*/, numberOfSteps: Int /*= 0*/) {
val f = if (numberOfSteps != 0) currentStep / numberOfSteps.f else 1f
update(f * 0.5f)
}
// -------------------------------------------------------------------
/** @brief Progress callback for post-processing steps
* @param numberOfSteps The number of total post-processing steps
* @param currentStep The index of the current post-processing step that will run, or equal to numberOfSteps if all
* of them has finished. This number is always strictly monotone increasing, although not necessarily linearly. */
fun updatePostProcess(currentStep: Int /*= 0*/, numberOfSteps: Int /*= 0*/) {
val f = if (numberOfSteps != 0) currentStep / numberOfSteps.f else 1f
update(f * 0.5f + 0.5f)
}
} | mit | cde190135786558058b99b1f45d08971 | 47.910112 | 122 | 0.66636 | 5.042874 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/debug/frame/VirtualFileStackFrame.kt | 1 | 2307 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.processor.debug.frame
import com.intellij.icons.AllIcons
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XStackFrame
import uk.co.reecedunn.intellij.plugin.processor.debug.position.QuerySourcePosition
class VirtualFileStackFrame(
file: VirtualFile,
line: Int = 0,
column: Int = 0,
val context: String? = null,
private val children: ComputeChildren? = null,
private val debuggerEvaluator: XDebuggerEvaluator? = null
) : XStackFrame() {
private val sourcePosition = QuerySourcePosition.create(file, line, column)
override fun getSourcePosition(): XSourcePosition? = sourcePosition
override fun customizePresentation(component: ColoredTextContainer) {
component.append(sourcePosition!!.file.name, SimpleTextAttributes.REGULAR_ATTRIBUTES)
component.append(":", SimpleTextAttributes.REGULAR_ATTRIBUTES)
component.append(sourcePosition.line.toString(), SimpleTextAttributes.REGULAR_ATTRIBUTES)
context?.let {
component.append(", ", SimpleTextAttributes.REGULAR_ATTRIBUTES)
component.append(it, SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES)
}
component.setIcon(AllIcons.Debugger.Frame)
}
override fun getEvaluator(): XDebuggerEvaluator? = debuggerEvaluator
override fun computeChildren(node: XCompositeNode) {
children?.computeChildren(node, evaluator)
}
}
| apache-2.0 | 23c68ff8c2bef62a2358e4f9c6038a8f | 38.101695 | 97 | 0.759861 | 4.717791 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/modal/ModalAnimator.kt | 1 | 7639 | package com.reactnativenavigation.viewcontrollers.modal
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.content.Context
import androidx.annotation.VisibleForTesting
import com.reactnativenavigation.options.FadeAnimation
import com.reactnativenavigation.options.StackAnimationOptions
import com.reactnativenavigation.options.TransitionAnimationOptions
import com.reactnativenavigation.options.params.Bool
import com.reactnativenavigation.utils.ScreenAnimationListener
import com.reactnativenavigation.utils.awaitRender
import com.reactnativenavigation.viewcontrollers.common.BaseAnimator
import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController
import com.reactnativenavigation.views.element.TransitionAnimatorCreator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*
open class ModalAnimator @JvmOverloads constructor(
context: Context,
private val transitionAnimatorCreator: TransitionAnimatorCreator = TransitionAnimatorCreator(),
private val defaultAnimation: StackAnimationOptions = FadeAnimation
) : BaseAnimator(context) {
val isRunning: Boolean
get() = runningAnimators.isNotEmpty()
@VisibleForTesting
internal val runningAnimators: MutableMap<ViewController<*>, AnimatorSet?> = HashMap()
open fun show(
appearing: ViewController<*>,
disappearing: ViewController<*>?,
animationOptions: TransitionAnimationOptions,
listener: ScreenAnimationListener
) {
val set = createShowModalAnimator(appearing, listener)
runningAnimators[appearing] = set
if (animationOptions.hasElementTransitions() && disappearing != null) {
showModalWithElementTransition(appearing, disappearing, animationOptions, set)
} else {
showModalWithoutElementTransition(appearing, disappearing, animationOptions, set)
}
}
private fun showModalWithElementTransition(appearing: ViewController<*>, disappearing: ViewController<*>, animationOptions: TransitionAnimationOptions, set: AnimatorSet) {
GlobalScope.launch(Dispatchers.Main.immediate) {
appearing.setWaitForRender(Bool(true))
appearing.view.alpha = 0f
appearing.awaitRender()
val appearingFade = if (animationOptions.enter.isFadeAnimation()) animationOptions.enter else defaultAnimation.content.enter
val transitionAnimators = transitionAnimatorCreator.create(animationOptions, appearingFade, disappearing, appearing)
set.playTogether(appearingFade.getAnimation(appearing.view), transitionAnimators)
transitionAnimators.listeners.forEach { animatorListener: Animator.AnimatorListener -> set.addListener(animatorListener) }
transitionAnimators.removeAllListeners()
set.start()
}
}
private fun showModalWithoutElementTransition(appearing: ViewController<*>, disappearing: ViewController<*>?, animationOptions: TransitionAnimationOptions, set: AnimatorSet) {
GlobalScope.launch(Dispatchers.Main.immediate) {
val appearingAnimation = if (animationOptions.enter.hasValue()) {
animationOptions.enter.getAnimation(appearing.view)
} else getDefaultPushAnimation(appearing.view)
val disappearingAnimation = if (disappearing != null && animationOptions.exit.hasValue()) {
animationOptions.exit.getAnimation(disappearing.view)
} else null
disappearingAnimation?.let {
set.playTogether(appearingAnimation, disappearingAnimation)
} ?: set.playTogether(appearingAnimation)
set.start()
}
}
open fun dismiss(appearing: ViewController<*>?, disappearing: ViewController<*>, animationOptions: TransitionAnimationOptions, listener: ScreenAnimationListener) {
GlobalScope.launch(Dispatchers.Main.immediate) {
if (runningAnimators.containsKey(disappearing)) {
runningAnimators[disappearing]?.cancel()
listener.onEnd()
} else {
val set = createDismissAnimator(disappearing, listener)
if (animationOptions.hasElementTransitions() && appearing != null) {
setupDismissAnimationWithSharedElementTransition(disappearing, appearing, animationOptions, set)
} else {
val appearingAnimation = if (appearing != null && animationOptions.enter.hasValue()) {
animationOptions.enter.getAnimation(appearing.view)
} else null
val disappearingAnimation = if (animationOptions.exit.hasValue()) {
animationOptions.exit.getAnimation(disappearing.view)
} else getDefaultPopAnimation(disappearing.view)
appearingAnimation?.let {
set.playTogether(appearingAnimation, disappearingAnimation)
} ?: set.playTogether(disappearingAnimation)
}
set.start()
}
}
}
private fun createShowModalAnimator(appearing: ViewController<*>, listener: ScreenAnimationListener): AnimatorSet {
val set = AnimatorSet()
set.addListener(object : AnimatorListenerAdapter() {
private var isCancelled = false
override fun onAnimationStart(animation: Animator) {
listener.onStart()
}
override fun onAnimationCancel(animation: Animator) {
isCancelled = true
runningAnimators.remove(appearing)
listener.onCancel()
}
override fun onAnimationEnd(animation: Animator) {
runningAnimators.remove(appearing)
if (!isCancelled) listener.onEnd()
}
})
return set
}
private fun createDismissAnimator(disappearing: ViewController<*>, listener: ScreenAnimationListener): AnimatorSet {
val set = AnimatorSet()
set.addListener(object : AnimatorListenerAdapter() {
private var isCancelled = false
override fun onAnimationStart(animation: Animator) {
listener.onStart()
}
override fun onAnimationCancel(animation: Animator) {
isCancelled = true
runningAnimators.remove(disappearing)
listener.onCancel()
}
override fun onAnimationEnd(animation: Animator) {
runningAnimators.remove(disappearing)
if (!isCancelled) listener.onEnd()
}
})
return set
}
private suspend fun setupDismissAnimationWithSharedElementTransition(
disappearing: ViewController<*>,
appearing: ViewController<*>,
animationOptions: TransitionAnimationOptions,
set: AnimatorSet
) {
val disappearFade = if (animationOptions.exit.isFadeAnimation()) animationOptions.exit else defaultAnimation.content.exit
val transitionAnimators = transitionAnimatorCreator.create(animationOptions, disappearFade, disappearing, appearing)
set.playTogether(disappearFade.getAnimation(disappearing.view), transitionAnimators)
transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) }
transitionAnimators.removeAllListeners()
}
}
| mit | e6bb66050869d34c1f83bab2b9c7a46d | 46.74375 | 179 | 0.685299 | 6.096568 | false | false | false | false |
pnemonic78/Electric-Fields | electric-android/app/src/main/kotlin/com/github/fields/electric/wallpaper/ElectricFieldsWallpaperService.kt | 1 | 5685 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.fields.electric.wallpaper
import android.content.Context
import android.service.wallpaper.WallpaperService
import android.text.format.DateUtils
import android.view.MotionEvent
import android.view.SurfaceHolder
import com.github.fields.electric.Charge
import com.github.fields.electric.ElectricFields
import com.github.fields.electric.ElectricFieldsView.Companion.MAX_CHARGES
import com.github.fields.electric.ElectricFieldsView.Companion.MIN_CHARGES
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.random.Random
/**
* Electric Fields wallpaper service.
*
* @author Moshe Waisberg
*/
class ElectricFieldsWallpaperService : WallpaperService() {
override fun onCreateEngine(): WallpaperService.Engine {
return ElectricFieldsWallpaperEngine()
}
/**
* Electric Fields wallpaper engine.
* @author Moshe Waisberg
*/
private inner class ElectricFieldsWallpaperEngine : WallpaperService.Engine(), WallpaperListener {
private lateinit var fieldsView: WallpaperView
private val random = Random.Default
private val isDrawing = AtomicBoolean()
override fun onCreate(surfaceHolder: SurfaceHolder) {
super.onCreate(surfaceHolder)
setTouchEventsEnabled(true)
val context: Context = this@ElectricFieldsWallpaperService
fieldsView = WallpaperView(context, this)
}
override fun onDestroy() {
super.onDestroy()
fieldsView.stop()
fieldsView.onDestroy()
}
override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
fieldsView.setSize(width, height)
randomise()
}
override fun onSurfaceDestroyed(holder: SurfaceHolder) {
fieldsView.stop()
fieldsView.onDestroy()
}
override fun onSurfaceRedrawNeeded(holder: SurfaceHolder) {
draw(fieldsView)
}
override fun onTouchEvent(event: MotionEvent) {
fieldsView.onTouchEvent(event)
}
override fun onVisibilityChanged(visible: Boolean) {
if (visible) {
fieldsView.start()
} else {
fieldsView.stop()
}
}
/**
* Add random charges.
* @param delay the start delay, in milliseconds.
*/
private fun randomise(delay: Long = 0L) {
val w = fieldsView.width
val h = fieldsView.height
val count = random.nextInt(MIN_CHARGES, MAX_CHARGES)
fieldsView.clear()
for (i in 0 until count) {
fieldsView.addCharge(random.nextInt(w), random.nextInt(h), random.nextDouble(-20.0, 20.0))
}
fieldsView.restart(delay)
}
override fun onChargeAdded(view: ElectricFields, charge: Charge) {}
override fun onChargeInverted(view: ElectricFields, charge: Charge) {}
override fun onChargeScaleBegin(view: ElectricFields, charge: Charge): Boolean {
return false
}
override fun onChargeScale(view: ElectricFields, charge: Charge): Boolean {
return false
}
override fun onChargeScaleEnd(view: ElectricFields, charge: Charge): Boolean {
return false
}
override fun onRenderFieldClicked(view: ElectricFields, x: Int, y: Int, size: Double): Boolean {
if (fieldsView.invertCharge(x, y) || fieldsView.addCharge(x, y, size)) {
fieldsView.restart()
return true
}
return false
}
override fun onRenderFieldStarted(view: ElectricFields) {}
override fun onRenderFieldFinished(view: ElectricFields) {
if (view === fieldsView) {
randomise(DELAY)
}
}
override fun onRenderFieldCancelled(view: ElectricFields) {}
override fun onDraw(view: WallpaperView) {
if (view === fieldsView) {
draw(view)
}
}
fun draw(view: WallpaperView) {
if (!isDrawing.compareAndSet(false, true)) {
return
}
val surfaceHolder = this.surfaceHolder
if (surfaceHolder.surface.isValid) {
try {
val canvas = surfaceHolder.lockCanvas()
if (canvas != null) {
try {
view.draw(canvas)
} finally {
surfaceHolder.unlockCanvasAndPost(canvas)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
isDrawing.set(false)
}
}
companion object {
/**
* Enough time for user to admire the wallpaper before starting the next rendition.
*/
private const val DELAY = 10L * DateUtils.SECOND_IN_MILLIS
}
}
| apache-2.0 | 04d03c3a074572b40214802825941770 | 31.485714 | 106 | 0.602287 | 4.863131 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt | 1 | 2900 | package info.nightscout.androidaps.plugins.general.automation.triggers
import android.widget.LinearLayout
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel
import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONObject
class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) {
var comparator = ComparatorExists(rh)
constructor(injector: HasAndroidInjector, compare: ComparatorExists.Compare) : this(injector) {
comparator = ComparatorExists(rh, compare)
}
constructor(injector: HasAndroidInjector, triggerTempTarget: TriggerTempTarget) : this(injector) {
comparator = ComparatorExists(rh, triggerTempTarget.comparator.value)
}
fun comparator(comparator: ComparatorExists.Compare): TriggerTempTarget {
this.comparator.value = comparator
return this
}
override fun shouldRun(): Boolean {
val tt = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tt is ValueWrapper.Absent && comparator.value == ComparatorExists.Compare.NOT_EXISTS) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true
}
if (tt is ValueWrapper.Existing && comparator.value == ComparatorExists.Compare.EXISTS) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true
}
aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription())
return false
}
override fun dataJSON(): JSONObject =
JSONObject()
.put("comparator", comparator.value.toString())
override fun fromJSON(data: String): Trigger {
val d = JSONObject(data)
comparator.value = ComparatorExists.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)
return this
}
override fun friendlyName(): Int = R.string.careportal_temporarytarget
override fun friendlyDescription(): String =
rh.gs(R.string.temptargetcompared, rh.gs(comparator.value.stringRes))
override fun icon(): Optional<Int> = Optional.of(R.drawable.ic_keyboard_tab)
override fun duplicate(): Trigger = TriggerTempTarget(injector, this)
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(StaticLabel(rh, R.string.careportal_temporarytarget, this))
.add(comparator)
.build(root)
}
} | agpl-3.0 | 3a94224f9ef16b8154f4cd6b8eb431ef | 39.859155 | 104 | 0.727586 | 4.777595 | false | false | false | false |
jgrandja/spring-security | config/src/test/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDslTests.kt | 2 | 17313 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.servlet
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic
import org.springframework.security.web.util.matcher.RegexRequestMatcher
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.put
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
/**
* Tests for [AuthorizeRequestsDsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class AuthorizeRequestsDslTests {
@JvmField
val spring = SpringTestContext(this)
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `request when secured by regex matcher then responds with forbidden`() {
this.spring.register(AuthorizeRequestsByRegexConfig::class.java).autowire()
this.mockMvc.get("/private")
.andExpect {
status { isForbidden() }
}
}
@Test
fun `request when allowed by regex matcher then responds with ok`() {
this.spring.register(AuthorizeRequestsByRegexConfig::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
}
@Test
fun `request when allowed by regex matcher with http method then responds based on method`() {
this.spring.register(AuthorizeRequestsByRegexConfig::class.java).autowire()
this.mockMvc.post("/onlyPostPermitted") { with(csrf()) }
.andExpect {
status { isOk() }
}
this.mockMvc.get("/onlyPostPermitted")
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
open class AuthorizeRequestsByRegexConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(RegexRequestMatcher("/path", null), permitAll)
authorize(RegexRequestMatcher("/onlyPostPermitted", "POST"), permitAll)
authorize(RegexRequestMatcher("/onlyPostPermitted", "GET"), denyAll)
authorize(RegexRequestMatcher(".*", null), authenticated)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
@RequestMapping("/onlyPostPermitted")
fun onlyPostPermitted() {
}
}
}
@Test
fun `request when secured by mvc then responds with forbidden`() {
this.spring.register(AuthorizeRequestsByMvcConfig::class.java).autowire()
this.mockMvc.get("/private")
.andExpect {
status { isForbidden() }
}
}
@Test
fun `request when allowed by mvc then responds with OK`() {
this.spring.register(AuthorizeRequestsByMvcConfig::class.java, LegacyMvcMatchingConfig::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/path.html")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/path/")
.andExpect {
status { isOk() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class AuthorizeRequestsByMvcConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/path", permitAll)
authorize("/**", authenticated)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Configuration
open class LegacyMvcMatchingConfig : WebMvcConfigurer {
override fun configurePathMatch(configurer: PathMatchConfigurer) {
configurer.setUseSuffixPatternMatch(true)
}
}
@Test
fun `request when secured by mvc path variables then responds based on path variable value`() {
this.spring.register(MvcMatcherPathVariablesConfig::class.java).autowire()
this.mockMvc.get("/user/user")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/user/deny")
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherPathVariablesConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/user/{userName}", "#userName == 'user'")
}
}
}
@RestController
internal class PathController {
@RequestMapping("/user/{user}")
fun path(@PathVariable user: String) {
}
}
}
@Test
fun `request when user has allowed role then responds with OK`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have allowed role then responds with forbidden`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasRoleConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/**", hasRole("ADMIN"))
}
httpBasic { }
}
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val adminDetails = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
return InMemoryUserDetailsManager(userDetails, adminDetails)
}
}
@Test
fun `request when user has some allowed roles then responds with OK`() {
this.spring.register(HasAnyRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isOk() }
}
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have any allowed roles then responds with forbidden`() {
this.spring.register(HasAnyRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("other", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAnyRoleConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/**", hasAnyRole("ADMIN", "USER"))
}
httpBasic { }
}
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val admin1Details = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
val admin2Details = User.withDefaultPasswordEncoder()
.username("other")
.password("password")
.roles("OTHER")
.build()
return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details)
}
}
@Test
fun `request when user has some allowed authorities then responds with OK`() {
this.spring.register(HasAnyAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isOk() }
}
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have any allowed authorities then responds with forbidden`() {
this.spring.register(HasAnyAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("other", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAnyAuthorityConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/**", hasAnyAuthority("ROLE_ADMIN", "ROLE_USER"))
}
httpBasic { }
}
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.authorities("ROLE_USER")
.build()
val admin1Details = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.authorities("ROLE_ADMIN")
.build()
val admin2Details = User.withDefaultPasswordEncoder()
.username("other")
.password("password")
.authorities("ROLE_OTHER")
.build()
return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details)
}
}
@Test
fun `request when secured by mvc with servlet path then responds based on servlet path`() {
this.spring.register(MvcMatcherServletPathConfig::class.java).autowire()
this.mockMvc.perform(MockMvcRequestBuilders.get("/spring/path")
.with { request ->
request.servletPath = "/spring"
request
})
.andExpect(status().isForbidden)
this.mockMvc.perform(MockMvcRequestBuilders.get("/other/path")
.with { request ->
request.servletPath = "/other"
request
})
.andExpect(status().isOk)
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherServletPathConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/path",
"/spring",
denyAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@EnableWebSecurity
@EnableWebMvc
open class AuthorizeRequestsByMvcConfigWithHttpMethod : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(HttpMethod.GET, "/path", permitAll)
authorize(HttpMethod.PUT, "/path", denyAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when secured by mvc with http method then responds based on http method`() {
this.spring.register(AuthorizeRequestsByMvcConfigWithHttpMethod::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
this.mockMvc.put("/path") { with(csrf()) }
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherServletPathHttpMethodConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(HttpMethod.GET, "/path", "/spring", denyAll)
authorize(HttpMethod.PUT, "/path", "/spring", denyAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when secured by mvc with servlet path and http method then responds based on path and method`() {
this.spring.register(MvcMatcherServletPathConfig::class.java).autowire()
this.mockMvc.perform(MockMvcRequestBuilders.get("/spring/path")
.with { request ->
request.apply {
servletPath = "/spring"
}
})
.andExpect(status().isForbidden)
this.mockMvc.perform(MockMvcRequestBuilders.put("/spring/path")
.with { request ->
request.apply {
servletPath = "/spring"
csrf()
}
})
.andExpect(status().isForbidden)
this.mockMvc.perform(MockMvcRequestBuilders.get("/other/path")
.with { request ->
request.apply {
servletPath = "/other"
}
})
.andExpect(status().isOk)
}
}
| apache-2.0 | 2687f456a6d0f786bb4c43b0e3f4ea2c | 31.482176 | 118 | 0.56911 | 5.557945 | false | true | false | false |
yuksanbo/cxf-rt-transports-http-ahc | src/test/kotlin/ru/yuksanbo/cxf/transportahc/AhcHttpConduitTest.kt | 1 | 4034 | package ru.yuksanbo.cxf.transportahc
import org.apache.cxf.BusFactory
import org.apache.cxf.continuations.ContinuationProvider
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase
import org.apache.hello_world_soap_http.Greeter
import org.apache.hello_world_soap_http.SOAPService
import org.apache.hello_world_soap_http.types.GreetMeResponse
import org.junit.AfterClass
import org.junit.Assert
import org.junit.BeforeClass
import org.junit.Test
import java.util.concurrent.ExecutionException
import javax.xml.ws.Endpoint
class AhcHttpConduitTest : AbstractBusClientServerTestBase() {
companion object {
val port = "1080" //allocatePort(AhcHttpConduitTest::class.java)
internal var ep: Endpoint? = null
lateinit var request: String
lateinit var g: Greeter
@BeforeClass
@Throws(Exception::class)
@JvmStatic
fun start() {
val b = AbstractBusClientServerTestBase.createStaticBus()
b.setProperty(AhcHttpConduit.Properties.Async, true)
BusFactory.setThreadDefaultBus(b)
ep = Endpoint.publish("http://localhost:$port/SoapContext/SoapPort",
object : org.apache.hello_world_soap_http.GreeterImpl() {
override fun greetMeLater(cnt: Long): String? {
//use the continuations so the async client can
//have a ton of connections, use less threads
//
//mimic a slow server by delaying somewhere between
//1 and 2 seconds, with a preference of delaying the earlier
//requests longer to create a sort of backlog/contention
//with the later requests
val p = context.messageContext[ContinuationProvider::class.java.name] as ContinuationProvider
val c = p.continuation
if (c.isNew) {
if (cnt < 0) {
c.suspend(-cnt)
} else {
c.suspend(2000 - cnt % 1000)
}
return null
}
return "Hello, finally! " + cnt
}
override fun greetMe(me: String?): String {
return "Hello " + me!!
}
})
val builder = StringBuilder("NaNaNa")
for (x in 0..49) {
builder.append(" NaNaNa ")
}
request = builder.toString()
val soapServiceWsdl = AhcHttpConduitTest::class.java.getResource("/wsdl/hello_world.wsdl")
Assert.assertNotNull("WSDL is null", soapServiceWsdl)
val service = SOAPService(soapServiceWsdl)
Assert.assertNotNull("Service is null", service)
g = service.soapPort
Assert.assertNotNull("Port is null", g)
}
@AfterClass
@Throws(Exception::class)
@JvmStatic
fun stop() {
(g as java.io.Closeable).close()
ep!!.stop()
ep = null
}
}
//todo: more tests
@Test
@Throws(Exception::class)
fun testCallAsync() {
updateAddressPort(g, port)
val resp = g.greetMeAsync(request) { res ->
try {
res.get().responseType
} catch (e: InterruptedException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: ExecutionException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}.get() as GreetMeResponse
Assert.assertEquals("Hello " + request, resp.responseType)
g.greetMeLaterAsync(1000) { }.get()
}
} | mit | 6bdd69b918b778b487ac101688249067 | 35.351351 | 121 | 0.534953 | 4.91352 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/CompilerWarningIntentionAction.kt | 2 | 1534 | // 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.highlighter
import com.intellij.codeInsight.intention.AbstractEmptyIntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInspection.util.IntentionFamilyName
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle
import javax.swing.Icon
class CompilerWarningIntentionAction(private val name: @IntentionFamilyName String): AbstractEmptyIntentionAction(), LowPriorityAction, Iconable {
override fun getText(): String = KotlinBaseFe10HighlightingBundle.message("kotlin.compiler.warning.0.options", name)
override fun getFamilyName(): String = name
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = true
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as CompilerWarningIntentionAction
return name == that.name
}
override fun hashCode(): Int = name.hashCode()
override fun getIcon(@Iconable.IconFlags flags: Int): Icon = AllIcons.Actions.RealIntentionBulb
}
| apache-2.0 | d96c0f9f3671abd5269d700e8c60e0c3 | 46.9375 | 158 | 0.784224 | 4.606607 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/android/labs/host/IntentHostAdapter.kt | 1 | 3425 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.sdk.android.labs.host
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ResultReceiver
import arcs.core.host.ArcHost
import arcs.core.host.ArcHostException
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeout
/**
* A stub that translates API calls into [Intent]s directed at a [Service] using
* [ArcHostHelper] to handle them.
*
* @property hostComponentName the [ComponentName] of the [Service]
* @property sender a callback used to fire the [Intent], overridable to allow testing.
*/
abstract class IntentHostAdapter(
protected val hostComponentName: ComponentName,
protected val sender: (Intent) -> Unit
) {
/**
* Asynchronously send a command via [Intent] without waiting for return result.
*/
protected fun sendIntentToHostService(intent: Intent) {
sender(intent)
}
@OptIn(ExperimentalCoroutinesApi::class)
class ResultReceiverContinuation<T>(
val continuation: CancellableContinuation<T?>,
val block: (Any?) -> T?
) : ResultReceiver(Handler(Looper.getMainLooper())) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
val exception = resultData?.getString(ArcHostHelper.EXTRA_OPERATION_EXCEPTION)
exception?.let {
continuation.cancel(
ArcHostException(
exception,
resultData.getString(ArcHostHelper.EXTRA_OPERATION_EXCEPTION_STACKTRACE, "")
)
)
} ?: run {
continuation.resume(
block(
resultData?.get(
ArcHostHelper.EXTRA_OPERATION_RESULT
)
),
onCancellation = {}
)
}
}
}
/**
* Sends an asynchronous [ArcHost] command via [Intent] to a [Service] and waits for a
* result using a suspendable coroutine.
*
* @property intent the [ArcHost] command, usually from [ArcHostHelper]
* @property transformer a lambda to map return values from a [Bundle] into other types.
*/
protected suspend fun <T> sendIntentToHostServiceForResult(
intent: Intent,
transformer: (Any?) -> T?
): T? = withTimeout(ARCHOST_INTENT_TIMEOUT_MS) {
suspendCancellableCoroutine { continuation: CancellableContinuation<T?> ->
ArcHostHelper.setResultReceiver(
intent,
ResultReceiverContinuation(continuation, transformer)
)
sendIntentToHostService(intent)
}
}
/**
* Sends an asynchronous [ArcHost] command via [Intent] and waits for it to complete
* with no return value.
*/
protected suspend fun sendIntentToHostServiceForResult(
intent: Intent
): Unit? = sendIntentToHostServiceForResult(intent) {}
companion object {
/**
* The maximum amount of time to wait for an [ArcHost] to process an [Intent]-based
* RPC call. This timeout ensures requests don't wait forever.
*/
const val ARCHOST_INTENT_TIMEOUT_MS = 5000L
}
}
| bsd-3-clause | b520462e5b0bc9baf561655cf793881d | 31.311321 | 96 | 0.703358 | 4.512516 | false | false | false | false |
android/renderscript-intrinsics-replacement-toolkit | test-app/src/main/java/com/google/android/renderscript_test/ReferenceYuvToRgb.kt | 1 | 4189 | /*
* Copyright (C) 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 com.google.android.renderscript_test
import com.google.android.renderscript.YuvFormat
import java.lang.IllegalArgumentException
/**
* Reference implementation of a YUV to RGB operation.
*/
@ExperimentalUnsignedTypes
fun referenceYuvToRgb(inputSignedArray: ByteArray, sizeX: Int, sizeY: Int, format: YuvFormat): ByteArray {
require(sizeX % 2 == 0) { "The width of the input should be even."}
val inputArray = inputSignedArray.asUByteArray()
val outputArray = ByteArray(sizeX * sizeY * 4)
val output = Vector2dArray(outputArray.asUByteArray(), 4, sizeX, sizeY)
when (format) {
YuvFormat.NV21 -> {
val startY = 0
val startU = sizeX * sizeY + 1
val startV = sizeX * sizeY
for (y in 0 until sizeY) {
for (x in 0 until sizeX) {
val offsetY = y * sizeX + x
val offsetU = ((y shr 1) * sizeX + (x shr 1) * 2)
val offsetV = ((y shr 1) * sizeX + (x shr 1) * 2)
output[x, y] = yuvToRGBA4(
inputArray[startY + offsetY],
inputArray[startU + offsetU],
inputArray[startV + offsetV]
)
}
}
}
YuvFormat.YV12 -> {
/* According to https://developer.android.com/reference/kotlin/android/graphics/ImageFormat#yv12,
* strideX and strideUV should be aligned to 16 byte boundaries. If we do this, we
* won't get the same results as RenderScript.
*
* We may want to test & require that sizeX is a multiple of 16/32.
*/
val strideX = roundUpTo16(sizeX) // sizeX //
val strideUV = roundUpTo16(strideX / 2) // strideX / 2 //
val startY = 0
val startU = strideX * sizeY
val startV = startU + strideUV * sizeY / 2
for (y in 0 until sizeY) {
for (x in 0 until sizeX) {
val offsetY = y * sizeX + x
val offsetUV = (y shr 1) * strideUV + (x shr 1)
output[x, y] = yuvToRGBA4(
inputArray[startY + offsetY],
inputArray[startU + offsetUV],
inputArray[startV + offsetUV],
)
}
}
}
else -> throw IllegalArgumentException("Unknown YUV format $format")
}
return outputArray
}
@ExperimentalUnsignedTypes
private fun yuvToRGBA4(y: UByte, u: UByte, v: UByte): UByteArray {
val intY = y.toInt() - 16
val intU = u.toInt() - 128
val intV = v.toInt() - 128
val p = intArrayOf(
intY * 298 + intV * 409 + 128 shr 8,
intY * 298 - intU * 100 - intV * 208 + 128 shr 8,
intY * 298 + intU * 516 + 128 shr 8,
255
)
return UByteArray(4) { p[it].clampToUByte() }
}
/* To be used if we support Float
private fun yuvToRGBA_f4(y: UByte, u: UByte, v: UByte): UByteArray {
val yuv_U_values = floatArrayOf(0f, -0.392f * 0.003921569f, 2.02f * 0.003921569f, 0f)
val yuv_V_values = floatArrayOf(1.603f * 0.003921569f, -0.815f * 0.003921569f, 0f, 0f)
var color = FloatArray(4) {y.toFloat() * 0.003921569f}
val fU = FloatArray(4) {u.toFloat() - 128f}
val fV = FloatArray(4) {v.toFloat() - 128f}
color += fU * yuv_U_values;
color += fV * yuv_V_values;
//color = clamp(color, 0.f, 1.f);
return UByteArray(4) { unitFloatClampedToUByte(color[it]) }
}
*/
| apache-2.0 | bbf55d88640049a9801ecc78efdc5949 | 36.401786 | 109 | 0.573645 | 3.860829 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/merge/concatff/ConcatFFLayerParameters.kt | 1 | 2288 | /* Copyright 2020-present Simone Cangialosi. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.merge.concatff
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.layers.models.feedforward.simple.FeedforwardLayerParameters
import com.kotlinnlp.simplednn.core.layers.models.merge.MergeLayerParameters
/**
* The parameters of the Concat Feedforward layer.
*
* @property inputsSize the size of each input
* @property outputSize the size of the output
* @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot)
* @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot)
*/
class ConcatFFLayerParameters(
inputsSize: List<Int>,
outputSize: Int,
weightsInitializer: Initializer? = GlorotInitializer(),
biasesInitializer: Initializer? = GlorotInitializer()
) : MergeLayerParameters(
inputsSize = inputsSize,
outputSize = outputSize,
weightsInitializer = weightsInitializer,
biasesInitializer = biasesInitializer,
sparseInput = false // actually not used because non-dense concatenation is not available
) {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* The output params.
*/
val output = FeedforwardLayerParameters(
inputSize = inputsSize.sum(),
outputSize = outputSize,
sparseInput = this.sparseInput)
/**
* The list of weights parameters.
*/
override val weightsList: List<ParamsArray> = this.output.weightsList
/**
* The list of biases parameters.
*/
override val biasesList: List<ParamsArray> = this.output.biasesList
/**
* Initialize all parameters values.
*/
init {
this.initialize()
}
}
| mpl-2.0 | ebd1dbc5342b8d25fa4cda36bbb5e198 | 31.685714 | 95 | 0.72465 | 4.557769 | false | false | false | false |
mdaniel/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/distance.kt | 5 | 8957 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.lang.resolve.impl
import com.intellij.lang.jvm.types.JvmPrimitiveTypeKind
import com.intellij.psi.*
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.TypeConversionUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ArgumentMapping
import org.jetbrains.plugins.groovy.lang.resolve.api.CallParameter
import org.jetbrains.plugins.groovy.lang.resolve.api.DelegateArgumentMapping
import org.jetbrains.plugins.groovy.lang.sam.samDistance
fun <X : CallParameter> compare(left: ArgumentMapping<X>, right: ArgumentMapping<X>): Int {
if (left is DelegateArgumentMapping) {
return compare(left.delegate, right)
}
else if (right is DelegateArgumentMapping) {
return compare(left, right.delegate)
}
if (left is NullArgumentMapping && right is NullArgumentMapping) {
return 0
}
else if (left is NullArgumentMapping) {
// prefer right
return 1
}
else if (right is NullArgumentMapping) {
// prefer left
return -1
}
if (left is VarargArgumentMapping && right is VarargArgumentMapping) {
return VarargArgumentMapping.compare(left, right)
}
else if (left is VarargArgumentMapping) {
// prefer right
return 1
}
else if (right is VarargArgumentMapping) {
// prefer left
return -1
}
val leftDistance = (left as PositionalArgumentMapping).distance
val rightDistance = (right as PositionalArgumentMapping).distance
return when {
leftDistance == 0L -> -1
rightDistance == 0L -> 1
else -> leftDistance.compareTo(rightDistance) // prefer one with less distance
}
}
fun positionalParametersDistance(map: Map<Argument, CallParameter>, context: PsiElement): Long {
var result = 0L
for ((argument, parameter) in map) {
val runtimeType = argument.runtimeType ?: continue
val parameterType = parameter.type ?: continue
result += parameterDistance(runtimeType, argument, parameterType, context)
}
return result
}
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.calculateParameterDistance
*/
fun parameterDistance(argument: PsiType, argumentCompileTime: Argument?, parameter: PsiType, context: PsiElement): Long {
return parameterDistance0(argument, argumentCompileTime, TypeConversionUtil.erasure(parameter), context)
}
private fun parameterDistance0(argument: PsiType, argumentCompileTime: Argument?, parameter: PsiType, context: PsiElement): Long {
if (argument == parameter) return 0
val parameterClass = (parameter as? PsiClassType)?.resolve()
val argumentClass = (argument as? PsiClassType)?.resolve()
if (PsiType.NULL == argument) {
return when {
parameter is PsiPrimitiveType -> 2L shl OBJECT_SHIFT // ?
parameterClass?.isInterface == true -> -1L
else -> objectDistance(parameter).toLong() shl OBJECT_SHIFT
}
}
if (parameterClass != null && parameterClass.isInterface) {
val dist = getMaximumInterfaceDistance(argumentClass, parameterClass)
if (dist > -1 || !InheritanceUtil.isInheritor(argument, GroovyCommonClassNames.GROOVY_LANG_CLOSURE)) {
return dist.toLong()
}
}
var objectDistance: Long = 0
val pd = getPrimitiveDistance(parameter, argument)
if (pd != -1) {
return pd.toLong() shl PRIMITIVE_SHIFT
}
objectDistance += primitives.size + 1
if (argument is PsiArrayType && parameter !is PsiArrayType) {
objectDistance += 4
}
var argumentClass2: PsiClass? = if (argument is PsiPrimitiveType) {
JavaPsiFacade.getInstance(context.project).findClass(argument.kind.boxedFqn, context.resolveScope)
}
else {
argumentClass
}
val samDistance = samDistance(argumentCompileTime, parameterClass)
if (samDistance != null) {
return (objectDistance + samDistance) shl OBJECT_SHIFT
}
while (argumentClass2 != null) {
if (argumentClass2 == parameterClass) break
if (argumentClass2.qualifiedName == GroovyCommonClassNames.GROOVY_LANG_GSTRING && parameterClass?.qualifiedName == CommonClassNames.JAVA_LANG_STRING) {
objectDistance += 2
break
}
argumentClass2 = argumentClass2.superClass
objectDistance += 3
}
return objectDistance shl OBJECT_SHIFT
}
private fun objectDistance(parameter: PsiType): Int {
val psiTypeSuperTypes = parameter.superTypes.size
val superTypesCount = if (parameter is PsiArrayType) psiTypeSuperTypes + 1 else psiTypeSuperTypes
return superTypesCount * 2
}
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.PRIMITIVE_SHIFT
*/
private const val PRIMITIVE_SHIFT = 21
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.OBJECT_SHIFT
*/
private const val OBJECT_SHIFT = 23
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.PRIMITIVES
*/
private val primitives = arrayOf(
JvmPrimitiveTypeKind.BOOLEAN.name,
JvmPrimitiveTypeKind.BOOLEAN.boxedFqn,
JvmPrimitiveTypeKind.BYTE.name,
JvmPrimitiveTypeKind.BYTE.boxedFqn,
JvmPrimitiveTypeKind.SHORT.name,
JvmPrimitiveTypeKind.SHORT.boxedFqn,
JvmPrimitiveTypeKind.CHAR.name,
JvmPrimitiveTypeKind.CHAR.boxedFqn,
JvmPrimitiveTypeKind.INT.name,
JvmPrimitiveTypeKind.INT.boxedFqn,
JvmPrimitiveTypeKind.LONG.name,
JvmPrimitiveTypeKind.LONG.boxedFqn,
GroovyCommonClassNames.JAVA_MATH_BIG_INTEGER,
JvmPrimitiveTypeKind.FLOAT.name,
JvmPrimitiveTypeKind.FLOAT.boxedFqn,
JvmPrimitiveTypeKind.DOUBLE.name,
JvmPrimitiveTypeKind.DOUBLE.boxedFqn,
GroovyCommonClassNames.JAVA_MATH_BIG_DECIMAL,
CommonClassNames.JAVA_LANG_NUMBER,
CommonClassNames.JAVA_LANG_OBJECT
)
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.PRIMITIVE_DISTANCE_TABLE
*/
private val primitiveDistances = arrayOf(
intArrayOf(0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2),
intArrayOf(1, 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2),
intArrayOf(18, 19, 0, 1, 2, 3, 16, 17, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
intArrayOf(18, 19, 1, 0, 2, 3, 16, 17, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
intArrayOf(18, 19, 14, 15, 0, 1, 16, 17, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
intArrayOf(18, 19, 14, 15, 1, 0, 16, 17, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
intArrayOf(18, 19, 16, 17, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
intArrayOf(18, 19, 16, 17, 14, 15, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9),
intArrayOf(18, 19, 9, 10, 7, 8, 16, 17, 5, 6, 3, 4, 0, 14, 15, 12, 13, 11, 1, 2),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 0, 1, 2, 3, 4, 5, 6),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 1, 0, 2, 3, 4, 5, 6),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 5, 6, 0, 1, 2, 3, 4),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 5, 6, 1, 0, 2, 3, 4),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 5, 6, 3, 4, 0, 1, 2),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 5, 6, 3, 4, 2, 0, 1),
intArrayOf(18, 19, 14, 15, 12, 13, 16, 17, 10, 11, 8, 9, 7, 5, 6, 3, 4, 2, 1, 0)
)
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.getPrimitiveIndex
*/
private fun getPrimitiveIndex(name: String?): Int = primitives.indexOf(name)
private fun getPrimitiveName(type: PsiType): String? = when (type) {
is PsiPrimitiveType -> type.kind.name
is PsiClassType -> type.resolve()?.qualifiedName
else -> null
}
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.getPrimitiveDistance
*/
private fun getPrimitiveDistance(from: PsiType, to: PsiType): Int {
val fromIndex = getPrimitiveIndex(getPrimitiveName(from))
if (fromIndex < 0) {
return -1
}
val toIndex = getPrimitiveIndex(getPrimitiveName(to))
if (toIndex < 0) {
return -1
}
return primitiveDistances[toIndex][fromIndex]
}
/**
* @see org.codehaus.groovy.runtime.MetaClassHelper.getMaximumInterfaceDistance
*/
private fun getMaximumInterfaceDistance(argument: PsiClass?, interfaceClass: PsiClass): Int {
if (argument == null) return -1 //?
if (argument.isEquivalentTo(interfaceClass)) return 0
val interfaces = argument.interfaces
var max = -1
for (anInterface in interfaces) {
var sub = getMaximumInterfaceDistance(anInterface, interfaceClass)
if (sub != -1) sub++
max = Math.max(max, sub)
}
var superClassMax = getMaximumInterfaceDistance(argument.superClass, interfaceClass)
if (superClassMax != -1) superClassMax++
return Math.max(max, superClassMax)
}
| apache-2.0 | a64432a61b1828473fc9bbdeb7770a46 | 36.320833 | 155 | 0.699565 | 3.41219 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.