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
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/util/BreakpointCreator.kt
1
11227
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.test.util import com.intellij.debugger.DebuggerInvocationUtil import com.intellij.debugger.engine.evaluation.CodeFragmentKind import com.intellij.debugger.engine.evaluation.TextWithImportsImpl import com.intellij.debugger.ui.breakpoints.Breakpoint import com.intellij.debugger.ui.breakpoints.BreakpointManager import com.intellij.debugger.ui.breakpoints.LineBreakpoint import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.search.FilenameIndex import com.intellij.xdebugger.XDebuggerManager import com.intellij.xdebugger.XDebuggerUtil import com.intellij.xdebugger.breakpoints.XBreakpointManager import com.intellij.xdebugger.breakpoints.XBreakpointProperties import com.intellij.xdebugger.breakpoints.XBreakpointType import com.intellij.xdebugger.breakpoints.XLineBreakpointType import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties import org.jetbrains.kotlin.idea.debugger.breakpoints.* import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.isKotlinSourceFile import org.jetbrains.kotlin.idea.debugger.core.breakpoints.KotlinFieldBreakpoint import org.jetbrains.kotlin.idea.debugger.core.breakpoints.KotlinFunctionBreakpoint import org.jetbrains.kotlin.idea.debugger.core.breakpoints.KotlinFunctionBreakpointType import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.findLinesWithPrefixesRemoved import org.jetbrains.kotlin.idea.util.application.runReadAction import java.util.* import javax.swing.SwingUtilities internal class BreakpointCreator( private val project: Project, private val logger: (String) -> Unit, private val preferences: DebuggerPreferences ) { fun createBreakpoints(file: PsiFile) { val document = runReadAction { PsiDocumentManager.getInstance(project).getDocument(file) } ?: return val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager val kotlinFieldBreakpointType = findBreakpointType(KotlinFieldBreakpointType::class.java) val virtualFile = file.virtualFile val runnable = { var offset = -1 while (true) { val fileText = document.text offset = fileText.indexOf("point!", offset + 1) if (offset == -1) break val commentLine = document.getLineNumber(offset) val lineIndex = commentLine + 1 val comment = fileText .substring(document.getLineStartOffset(commentLine), document.getLineEndOffset(commentLine)) .trim() when { comment.startsWith("//FieldWatchpoint!") -> { val javaBreakpoint = createBreakpointOfType( breakpointManager, kotlinFieldBreakpointType, lineIndex, virtualFile ) (javaBreakpoint as? KotlinFieldBreakpoint)?.apply { val fieldName = comment.substringAfter("//FieldWatchpoint! (").substringBefore(")") setFieldName(fieldName) setWatchAccess(preferences[DebuggerPreferenceKeys.WATCH_FIELD_ACCESS]) setWatchModification(preferences[DebuggerPreferenceKeys.WATCH_FIELD_MODIFICATION]) setWatchInitialization(preferences[DebuggerPreferenceKeys.WATCH_FIELD_INITIALISATION]) BreakpointManager.addBreakpoint(javaBreakpoint) logger("KotlinFieldBreakpoint created at ${file.virtualFile.name}:${lineIndex + 1}") } } comment.startsWith("//Breakpoint!") -> { val ordinal = getPropertyFromComment(comment, "lambdaOrdinal")?.toInt() val condition = getPropertyFromComment(comment, "condition") createLineBreakpoint(breakpointManager, file, lineIndex, ordinal, condition) } comment.startsWith("//FunctionBreakpoint!") -> { createFunctionBreakpoint(breakpointManager, file, lineIndex, false) } else -> throw AssertionError("Cannot create breakpoint at line ${lineIndex + 1}") } } } if (!SwingUtilities.isEventDispatchThread()) { DebuggerInvocationUtil.invokeAndWait(project, runnable, ModalityState.defaultModalityState()) } else { runnable.invoke() } } fun createAdditionalBreakpoints(fileContents: String) { val breakpoints = findLinesWithPrefixesRemoved(fileContents, "// ADDITIONAL_BREAKPOINT: ") for (breakpoint in breakpoints) { val chunks = breakpoint.split('/').map { it.trim() } val fileName = chunks.getOrNull(0) ?: continue val lineMarker = chunks.getOrNull(1) ?: continue val kind = chunks.getOrElse(2) { "line" } val ordinal = chunks.getOrNull(3)?.toInt() val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager when (kind) { "line" -> createBreakpoint(fileName, lineMarker) { psiFile, lineNumber -> createLineBreakpoint(breakpointManager, psiFile, lineNumber + 1, ordinal, null) } "fun" -> createBreakpoint(fileName, lineMarker) { psiFile, lineNumber -> createFunctionBreakpoint(breakpointManager, psiFile, lineNumber, true) } else -> error("Unknown breakpoint kind: $kind") } } } private fun getPropertyFromComment(comment: String, propertyName: String): String? { if (comment.contains("$propertyName = ")) { val result = comment.substringAfter("$propertyName = ") if (result.contains(", ")) { return result.substringBefore(", ") } if (result.contains(")")) { return result.substringBefore(")") } return result } return null } private fun createBreakpoint(fileName: String, lineMarker: String, action: (PsiFile, Int) -> Unit) { val sourceFiles = runReadAction { val actualType = FileUtilRt.getExtension(fileName).lowercase(Locale.getDefault()) assert(isKotlinSourceFile(fileName)) { "Could not set a breakpoint on a non-kt file" } FilenameIndex.getAllFilesByExt(project, actualType) .filter { it.name == fileName && it.contentsToByteArray().toString(Charsets.UTF_8).contains(lineMarker) } } val sourceFile = sourceFiles.singleOrNull() ?: error("Single source file should be found: name = $fileName, sourceFiles = $sourceFiles") val runnable = Runnable { val psiSourceFile = PsiManager.getInstance(project).findFile(sourceFile) ?: error("Psi file not found for $sourceFile") val document = PsiDocumentManager.getInstance(project).getDocument(psiSourceFile)!! val index = psiSourceFile.text!!.indexOf(lineMarker) val lineNumber = document.getLineNumber(index) action(psiSourceFile, lineNumber) } DebuggerInvocationUtil.invokeAndWait(project, runnable, ModalityState.defaultModalityState()) } private fun createFunctionBreakpoint(breakpointManager: XBreakpointManager, file: PsiFile, lineIndex: Int, fromLibrary: Boolean) { val breakpointType = findBreakpointType(KotlinFunctionBreakpointType::class.java) val breakpoint = createBreakpointOfType(breakpointManager, breakpointType, lineIndex, file.virtualFile) if (breakpoint is KotlinFunctionBreakpoint) { val lineNumberSuffix = if (fromLibrary) "" else ":${lineIndex + 1}" logger("FunctionBreakpoint created at ${file.virtualFile.name}$lineNumberSuffix") } } private fun createLineBreakpoint( breakpointManager: XBreakpointManager, file: PsiFile, lineIndex: Int, lambdaOrdinal: Int?, condition: String? ) { val kotlinLineBreakpointType = findBreakpointType(KotlinLineBreakpointType::class.java) val javaBreakpoint = createBreakpointOfType( breakpointManager, kotlinLineBreakpointType, lineIndex, file.virtualFile ) if (javaBreakpoint is LineBreakpoint<*>) { val properties = javaBreakpoint.xBreakpoint.properties as? JavaLineBreakpointProperties ?: return var suffix = "" if (lambdaOrdinal != null) { if (lambdaOrdinal != -1) { properties.lambdaOrdinal = lambdaOrdinal - 1 } else { properties.lambdaOrdinal = lambdaOrdinal } suffix += " lambdaOrdinal = $lambdaOrdinal" } if (condition != null) { javaBreakpoint.setCondition(TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition)) suffix += " condition = $condition" } BreakpointManager.addBreakpoint(javaBreakpoint) logger("LineBreakpoint created at ${file.virtualFile.name}:${lineIndex + 1}$suffix") } } private fun createBreakpointOfType( breakpointManager: XBreakpointManager, breakpointType: XLineBreakpointType<XBreakpointProperties<*>>, lineIndex: Int, virtualFile: VirtualFile ): Breakpoint<out JavaBreakpointProperties<*>>? { if (!breakpointType.canPutAt(virtualFile, lineIndex, project)) return null val xBreakpoint = runWriteAction { breakpointManager.addLineBreakpoint( breakpointType, virtualFile.url, lineIndex, breakpointType.createBreakpointProperties(virtualFile, lineIndex) ) } return BreakpointManager.getJavaBreakpoint(xBreakpoint) } @Suppress("UNCHECKED_CAST") private inline fun <reified T : XBreakpointType<*, *>> findBreakpointType(javaClass: Class<T>): XLineBreakpointType<XBreakpointProperties<*>> { return XDebuggerUtil.getInstance().findBreakpointType(javaClass) as XLineBreakpointType<XBreakpointProperties<*>> } }
apache-2.0
38e56c3b29d73c53eef0ff73dbe46dad
46.371308
147
0.655295
5.633216
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryEntityImpl.kt
1
19597
package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import com.intellij.workspaceModel.storage.url.VirtualFileUrl import java.io.Serializable import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class LibraryEntityImpl: LibraryEntity, WorkspaceEntityBase() { companion object { internal val SDK_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, SdkEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val LIBRARYPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, LibraryPropertiesEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, LibraryFilesPackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( SDK_CONNECTION_ID, LIBRARYPROPERTIES_CONNECTION_ID, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, ) } @JvmField var _name: String? = null override val name: String get() = _name!! @JvmField var _tableId: LibraryTableId? = null override val tableId: LibraryTableId get() = _tableId!! @JvmField var _roots: List<LibraryRoot>? = null override val roots: List<LibraryRoot> get() = _roots!! @JvmField var _excludedRoots: List<VirtualFileUrl>? = null override val excludedRoots: List<VirtualFileUrl> get() = _excludedRoots!! override val sdk: SdkEntity? get() = snapshot.extractOneToOneChild(SDK_CONNECTION_ID, this) override val libraryProperties: LibraryPropertiesEntity? get() = snapshot.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this) override val libraryFilesPackagingElement: LibraryFilesPackagingElementEntity? get() = snapshot.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: LibraryEntityData?): ModifiableWorkspaceEntityBase<LibraryEntity>(), LibraryEntity.Builder { constructor(): this(LibraryEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity LibraryEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() index(this, "excludedRoots", this.excludedRoots.toHashSet()) indexLibraryRoots(roots) // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isNameInitialized()) { error("Field LibraryEntity#name should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field LibraryEntity#entitySource should be initialized") } if (!getEntityData().isTableIdInitialized()) { error("Field LibraryEntity#tableId should be initialized") } if (!getEntityData().isRootsInitialized()) { error("Field LibraryEntity#roots should be initialized") } if (!getEntityData().isExcludedRootsInitialized()) { error("Field LibraryEntity#excludedRoots should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } private fun indexLibraryRoots(libraryRoots: List<LibraryRoot>) { val jarDirectories = mutableSetOf<VirtualFileUrl>() val libraryRootList = libraryRoots.map { if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) { jarDirectories.add(it.url) } it.url }.toHashSet() index(this, "roots", libraryRootList) indexJarDirectories(this, jarDirectories) } override var name: String get() = getEntityData().name set(value) { checkModificationAllowed() getEntityData().name = value changedProperty.add("name") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var tableId: LibraryTableId get() = getEntityData().tableId set(value) { checkModificationAllowed() getEntityData().tableId = value changedProperty.add("tableId") } override var roots: List<LibraryRoot> get() = getEntityData().roots set(value) { checkModificationAllowed() getEntityData().roots = value val _diff = diff if (_diff != null) { indexLibraryRoots(value) } changedProperty.add("roots") } override var excludedRoots: List<VirtualFileUrl> get() = getEntityData().excludedRoots set(value) { checkModificationAllowed() getEntityData().excludedRoots = value val _diff = diff if (_diff != null) index(this, "excludedRoots", value.toHashSet()) changedProperty.add("excludedRoots") } override var sdk: SdkEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(SDK_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity } else { this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(SDK_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] = value } changedProperty.add("sdk") } override var libraryProperties: LibraryPropertiesEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity } else { this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(LIBRARYPROPERTIES_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] = value } changedProperty.add("libraryProperties") } override var libraryFilesPackagingElement: LibraryFilesPackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity } else { this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = value } changedProperty.add("libraryFilesPackagingElement") } override fun getEntityData(): LibraryEntityData = result ?: super.getEntityData() as LibraryEntityData override fun getEntityClass(): Class<LibraryEntity> = LibraryEntity::class.java } } class LibraryEntityData : WorkspaceEntityData.WithCalculablePersistentId<LibraryEntity>(), SoftLinkable { lateinit var name: String lateinit var tableId: LibraryTableId lateinit var roots: List<LibraryRoot> lateinit var excludedRoots: List<VirtualFileUrl> fun isNameInitialized(): Boolean = ::name.isInitialized fun isTableIdInitialized(): Boolean = ::tableId.isInitialized fun isRootsInitialized(): Boolean = ::roots.isInitialized fun isExcludedRootsInitialized(): Boolean = ::excludedRoots.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() val _tableId = tableId when (_tableId) { is LibraryTableId.ModuleLibraryTableId -> { result.add(_tableId.moduleId) } is LibraryTableId.ProjectLibraryTableId -> { } is LibraryTableId.GlobalLibraryTableId -> { } } for (item in roots) { } for (item in excludedRoots) { } return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { val _tableId = tableId when (_tableId) { is LibraryTableId.ModuleLibraryTableId -> { index.index(this, _tableId.moduleId) } is LibraryTableId.ProjectLibraryTableId -> { } is LibraryTableId.GlobalLibraryTableId -> { } } for (item in roots) { } for (item in excludedRoots) { } } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val _tableId = tableId when (_tableId) { is LibraryTableId.ModuleLibraryTableId -> { val removedItem__tableId_moduleId = mutablePreviousSet.remove(_tableId.moduleId) if (!removedItem__tableId_moduleId) { index.index(this, _tableId.moduleId) } } is LibraryTableId.ProjectLibraryTableId -> { } is LibraryTableId.GlobalLibraryTableId -> { } } for (item in roots) { } for (item in excludedRoots) { } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val _tableId = tableId val res_tableId = when (_tableId) { is LibraryTableId.ModuleLibraryTableId -> { val _tableId_moduleId_data = if (_tableId.moduleId == oldLink) { changed = true newLink as ModuleId } else { null } var _tableId_data = _tableId if (_tableId_moduleId_data != null) { _tableId_data = _tableId_data.copy(moduleId = _tableId_moduleId_data) } _tableId_data } is LibraryTableId.ProjectLibraryTableId -> { _tableId } is LibraryTableId.GlobalLibraryTableId -> { _tableId } } if (res_tableId != null) { tableId = res_tableId } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryEntity> { val modifiable = LibraryEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): LibraryEntity { val entity = LibraryEntityImpl() entity._name = name entity._tableId = tableId entity._roots = roots entity._excludedRoots = excludedRoots entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return LibraryId(name, tableId) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return LibraryEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LibraryEntityData if (this.name != other.name) return false if (this.entitySource != other.entitySource) return false if (this.tableId != other.tableId) return false if (this.roots != other.roots) return false if (this.excludedRoots != other.excludedRoots) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LibraryEntityData if (this.name != other.name) return false if (this.tableId != other.tableId) return false if (this.roots != other.roots) return false if (this.excludedRoots != other.excludedRoots) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + name.hashCode() result = 31 * result + tableId.hashCode() result = 31 * result + roots.hashCode() result = 31 * result + excludedRoots.hashCode() return result } }
apache-2.0
6d443e3f45128e6d5517830e99602998
41.146237
221
0.591468
5.980165
false
false
false
false
InputUsername/Ananas
app/src/main/java/com/fruitscale/ananas/NewGroupActivity.kt
1
5544
package com.fruitscale.ananas import android.app.SearchManager import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.SearchView import android.view.Menu import android.view.MenuItem import android.view.View import com.fruitscale.ananas.adapters.ContactListAdapter import com.fruitscale.ananas.adapters.SelectedContactListAdapter import kotlinx.android.synthetic.main.activity_new_group.* class NewGroupActivity : AppCompatActivity() { private var mEnableEndToEndEncryption = true private var mSelectedContactsRecyclerViewAdapter: SelectedContactListAdapter? = null private var mSelectedContactsRecyclerViewLayoutManager: RecyclerView.LayoutManager? = null private val mSelectedContactList: MutableSet<Contact> = hashSetOf() private var mContactsRecyclerViewAdapter: ContactListAdapter? = null private var mContactsRecyclerViewLayoutManager: RecyclerView.LayoutManager? = null private val mContactList: MutableSet<Contact> = hashSetOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_group) val toolbar = create_group_main_menu setSupportActionBar(toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) mContactsRecyclerViewLayoutManager = LinearLayoutManager(this) unselected_contacts_recyclerview.layoutManager = mContactsRecyclerViewLayoutManager mContactList.addAll(arrayOf( Contact("BudD", "[email protected]", "1-234-567-8910", "Bud Ditchwater"), Contact("BarryTheB", "[email protected]", "1-234-567-8910", "Barry the Bee"), Contact("VanessaB", "[email protected]", "1-234-567-8910", "Vanessa Bloome"), Contact("buzzw3ll", "[email protected]", "1-234-567-8910", "buzzwell"), Contact("cptLou", "[email protected]", "1-234-567-8910", "Lou Lo Duca"), Contact("TLayton", "[email protected]", "1-234-567-8910", "Layton T. Montgomery"), Contact("cool_bbton", "[email protected]", "1-234-567-8910", "Judge Bumbleton") )) mSelectedContactsRecyclerViewLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) selected_contacts_recyclerview.layoutManager = mSelectedContactsRecyclerViewLayoutManager mSelectedContactList.addAll(arrayOf( mContactList.toTypedArray()[1], mContactList.toTypedArray()[3], mContactList.toTypedArray()[4], mContactList.toTypedArray()[6] )) // Create adapters etc. mSelectedContactsRecyclerViewAdapter = SelectedContactListAdapter(mSelectedContactList, this) selected_contacts_recyclerview.adapter = mSelectedContactsRecyclerViewAdapter mContactsRecyclerViewAdapter = ContactListAdapter(mContactList, mSelectedContactList) unselected_contacts_recyclerview.adapter = mContactsRecyclerViewAdapter val dividerItemDecoration = DividerItemDecoration(unselected_contacts_recyclerview.context, DividerItemDecoration.VERTICAL) unselected_contacts_recyclerview.addItemDecoration(dividerItemDecoration) updateViewForContactsSelected(!mSelectedContactList.isEmpty()) // TODO: Add this inside an onClickListener that listens for clicks on a contact or selectedContact. if (!mContactList.isEmpty()) { text_no_contacts.visibility = View.GONE } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_new_group, menu) // https://developer.android.com/training/search/setup.html#create-sc // Associate searchable configuration with the SearchView val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchView: SearchView = menu.findItem(R.id.search_contacts).actionView as SearchView searchView.setSearchableInfo( searchManager.getSearchableInfo(componentName) ) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.enable_encryption -> { mEnableEndToEndEncryption = !mEnableEndToEndEncryption if (mEnableEndToEndEncryption) { // Encryption is enabled item.setIcon(R.drawable.ic_lock_outline_black_24dp) item.setTitle(R.string.disable_end_to_end_encryption) } else { // Encryption is disabled item.setIcon(R.drawable.ic_lock_open_black_24dp) item.setTitle(R.string.enable_end_to_end_encryption) } return true } else -> return super.onOptionsItemSelected(item) } } fun updateViewForContactsSelected(selected: Boolean) { if (selected) { no_contacts_selected.visibility = View.GONE selected_contacts_recyclerview.visibility = View.VISIBLE } else { no_contacts_selected.visibility = View.VISIBLE selected_contacts_recyclerview.visibility = View.GONE } } }
mit
fad7b988c111d54e3b8ccdb93c0ca24f
43.352
131
0.703824
4.738462
false
false
false
false
Major-/Vicis
modern/src/test/kotlin/rs/emulate/modern/codec/ReferenceTableTest.kt
1
4154
package rs.emulate.modern.codec import io.netty.buffer.Unpooled import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import rs.emulate.modern.codec.ReferenceTable.Companion.readRefTable class ReferenceTableTest { private val buf = Unpooled.buffer().apply { /* header */ writeByte(6) /* format */ writeInt(1337) /* version */ writeByte(0x1) /* flags */ writeShort(3) /* size */ /* entry id deltas */ writeShort(3) writeShort(1) writeShort(6) /* entry name hashes */ writeInt(0x1234) writeInt(0x5678) writeInt(0x9ABC) /* entry checksums */ writeInt(0xDDDD) writeInt(0xEEEE) writeInt(0xFFFF) /* entry versions */ writeInt(1) writeInt(2) writeInt(3) /* child sizes */ writeShort(0) writeShort(1) writeShort(3) /* child id deltas */ writeShort(1) writeShort(1) writeShort(3) writeShort(6) /* child name hashes */ writeInt(0x0123) writeInt(0x4567) writeInt(0x89AB) writeInt(0xCDEF) } @Test fun read() { val table = buf.readRefTable() assertEquals(6, table.format) assertEquals(1337, table.version) assertTrue(table.nameHashingEnabled) assertEquals(3, table.size) assertEquals(11, table.capacity) for (i in 0..10) { if (i == 3 || i == 4 || i == 10) { assertTrue(table.containsEntry(i)) } else { assertFalse(table.containsEntry(i)) } } var entry: ReferenceTable.Entry = table.getEntry(3)!! assertEquals(0x1234, entry.nameHash) assertEquals(0xDDDD, entry.checksum) assertEquals(1, entry.version) assertEquals(0, entry.size) assertEquals(0, entry.capacity) entry = table.getEntry(4)!! assertEquals(0x5678, entry.nameHash) assertEquals(0xEEEE, entry.checksum) assertEquals(2, entry.version) assertEquals(1, entry.size) assertEquals(2, entry.capacity) assertTrue(1 in entry) var child: ReferenceTable.ChildEntry = entry[1]!! assertEquals(0x0123, child.nameHash) entry = table.getEntry(10)!! assertEquals(0x9ABC, entry.nameHash) assertEquals(0xFFFF, entry.checksum) assertEquals(3, entry.version) assertEquals(3, entry.size) assertEquals(11, entry.capacity) child = entry[1]!! assertEquals(0x4567, child.nameHash) child = entry[4]!! assertEquals(0x89AB, child.nameHash) child = entry[10]!! assertEquals(0xCDEF, child.nameHash) } @Test fun write() { val table = ReferenceTable() table.version = 1337 table.nameHashingEnabled = true var entry: ReferenceTable.Entry = table.createEntry(3) entry.nameHash = 0x1234 entry.checksum = 0xDDDD entry.version = 1 entry = table.createEntry(4) entry.nameHash = 0x5678 entry.checksum = 0xEEEE entry.version = 2 var child: ReferenceTable.ChildEntry = entry.createChild(1) child.nameHash = 0x0123 entry = table.createEntry(10) entry.nameHash = 0x9ABC entry.checksum = 0xFFFF entry.version = 3 child = entry.createChild(1) child.nameHash = 0x4567 child = entry.createChild(4) child.nameHash = 0x89AB child = entry.createChild(10) child.nameHash = 0xCDEF assertEquals(buf, table.write()) } @Test fun `lookup by name hash`() { val table = ReferenceTable() val entry = table.createEntry(123) entry.setName("hello") assertEquals(entry, table.getEntry("hello")) assertNull(table.getEntry("non-existent")) } }
isc
050026ac260599509af46784f000cb3b
24.801242
68
0.592922
4.08055
false
false
false
false
byu-oit/android-byu-suite-v2
app/src/main/java/edu/byu/suite/features/myClasses/MyClassesMapFragment.kt
2
1149
package edu.byu.suite.features.myClasses import android.os.Bundle import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import edu.byu.support.client.campusLocation.model.Building import edu.byu.support.fragment.ByuMapFragment /** * Created by geogor37 on 1/19/18 */ class MyClassesMapFragment: ByuMapFragment() { companion object { const val BUILDINGS: String = "buildings" fun newInstance(buildings: ArrayList<Building>): MyClassesMapFragment { val args = Bundle() args.putParcelableArrayList(BUILDINGS, buildings) val fragment = MyClassesMapFragment() fragment.arguments = args return fragment } } override fun onMapReady(googleMap: GoogleMap?) { super.onMapReady(googleMap) val buildings: List<Building>? = arguments?.getParcelableArrayList(BUILDINGS) buildings?.forEach { addMarker(MarkerOptions().position(LatLng(it.latitude.toDouble(), it.longitude.toDouble())).title(it.acronym).snippet(it.name))?.showInfoWindow() } zoomWithOptions(includeCampus = true, includeMarkers = true) dismissProgressDialog() } }
apache-2.0
779aa9fc299b2e2b3c016bf11a4d54d6
32.823529
170
0.778938
3.855705
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/migration/DataExporter.kt
1
8273
package io.ipoli.android.common.migration import android.annotation.SuppressLint import android.arch.persistence.room.Transaction import android.content.Context import android.support.annotation.WorkerThread import com.google.android.gms.tasks.Tasks import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.WriteBatch import io.ipoli.android.Constants import io.ipoli.android.MyPoliApp import io.ipoli.android.challenge.persistence.FirestoreChallengeRepository import io.ipoli.android.common.datetime.milliseconds import io.ipoli.android.common.di.BackgroundModule import io.ipoli.android.common.persistence.BaseFirestoreRepository import io.ipoli.android.dailychallenge.data.persistence.FirestoreDailyChallengeRepository import io.ipoli.android.habit.persistence.FirestoreHabitRepository import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.FirestorePlayerRepository import io.ipoli.android.quest.Entity import io.ipoli.android.quest.data.persistence.FirestoreQuestRepository import io.ipoli.android.repeatingquest.persistence.FirestoreRepeatingQuestRepository import io.ipoli.android.tag.persistence.FirestoreTagRepository import space.traversal.kapsule.Injects import space.traversal.kapsule.inject import space.traversal.kapsule.required class DataExporter(private val appContext: Context) : Injects<BackgroundModule> { private val remoteDatabase by required { remoteDatabase } private val sharedPreferences by required { sharedPreferences } private val internetConnectionChecker by required { internetConnectionChecker } private val playerRepository by required { playerRepository } private val tagRepository by required { tagRepository } private val habitRepository by required { habitRepository } private val dailyChallengeRepository by required { dailyChallengeRepository } private val challengeRepository by required { challengeRepository } private val repeatingQuestRepository by required { repeatingQuestRepository } private val questRepository by required { questRepository } @SuppressLint("ApplySharedPref") @WorkerThread fun export() { inject(MyPoliApp.backgroundModule(appContext)) if (!internetConnectionChecker.isConnected()) return val authUser = FirebaseAuth.getInstance().currentUser requireNotNull(authUser) { "DataExporter called without FirebaseAuth user" } val syncTime = System.currentTimeMillis() exportPlayerData() exportCollections() sharedPreferences.edit() .putLong(Constants.KEY_LAST_SYNC_MILLIS, syncTime) .commit() } @SuppressLint("ApplySharedPref") @WorkerThread fun exportNewData() { inject(MyPoliApp.backgroundModule(appContext)) if (!internetConnectionChecker.isConnected()) return requireNotNull(FirebaseAuth.getInstance().currentUser) { "DataExporter called without FirebaseAuth user" } val lastSync = sharedPreferences.getLong(Constants.KEY_LAST_SYNC_MILLIS, 0) val lastSyncMillis = lastSync.milliseconds val batch = remoteDatabase.batch() var count = 0 val syncTime = System.currentTimeMillis() val fp = FirestorePlayerRepository(remoteDatabase) fp.addToBatch(playerRepository.findAllForSync(lastSyncMillis), batch) count++ val (b, c) = exportEntities( entities = tagRepository.findAllForSync(lastSyncMillis), remoteRepo = FirestoreTagRepository(remoteDatabase), startBatch = batch, startCount = count ) val (b1, c1) = exportEntities( entities = habitRepository.findAllForSync(lastSyncMillis), remoteRepo = FirestoreHabitRepository(remoteDatabase), startBatch = b, startCount = c ) val (b2, c2) = exportEntities( entities = challengeRepository.findAllForSync(lastSyncMillis), remoteRepo = FirestoreChallengeRepository(remoteDatabase), startBatch = b1, startCount = c1 ) val (b3, c3) = exportEntities( entities = repeatingQuestRepository.findAllForSync(lastSyncMillis), remoteRepo = FirestoreRepeatingQuestRepository(remoteDatabase), startBatch = b2, startCount = c2 ) val (b4, c4) = exportEntities( entities = dailyChallengeRepository.findAllForSync(lastSyncMillis), remoteRepo = FirestoreDailyChallengeRepository(remoteDatabase), startBatch = b3, startCount = c3 ) val (lb, _) = exportEntities( entities = questRepository.findAllForSync(lastSyncMillis), remoteRepo = FirestoreQuestRepository(remoteDatabase), startBatch = b4, startCount = c4 ) Tasks.await(lb.commit()) sharedPreferences.edit() .putLong(Constants.KEY_LAST_SYNC_MILLIS, syncTime) .commit() } private fun <E : Entity> exportEntities( entities: List<E>, remoteRepo: BaseFirestoreRepository<E, *>, startBatch: WriteBatch, startCount: Int ): Pair<WriteBatch, Int> { var batch = startBatch var count = startCount entities.forEach { remoteRepo.addToBatch(it, batch) count++ if (count == 500) { batch = commitAndCreateNewBatch(batch) count = 0 } } return Pair(batch, count) } private fun commitAndCreateNewBatch(batch: WriteBatch): WriteBatch { Tasks.await(batch.commit()) return remoteDatabase.batch() } @SuppressLint("ApplySharedPref") private fun exportPlayerData() { val batch = remoteDatabase.batch() val fp = FirestorePlayerRepository(remoteDatabase) val localPlayer = playerRepository.find()!! val remotePlayerId = FirebaseAuth.getInstance().currentUser!!.uid val newPlayer = if (localPlayer.id != remotePlayerId) { sharedPreferences .edit() .putString(Constants.KEY_PLAYER_ID, remotePlayerId) .commit() localPlayer.copy(id = remotePlayerId) } else localPlayer fp.addToBatch(newPlayer, batch) Tasks.await(batch.commit()) if (newPlayer.id != localPlayer.id) { replacePlayer(newPlayer) } } @Transaction private fun replacePlayer(newPlayer: Player) { playerRepository.delete() playerRepository.save(newPlayer) } private fun exportCollections() { val ft = FirestoreTagRepository(remoteDatabase) val fh = FirestoreHabitRepository(remoteDatabase) val fc = FirestoreChallengeRepository(remoteDatabase) val fr = FirestoreRepeatingQuestRepository(remoteDatabase) val batch = remoteDatabase.batch() ft.addToBatch(tagRepository.findAll(), batch) fh.addToBatch(habitRepository.findAll(), batch) fc.addToBatch(challengeRepository.findAll(), batch) fr.addToBatch(repeatingQuestRepository.findAll(), batch) Tasks.await(batch.commit()) exportDailyChallengesAndQuests() } private fun exportDailyChallengesAndQuests() { val fd = FirestoreDailyChallengeRepository(remoteDatabase) var batch = remoteDatabase.batch() var cnt = 0 dailyChallengeRepository .findAll() .forEach { fd.addToBatch(it, batch) cnt++ if (cnt >= 500) { Tasks.await(batch.commit()) cnt = 0 batch = remoteDatabase.batch() } } val fq = FirestoreQuestRepository(remoteDatabase) questRepository .findAll() .forEach { fq.addToBatch(it, batch) cnt++ if (cnt >= 500) { Tasks.await(batch.commit()) cnt = 0 batch = remoteDatabase.batch() } } Tasks.await(batch.commit()) } }
gpl-3.0
63cb89b4bfada1ccd796a3186bcfffd0
32.909836
114
0.661066
5.06924
false
false
false
false
siarhei-luskanau/android-iot-doorbell
di/di_dagger/di_dagger_common/src/main/kotlin/siarhei/luskanau/iot/doorbell/dagger/common/CommonModule.kt
1
5921
package siarhei.luskanau.iot.doorbell.dagger.common import android.app.Application import android.content.Context import androidx.startup.AppInitializer import androidx.work.WorkManager import dagger.Module import dagger.Provides import siarhei.luskanau.iot.doorbell.common.DefaultDoorbellsDataSource import siarhei.luskanau.iot.doorbell.common.DeviceInfoProvider import siarhei.luskanau.iot.doorbell.common.DoorbellsDataSource import siarhei.luskanau.iot.doorbell.common.ImagesDataSourceFactory import siarhei.luskanau.iot.doorbell.common.ImagesDataSourceFactoryImpl import siarhei.luskanau.iot.doorbell.common.IpAddressProvider import siarhei.luskanau.iot.doorbell.data.AndroidDeviceInfoProvider import siarhei.luskanau.iot.doorbell.data.AndroidIpAddressProvider import siarhei.luskanau.iot.doorbell.data.AndroidThisDeviceRepository import siarhei.luskanau.iot.doorbell.data.AppBackgroundServices import siarhei.luskanau.iot.doorbell.data.ScheduleWorkManagerService import siarhei.luskanau.iot.doorbell.data.repository.CameraRepository import siarhei.luskanau.iot.doorbell.data.repository.DoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.FirebaseDoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.ImageRepository import siarhei.luskanau.iot.doorbell.data.repository.InternalStorageImageRepository import siarhei.luskanau.iot.doorbell.data.repository.JetpackCameraRepository import siarhei.luskanau.iot.doorbell.data.repository.PersistenceRepository import siarhei.luskanau.iot.doorbell.data.repository.StubDoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.StubUptimeRepository import siarhei.luskanau.iot.doorbell.data.repository.ThisDeviceRepository import siarhei.luskanau.iot.doorbell.data.repository.UptimeFirebaseRepository import siarhei.luskanau.iot.doorbell.data.repository.UptimeRepository import siarhei.luskanau.iot.doorbell.persistence.DefaultPersistenceRepository import siarhei.luskanau.iot.doorbell.workmanager.DefaultScheduleWorkManagerService import siarhei.luskanau.iot.doorbell.workmanager.WorkManagerInitializer import javax.inject.Provider import javax.inject.Singleton @Suppress("TooManyFunctions") @Module class CommonModule { @Provides @Singleton fun provideContext(application: Application): Context = application.applicationContext @Provides @Singleton fun provideWorkManager(context: Provider<Context>): WorkManager = AppInitializer.getInstance(context.get()) .initializeComponent(WorkManagerInitializer::class.java) @Provides @Singleton fun provideImageRepository(context: Provider<Context>): ImageRepository = InternalStorageImageRepository(context = context.get()) @Provides @Singleton fun provideDoorbellRepository(thisDeviceRepository: ThisDeviceRepository): DoorbellRepository = if (thisDeviceRepository.isEmulator()) { StubDoorbellRepository() } else { FirebaseDoorbellRepository() } @Provides @Singleton fun providePersistenceRepository(context: Provider<Context>): PersistenceRepository = DefaultPersistenceRepository(context = context.get()) @Provides @Singleton fun provideScheduleWorkManagerService( workManager: Provider<WorkManager> ): ScheduleWorkManagerService = DefaultScheduleWorkManagerService(workManager = { workManager.get() }) @Provides @Singleton fun provideCameraRepository( context: Provider<Context>, imageRepository: Provider<ImageRepository> ): CameraRepository = JetpackCameraRepository( context = context.get(), imageRepository = imageRepository.get() ) @Provides @Singleton fun provideUptimeRepository(thisDeviceRepository: ThisDeviceRepository): UptimeRepository = if (thisDeviceRepository.isEmulator()) { StubUptimeRepository() } else { UptimeFirebaseRepository() } @Provides @Singleton fun provideDoorbellsDataSource( doorbellRepository: Provider<DoorbellRepository> ): DoorbellsDataSource = DefaultDoorbellsDataSource( doorbellRepository = doorbellRepository.get() ) @Provides @Singleton fun provideDeviceInfoProvider(context: Provider<Context>): DeviceInfoProvider = AndroidDeviceInfoProvider(context = context.get()) @Provides @Singleton fun provideIpAddressProvider(): IpAddressProvider = AndroidIpAddressProvider() @Provides @Singleton fun provideImagesDataSourceFactory( doorbellRepository: Provider<DoorbellRepository> ): ImagesDataSourceFactory = ImagesDataSourceFactoryImpl( doorbellRepository = doorbellRepository.get() ) @Provides @Singleton fun provideThisDeviceRepository( context: Provider<Context>, deviceInfoProvider: Provider<DeviceInfoProvider>, cameraRepository: Provider<CameraRepository>, ipAddressProvider: Provider<IpAddressProvider> ): ThisDeviceRepository = AndroidThisDeviceRepository( context = context.get(), deviceInfoProvider = deviceInfoProvider.get(), cameraRepository = cameraRepository.get(), ipAddressProvider = ipAddressProvider.get() ) @Provides @Singleton fun provideAppBackgroundServices( doorbellRepository: Provider<DoorbellRepository>, thisDeviceRepository: Provider<ThisDeviceRepository>, scheduleWorkManagerService: Provider<ScheduleWorkManagerService> ): AppBackgroundServices = AppBackgroundServices( doorbellRepository = doorbellRepository.get(), thisDeviceRepository = thisDeviceRepository.get(), scheduleWorkManagerService = scheduleWorkManagerService.get() ) }
mit
cdb9fd6085113299e0b6f5d95c754338
37.448052
99
0.764736
5.21674
false
false
false
false
deviant-studio/bindingtools
lib/src/main/java/ds/bindingtools/ResBindings.kt
1
2256
package ds.bindingtools import android.app.Activity import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import androidx.annotation.AnyRes import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty inline fun <reified T : Any> Context.res(@AnyRes id: Int): ReadOnlyProperty<Activity, T> = ResourcesDelegate(this, id, T::class) inline fun <reified T : Any> Fragment.res(@AnyRes id: Int): ReadOnlyProperty<Activity, T> = ResourcesDelegate(this.context!!, id, T::class) class ResourcesDelegate<out T : Any>(private val context: Context, private val id: Int, private val cls: KClass<T>) : ReadOnlyProperty<Any, T> { private lateinit var type: String @Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY") override fun getValue(thisRef: Any, property: KProperty<*>): T { type = context.resources.getResourceTypeName(id) with(context.resources) { return when { match("drawable", Drawable::class) -> ContextCompat.getDrawable(context, id) match("bool", Boolean::class) -> getBoolean(id) match("integer", Int::class) -> getInteger(id) match("color", Int::class) -> ContextCompat.getColor(context, id) match("color", ColorStateList::class) -> ContextCompat.getColorStateList(context, id) match("dimen", Float::class) -> getDimension(id) match("dimen", Int::class) -> getDimension(id) match("string", String::class) -> getString(id) match("string", CharSequence::class) -> getText(id) match("array", IntArray::class) -> getIntArray(id) match("array", Array<Int>::class) -> getIntArray(id) match("array", Array<String>::class) -> getStringArray(id) match("array", Array<CharSequence>::class) -> getTextArray(id) else -> throw IllegalArgumentException() } as T } } private fun match(desiredType: String, desiredClass: KClass<*>) = desiredType == type && desiredClass.java == cls.java }
apache-2.0
11f3d8259241d7c4f1498aec0cb4561a
49.133333
144
0.659574
4.380583
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenEncodingConfigurator.kt
4
5228
// 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.idea.maven.importing import com.intellij.openapi.application.ReadAction import com.intellij.openapi.components.service import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore.fileToUrl import com.intellij.openapi.vfs.encoding.EncodingProjectManager import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl import com.intellij.openapi.vfs.pointers.VirtualFilePointer import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager import com.intellij.util.io.URLUtil.urlToPath import org.jetbrains.annotations.ApiStatus import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectChanges import org.jetbrains.idea.maven.utils.MavenLog import java.io.File import java.nio.charset.Charset import java.nio.charset.UnsupportedCharsetException /** * @author Sergey Evdokimov */ @ApiStatus.Internal class MavenEncodingConfigurator : MavenImporter("", ""), MavenWorkspaceConfigurator { private val PREPARED_MAPPER = Key.create<EncodingMapper>("ENCODING_MAPPER") override fun isApplicable(mavenProject: MavenProject): Boolean { return true } override fun isMigratedToConfigurator(): Boolean { return true } override fun beforeModelApplied(context: MavenWorkspaceConfigurator.MutableModelContext) { val allMavenProjects = context.mavenProjectsWithModules.filter { it.hasChanges() }.map { it.mavenProject } val mapper = mapEncodings(allMavenProjects, context.project) PREPARED_MAPPER.set(context, mapper) } override fun afterModelApplied(context: MavenWorkspaceConfigurator.AppliedModelContext) { PREPARED_MAPPER.get(context)?.applyCollectedInfo() } override fun postProcess(module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider) { mapEncodings(sequenceOf(mavenProject), module.project).applyCollectedInfo() } private fun mapEncodings(mavenProjects: Sequence<MavenProject>, project: Project): EncodingMapper { val encodingMapper = EncodingMapper(project) mavenProjects.forEach { mavenProject -> ReadAction.compute<Unit, Throwable> { fillSourceEncoding(mavenProject, encodingMapper) } ReadAction.compute<Unit, Throwable> { fillResourceEncoding(project, mavenProject, encodingMapper) } } return encodingMapper } private class EncodingMapper(project: Project) { private val newPointerMappings = LinkedHashMap<VirtualFilePointer, Charset>() private val oldPointerMappings = LinkedHashMap<VirtualFilePointer, Charset>() private val encodingManager = (EncodingProjectManager.getInstance(project) as EncodingProjectManagerImpl) fun processDir(directory: String, charset: Charset) { val dirVfile = LocalFileSystem.getInstance().findFileByIoFile(File(directory)) val pointer = if (dirVfile != null) { service<VirtualFilePointerManager>().create(dirVfile, encodingManager, null) } else { service<VirtualFilePointerManager>().create(fileToUrl(File(directory).absoluteFile), encodingManager, null) } newPointerMappings[pointer] = charset encodingManager.allPointersMappings.forEach { val filePointer = it.key if (FileUtil.isAncestor(directory, urlToPath(filePointer.url), false) || newPointerMappings.containsKey(filePointer)) { newPointerMappings[filePointer] = charset oldPointerMappings.remove(filePointer) } else { oldPointerMappings[filePointer] = it.value } } } fun applyCollectedInfo() { if (newPointerMappings.isEmpty()) { return } val pointerMapping = newPointerMappings + oldPointerMappings encodingManager.setPointerMapping(pointerMapping) } } private fun fillResourceEncoding(project: Project, mavenProject: MavenProject, encodingMapper: EncodingMapper) { mavenProject.getResourceEncoding(project)?.let(this::getCharset)?.let { charset -> mavenProject.resources.map { it.directory }.forEach { encodingMapper.processDir(it, charset) } } } private fun fillSourceEncoding(mavenProject: MavenProject, encodingMapper: EncodingMapper) { mavenProject.sourceEncoding?.let(this::getCharset)?.let { charset -> mavenProject.sources.forEach { encodingMapper.processDir(it, charset) } } } private fun getCharset(name: String): Charset? { try { return Charset.forName(name) } catch (e: UnsupportedCharsetException) { MavenLog.LOG.warn("Charset ${name} is not supported") return null } } }
apache-2.0
26cf3dc0e80a97d749f31cf88e1ebc29
37.733333
120
0.732976
4.836263
false
false
false
false
GunoH/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradlePropertiesUtil.kt
6
4535
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("GradlePropertiesUtil") package org.jetbrains.plugins.gradle.util import com.intellij.openapi.externalSystem.util.environment.Environment import com.intellij.openapi.project.Project import com.intellij.util.io.exists import com.intellij.util.io.inputStream import com.intellij.util.io.isFile import org.jetbrains.plugins.gradle.settings.GradleLocalSettings import org.jetbrains.plugins.gradle.util.GradleProperties.EMPTY import org.jetbrains.plugins.gradle.util.GradleProperties.GradleProperty import java.io.IOException import java.nio.file.Path import java.nio.file.Paths import java.util.* const val USER_HOME = "user.home" const val GRADLE_CACHE_DIR_NAME = ".gradle" const val PROPERTIES_FILE_NAME = "gradle.properties" const val GRADLE_JAVA_HOME_PROPERTY = "org.gradle.java.home" const val GRADLE_LOGGING_LEVEL_PROPERTY = "org.gradle.logging.level" fun getGradleProperties(project: Project, externalProjectPath: Path): GradleProperties { return findAndMergeProperties(getPossiblePropertiesFiles(project, externalProjectPath)) } fun getGradleProperties(serviceDirectoryStr: String?, externalProjectPath: Path): GradleProperties { return findAndMergeProperties(getPossiblePropertiesFiles(serviceDirectoryStr, externalProjectPath)) } private fun findAndMergeProperties(possiblePropertiesFiles: List<Path>): GradleProperties { return possiblePropertiesFiles .asSequence() .map { it.toAbsolutePath().normalize() } .map(::loadGradleProperties) .reduce(::mergeGradleProperties) } private fun getPossiblePropertiesFiles(project: Project, externalProjectPath: Path): List<Path> { return listOfNotNull( getGradleServiceDirectoryPath(project), getGradleUserHomePropertiesPath(), getGradleProjectPropertiesPath(externalProjectPath) ) } private fun getPossiblePropertiesFiles(serviceDirectoryStr: String?, externalProjectPath: Path): List<Path> { return listOfNotNull( getGradleServiceDirectoryPath(serviceDirectoryStr), getGradleUserHomePropertiesPath(), getGradleProjectPropertiesPath(externalProjectPath) ) } private fun getGradleServiceDirectoryPath(project: Project): Path? { val gradleUserHome = GradleLocalSettings.getInstance(project).gradleUserHome ?: return null return Paths.get(gradleUserHome, PROPERTIES_FILE_NAME) } private fun getGradleServiceDirectoryPath(serviceDirectoryStr: String?): Path? { return serviceDirectoryStr?.let { Paths.get(serviceDirectoryStr, PROPERTIES_FILE_NAME) } } fun getGradleUserHomePropertiesPath(): Path? { val gradleUserHome = Environment.getVariable(GradleConstants.SYSTEM_DIRECTORY_PATH_KEY) if (gradleUserHome != null) { return Paths.get(gradleUserHome, PROPERTIES_FILE_NAME) } val userHome = Environment.getProperty(USER_HOME) if (userHome != null) { return Paths.get(userHome, GRADLE_CACHE_DIR_NAME, PROPERTIES_FILE_NAME) } return null } private fun getGradleProjectPropertiesPath(externalProjectPath: Path): Path { return externalProjectPath.resolve(PROPERTIES_FILE_NAME) } private fun loadGradleProperties(propertiesPath: Path): GradleProperties { val properties = loadProperties(propertiesPath) ?: return EMPTY val javaHome = properties.getProperty(GRADLE_JAVA_HOME_PROPERTY) val javaHomeProperty = javaHome?.let { GradleProperty(it, propertiesPath.toString()) } val logLevel = properties.getProperty(GRADLE_LOGGING_LEVEL_PROPERTY) val logLevelProperty = logLevel?.let { GradleProperty(it, propertiesPath.toString()) } return GradlePropertiesImpl(javaHomeProperty, logLevelProperty) } private fun loadProperties(propertiesFile: Path): Properties? { if (!propertiesFile.isFile() || !propertiesFile.exists()) { return null } val properties = Properties() try { propertiesFile.inputStream().use { properties.load(it) } } catch (_: IOException) { return null } return properties } private fun mergeGradleProperties(most: GradleProperties, other: GradleProperties): GradleProperties { return when { most is EMPTY -> other other is EMPTY -> most else -> GradlePropertiesImpl(most.javaHomeProperty ?: other.javaHomeProperty, most.gradleLoggingLevel ?: other.gradleLoggingLevel) } } private data class GradlePropertiesImpl(override val javaHomeProperty: GradleProperty<String>?, override val gradleLoggingLevel: GradleProperty<String>?) : GradleProperties
apache-2.0
cfe72cebfbeea3ff27919d8e70b9f106
37.440678
120
0.786108
4.580808
false
false
false
false
binaryroot/AndroidArchitecture
app/src/main/java/com/androidarchitecture/utility/NetworkUtils.kt
1
690
package com.androidarchitecture.utility import java.net.HttpURLConnection import javax.inject.Singleton import okhttp3.Response @Singleton class NetworkUtils { fun isNotAuthorized(response: Response): Boolean { return response.code() == HttpURLConnection.HTTP_FORBIDDEN || response.code() == HttpURLConnection.HTTP_UNAUTHORIZED } /** * This method coverts url from 'https://www.example.com/' to 'https://www.example.com' * @return converted url */ fun formatToBaseUrl(str: String): String { var url = str if (str[str.length - 1] == '/') { url = str.substring(0, str.length - 1) } return url } }
mit
95fe970fff567f2fb1a39f9ae5bc17eb
23.642857
124
0.644928
4.131737
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/data/remote/RemoteViewModel.kt
1
2704
package org.dvbviewer.controller.data.remote import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.apache.commons.collections4.CollectionUtils import org.apache.commons.lang3.StringUtils import org.dvbviewer.controller.data.api.ApiResponse import org.dvbviewer.controller.data.entities.DVBTarget import org.dvbviewer.controller.data.entities.DVBViewerPreferences class RemoteViewModel internal constructor(private val mRepository: RemoteRepository, private val prefs: DVBViewerPreferences) : ViewModel() { private var data: MutableLiveData<ApiResponse<List<DVBTarget>>> = MutableLiveData() private val gson = Gson() private val type = object : TypeToken<List<DVBTarget>>() {}.type fun getTargets(force: Boolean = false): MutableLiveData<ApiResponse<List<DVBTarget>>> { if (data.value == null || force) { fetchTargets() } return data } private fun fetchTargets() { viewModelScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT) { var apiResponse: ApiResponse<List<DVBTarget>> = ApiResponse.error(null, null) async(Dispatchers.Default) { apiResponse = try { var targets = mRepository.getTargets() if (CollectionUtils.isNotEmpty(targets)) { prefs.prefs.edit() .putString(DVBViewerPreferences.KEY_RS_CLIENTS, gson.toJson(targets)) .apply() } else { val prefValue = prefs.prefs.getString(DVBViewerPreferences.KEY_RS_CLIENTS, "") if (StringUtils.isNotBlank(prefValue)) { try { targets = gson.fromJson<List<DVBTarget>>(prefValue, type) } catch (e: Exception) { Log.e(TAG, "Error reading Targets vom prefs", e) } } } ApiResponse.success(targets) } catch (e: Exception) { Log.e(TAG, "Error getting recording list", e) ApiResponse.error(e, null) } }.await() data.value = apiResponse } } companion object { private const val TAG = "RemoteViewModel" } }
apache-2.0
9a81c60e4aafaaf50b5edaba30dd443a
38.779412
142
0.606509
5.140684
false
false
false
false
emoji-gen/Emoji-Android
app/src/main/java/moe/pine/emoji/view/generator/RegisterDialogView.kt
1
2395
package moe.pine.emoji.view.generator import android.content.Context import android.support.v4.app.Fragment import android.util.AttributeSet import android.widget.LinearLayout import com.squareup.otto.Subscribe import io.realm.Realm import io.realm.Sort import kotlinx.android.synthetic.main.dialog_register.view.* import moe.pine.emoji.adapter.generator.GeneratorTeamListAdapter import moe.pine.emoji.components.generator.EmojiRegisterComponent import moe.pine.emoji.components.generator.InputChangedWatcherComponent import moe.pine.emoji.model.event.TeamAddedEvent import moe.pine.emoji.model.event.TeamDeleteEvent import moe.pine.emoji.model.realm.SlackTeam import moe.pine.emoji.util.eventBus /** * View for register dialog * Created by pine on May 13, 2017. */ class RegisterDialogView : LinearLayout { private lateinit var realm: Realm var previewUri: String = "" var downloadUri: String = "" var fragment: Fragment? = null private val inputWatcher by lazy { InputChangedWatcherComponent(this) } private val register by lazy { EmojiRegisterComponent(this) } private val teams: List<SlackTeam> get() = this.realm.where(SlackTeam::class.java).findAllSorted("team", Sort.ASCENDING) constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onFinishInflate() { super.onFinishInflate() if (this.isInEditMode) return this.inputWatcher.onFinishInflate() this.register.onFinishInflate() this.realm = Realm.getDefaultInstance() this.eventBus.register(this) val adapter = GeneratorTeamListAdapter(this.context) this.spinner_generator_teams.adapter = adapter this.update() } override fun onDetachedFromWindow() { this.eventBus.unregister(this) this.realm.close() super.onDetachedFromWindow() } @Subscribe fun onTeamAdded(event: TeamAddedEvent) { this.update() } @Subscribe fun onTeamDeleted(event: TeamDeleteEvent) { this.update() } private fun update() { val adapter = this.spinner_generator_teams.adapter as GeneratorTeamListAdapter adapter.replaceAll(this.teams) } }
mit
e3a092d2ec18ee06f88d030bee92c4fd
30.946667
113
0.729854
4.338768
false
false
false
false
neva-dev/javarel-framework
processing/scheduler/src/main/kotlin/com/neva/javarel/processing/scheduler/api/BaseSchedule.kt
1
1469
package com.neva.javarel.processing.scheduler.api import org.quartz.* import java.util.* import kotlin.reflect.KClass abstract class BaseSchedule<T : Job> : Schedule { override val job: JobDetail get() = JobBuilder.newJob(jobType.java).build() abstract val jobType: KClass<T> override val trigger: Trigger get() { val result = TriggerBuilder.newTrigger() if (startAt != null) { result.startAt(startAt) } if (endAt != null) { result.endAt(endAt) } return result.withSchedule(schedule()).build() } protected open val startAt: Date? = null protected open val endAt: Date? = null abstract fun schedule(): ScheduleBuilder<*> protected fun cron(expression: String): ScheduleBuilder<*> = CronScheduleBuilder.cronSchedule(expression) protected fun repeat(how: (SimpleScheduleBuilder) -> ScheduleBuilder<*>): ScheduleBuilder<*> { return how(SimpleScheduleBuilder.simpleSchedule().repeatForever()) } protected fun daily(how: (DailyTimeIntervalScheduleBuilder) -> ScheduleBuilder<*>): ScheduleBuilder<*> { return how(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule()) } protected fun calendar(how: (CalendarIntervalScheduleBuilder) -> ScheduleBuilder<*>): ScheduleBuilder<*> { return how(CalendarIntervalScheduleBuilder.calendarIntervalSchedule()) } }
apache-2.0
f33923c74dad028458e1da45e18b1bf5
30.276596
110
0.668482
4.693291
false
false
false
false
hantsy/spring-reactive-sample
kotlin-dsl/src/main/kotlin/com/example/demo/PostRepository.kt
1
637
package com.example.demo import org.springframework.data.mongodb.core.ReactiveMongoTemplate import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query class PostRepository(private val template: ReactiveMongoTemplate) { fun findAll() = template.findAll(Post::class.java) fun findById(id: String) = template.findById(id, Post::class.java) fun save(post: Post) = template.save(post) fun deleteAll() = template.remove(Query(), Post::class.java) fun deleteById(id: String) = template.remove(Query().addCriteria(Criteria.where("id").`is`(id)), Post::class.java) }
gpl-3.0
527ad644894c81c4cf80e7baa0c17bf0
48.076923
118
0.762951
3.747059
false
false
false
false
cascheberg/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationFactory.kt
2
16507
package org.thoughtcrime.securesms.notifications.v2 import android.annotation.TargetApi import android.app.Notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.media.AudioAttributes import android.media.AudioManager import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.TransactionTooLargeException import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.MainActivity import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.conversation.ConversationIntents import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.database.model.InMemoryMessageRecord import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.notifications.NotificationChannels import org.thoughtcrime.securesms.notifications.NotificationIds import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.BubbleUtil import org.thoughtcrime.securesms.util.ConversationUtil import org.thoughtcrime.securesms.util.ServiceUtil import org.thoughtcrime.securesms.util.TextSecurePreferences private val TAG = Log.tag(NotificationFactory::class.java) /** * Given a notification state consisting of conversations of messages, show appropriate system notifications. */ object NotificationFactory { fun notify( context: Context, state: NotificationStateV2, visibleThreadId: Long, targetThreadId: Long, defaultBubbleState: BubbleUtil.BubbleState, lastAudibleNotification: Long, notificationConfigurationChanged: Boolean, alertOverrides: Set<Long>, previousState: NotificationStateV2 ): Set<Long> { if (state.isEmpty) { Log.d(TAG, "State is empty, bailing") return emptySet() } val nonVisibleThreadCount: Int = state.conversations.count { it.threadId != visibleThreadId } return if (Build.VERSION.SDK_INT < 24) { notify19( context = context, state = state, visibleThreadId = visibleThreadId, targetThreadId = targetThreadId, defaultBubbleState = defaultBubbleState, lastAudibleNotification = lastAudibleNotification, alertOverrides = alertOverrides, nonVisibleThreadCount = nonVisibleThreadCount ) } else { notify24( context = context, state = state, visibleThreadId = visibleThreadId, targetThreadId = targetThreadId, defaultBubbleState = defaultBubbleState, lastAudibleNotification = lastAudibleNotification, notificationConfigurationChanged = notificationConfigurationChanged, alertOverrides = alertOverrides, nonVisibleThreadCount = nonVisibleThreadCount, previousState = previousState ) } } private fun notify19( context: Context, state: NotificationStateV2, visibleThreadId: Long, targetThreadId: Long, defaultBubbleState: BubbleUtil.BubbleState, lastAudibleNotification: Long, alertOverrides: Set<Long>, nonVisibleThreadCount: Int ): Set<Long> { val threadsThatNewlyAlerted: MutableSet<Long> = mutableSetOf() state.conversations.find { it.threadId == visibleThreadId }?.let { conversation -> if (conversation.hasNewNotifications()) { Log.internal().i(TAG, "Thread is visible, notifying in thread. notificationId: ${conversation.notificationId}") notifyInThread(context, conversation.recipient, lastAudibleNotification) } } if (nonVisibleThreadCount == 1) { state.conversations.first { it.threadId != visibleThreadId }.let { conversation -> notifyForConversation( context = context, conversation = conversation, targetThreadId = targetThreadId, defaultBubbleState = defaultBubbleState, shouldAlert = (conversation.hasNewNotifications() || alertOverrides.contains(conversation.threadId)) && !conversation.mostRecentNotification.individualRecipient.isSelf ) if (conversation.hasNewNotifications()) { threadsThatNewlyAlerted += conversation.threadId } } } else if (nonVisibleThreadCount > 1) { val nonVisibleConversations: List<NotificationConversation> = state.getNonVisibleConversation(visibleThreadId) threadsThatNewlyAlerted += nonVisibleConversations.filter { it.hasNewNotifications() }.map { it.threadId } notifySummary(context = context, state = state.copy(conversations = nonVisibleConversations)) } return threadsThatNewlyAlerted } @TargetApi(24) private fun notify24( context: Context, state: NotificationStateV2, visibleThreadId: Long, targetThreadId: Long, defaultBubbleState: BubbleUtil.BubbleState, lastAudibleNotification: Long, notificationConfigurationChanged: Boolean, alertOverrides: Set<Long>, nonVisibleThreadCount: Int, previousState: NotificationStateV2 ): Set<Long> { val threadsThatNewlyAlerted: MutableSet<Long> = mutableSetOf() state.conversations.forEach { conversation -> if (conversation.threadId == visibleThreadId && conversation.hasNewNotifications()) { Log.internal().i(TAG, "Thread is visible, notifying in thread. notificationId: ${conversation.notificationId}") notifyInThread(context, conversation.recipient, lastAudibleNotification) } else if (notificationConfigurationChanged || conversation.hasNewNotifications() || alertOverrides.contains(conversation.threadId) || !conversation.hasSameContent(previousState.getConversation(conversation.threadId))) { if (conversation.hasNewNotifications()) { threadsThatNewlyAlerted += conversation.threadId } notifyForConversation( context = context, conversation = conversation, targetThreadId = targetThreadId, defaultBubbleState = defaultBubbleState, shouldAlert = (conversation.hasNewNotifications() || alertOverrides.contains(conversation.threadId)) && !conversation.mostRecentNotification.individualRecipient.isSelf ) } } if (nonVisibleThreadCount > 1 || ServiceUtil.getNotificationManager(context).isDisplayingSummaryNotification()) { notifySummary(context = context, state = state.copy(conversations = state.getNonVisibleConversation(visibleThreadId))) } return threadsThatNewlyAlerted } private fun notifyForConversation( context: Context, conversation: NotificationConversation, targetThreadId: Long, defaultBubbleState: BubbleUtil.BubbleState, shouldAlert: Boolean ) { if (conversation.notificationItems.isEmpty()) { return } val builder: NotificationBuilder = NotificationBuilder.create(context) builder.apply { setSmallIcon(R.drawable.ic_notification) setColor(ContextCompat.getColor(context, R.color.core_ultramarine)) setCategory(NotificationCompat.CATEGORY_MESSAGE) setGroup(MessageNotifierV2.NOTIFICATION_GROUP) setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) setChannelId(conversation.getChannelId(context)) setContentTitle(conversation.getContentTitle(context)) setLargeIcon(conversation.getContactLargeIcon(context).toLargeBitmap(context)) addPerson(conversation.recipient) setShortcutId(ConversationUtil.getShortcutId(conversation.recipient)) setContentInfo(conversation.messageCount.toString()) setNumber(conversation.messageCount) setContentText(conversation.getContentText(context)) setContentIntent(conversation.getPendingIntent(context)) setDeleteIntent(conversation.getDeleteIntent(context)) setSortKey(conversation.sortKey.toString()) setWhen(conversation) addReplyActions(conversation) setOnlyAlertOnce(!shouldAlert) addMessages(conversation) setPriority(TextSecurePreferences.getNotificationPriority(context)) setLights() setAlarms(conversation.recipient) setTicker(conversation.mostRecentNotification.getStyledPrimaryText(context, true)) setBubbleMetadata(conversation, if (targetThreadId == conversation.threadId) defaultBubbleState else BubbleUtil.BubbleState.HIDDEN) } if (conversation.isOnlyContactJoinedEvent) { builder.addTurnOffJoinedNotificationsAction(conversation.getTurnOffJoinedNotificationsIntent(context)) } val notificationId: Int = if (Build.VERSION.SDK_INT < 24) NotificationIds.MESSAGE_SUMMARY else conversation.notificationId NotificationManagerCompat.from(context).safelyNotify(context, conversation.recipient, notificationId, builder.build()) } private fun notifySummary(context: Context, state: NotificationStateV2) { if (state.messageCount == 0) { return } val builder: NotificationBuilder = NotificationBuilder.create(context) builder.apply { setSmallIcon(R.drawable.ic_notification) setColor(ContextCompat.getColor(context, R.color.core_ultramarine)) setCategory(NotificationCompat.CATEGORY_MESSAGE) setGroup(MessageNotifierV2.NOTIFICATION_GROUP) setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) setChannelId(NotificationChannels.getMessagesChannel(context)) setContentTitle(context.getString(R.string.app_name)) setContentIntent(PendingIntent.getActivity(context, 0, MainActivity.clearTop(context), 0)) setGroupSummary(true) setSubText(context.getString(R.string.MessageNotifier_d_new_messages_in_d_conversations, state.messageCount, state.threadCount)) setContentInfo(state.messageCount.toString()) setNumber(state.messageCount) setSummaryContentText(state.mostRecentSender) setDeleteIntent(state.getDeleteIntent(context)) setWhen(state.mostRecentNotification) addMarkAsReadAction(state) addMessages(state) setOnlyAlertOnce(!state.notificationItems.any { it.isNewNotification }) setPriority(TextSecurePreferences.getNotificationPriority(context)) setLights() setAlarms(state.mostRecentSender) setTicker(state.mostRecentNotification?.getStyledPrimaryText(context, true)) } Log.d(TAG, "showing summary notification") NotificationManagerCompat.from(context).safelyNotify(context, null, NotificationIds.MESSAGE_SUMMARY, builder.build()) } private fun notifyInThread(context: Context, recipient: Recipient, lastAudibleNotification: Long) { if (!SignalStore.settings().isMessageNotificationsInChatSoundsEnabled || ServiceUtil.getAudioManager(context).ringerMode != AudioManager.RINGER_MODE_NORMAL || (System.currentTimeMillis() - lastAudibleNotification) < MessageNotifierV2.MIN_AUDIBLE_PERIOD_MILLIS ) { return } val uri: Uri = if (NotificationChannels.supported()) { NotificationChannels.getMessageRingtone(context, recipient) ?: NotificationChannels.getMessageRingtone(context) } else { recipient.messageRingtone ?: SignalStore.settings().messageNotificationSound } if (uri.toString().isEmpty()) { Log.d(TAG, "ringtone uri is empty") return } val ringtone = RingtoneManager.getRingtone(context, uri) if (ringtone == null) { Log.w(TAG, "ringtone is null") return } if (Build.VERSION.SDK_INT >= 21) { ringtone.audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) .build() } else { @Suppress("DEPRECATION") ringtone.streamType = AudioManager.STREAM_NOTIFICATION } ringtone.play() } fun notifyMessageDeliveryFailed(context: Context, recipient: Recipient, threadId: Long, visibleThread: Long) { if (threadId == visibleThread) { notifyInThread(context, recipient, 0) return } val intent: Intent = ConversationIntents.createBuilder(context, recipient.id, threadId) .build() .makeUniqueToPreventMerging() val builder: NotificationBuilder = NotificationBuilder.create(context) builder.apply { setSmallIcon(R.drawable.ic_notification) setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.ic_action_warning_red)) setContentTitle(context.getString(R.string.MessageNotifier_message_delivery_failed)) setContentText(context.getString(R.string.MessageNotifier_failed_to_deliver_message)) setTicker(context.getString(R.string.MessageNotifier_error_delivering_message)) setContentIntent(PendingIntent.getActivity(context, 0, intent, 0)) setAutoCancel(true) setAlarms(recipient) setChannelId(NotificationChannels.FAILURES) } NotificationManagerCompat.from(context).safelyNotify(context, recipient, threadId.toInt(), builder.build()) } fun notifyProofRequired(context: Context, recipient: Recipient, threadId: Long, visibleThread: Long) { if (threadId == visibleThread) { notifyInThread(context, recipient, 0) return } val intent: Intent = ConversationIntents.createBuilder(context, recipient.id, threadId) .build() .makeUniqueToPreventMerging() val builder: NotificationBuilder = NotificationBuilder.create(context) builder.apply { setSmallIcon(R.drawable.ic_notification) setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.ic_info_outline)) setContentTitle(context.getString(R.string.MessageNotifier_message_delivery_paused)) setContentText(context.getString(R.string.MessageNotifier_verify_to_continue_messaging_on_signal)) setContentIntent(PendingIntent.getActivity(context, 0, intent, 0)) setOnlyAlertOnce(true) setAutoCancel(true) setAlarms(recipient) setChannelId(NotificationChannels.FAILURES) } NotificationManagerCompat.from(context).safelyNotify(context, recipient, threadId.toInt(), builder.build()) } @JvmStatic fun notifyToBubbleConversation(context: Context, recipient: Recipient, threadId: Long) { val builder: NotificationBuilder = NotificationBuilder.create(context) val conversation = NotificationConversation( recipient = recipient, threadId = threadId, notificationItems = listOf( MessageNotification( threadRecipient = recipient, record = InMemoryMessageRecord.ForceConversationBubble(recipient, threadId) ) ) ) builder.apply { setSmallIcon(R.drawable.ic_notification) setColor(ContextCompat.getColor(context, R.color.core_ultramarine)) setCategory(NotificationCompat.CATEGORY_MESSAGE) setGroup(MessageNotifierV2.NOTIFICATION_GROUP) setChannelId(conversation.getChannelId(context)) setContentTitle(conversation.getContentTitle(context)) setLargeIcon(conversation.getContactLargeIcon(context).toLargeBitmap(context)) addPerson(conversation.recipient) setShortcutId(ConversationUtil.getShortcutId(conversation.recipient)) addMessages(conversation) setBubbleMetadata(conversation, BubbleUtil.BubbleState.SHOWN) } Log.d(TAG, "Posting Notification for requested bubble") NotificationManagerCompat.from(context).safelyNotify(context, recipient, conversation.notificationId, builder.build()) } private fun NotificationManagerCompat.safelyNotify(context: Context, threadRecipient: Recipient?, notificationId: Int, notification: Notification) { try { notify(notificationId, notification) Log.internal().i(TAG, "Posted notification: $notification") } catch (e: SecurityException) { Log.i(TAG, "Security exception when posting notification, clearing ringtone") if (threadRecipient != null) { SignalExecutors.BOUNDED.execute { DatabaseFactory.getRecipientDatabase(context).setMessageRingtone(threadRecipient.id, null) NotificationChannels.updateMessageRingtone(context, threadRecipient, null) } } } catch (runtimeException: RuntimeException) { if (runtimeException.cause is TransactionTooLargeException) { Log.e(TAG, "Transaction too large", runtimeException) } else { throw runtimeException } } } }
gpl-3.0
d916ffe34ab00bc222528f4f69eb5512
40.370927
226
0.748349
4.86645
false
false
false
false
google/ground-android
ground/src/main/java/com/google/android/ground/ui/home/BottomSheetState.kt
1
1205
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.ui.home import com.google.android.ground.model.locationofinterest.LocationOfInterest class BottomSheetState private constructor( val visibility: Visibility, val locationOfInterest: LocationOfInterest? = null ) { enum class Visibility { VISIBLE, HIDDEN } val isVisible: Boolean get() = Visibility.VISIBLE == visibility companion object { @JvmStatic fun visible(locationOfInterest: LocationOfInterest) = BottomSheetState(Visibility.VISIBLE, locationOfInterest) @JvmStatic fun hidden() = BottomSheetState(Visibility.HIDDEN) } }
apache-2.0
eef420cb63b6fc31710560df186eac91
27.690476
76
0.746888
4.513109
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/ClassPropertiesOverrides.kt
12
692
// MODE: inheritors <# block [ 1 Inheritor] #> abstract class SomeClass { <# block [ 1 Override] #> abstract val someAbstractProperty: Int <# block [ 2 Overrides] #> open val nonAbstractProperty: Int = 10 open val notToBeOverriddenProperty: Int = 10 } <# block [ 1 Inheritor] #> open class DerivedClassA : SomeClass() { override val someAbstractProperty: Int = 5 <# block [ 1 Override] #> override val nonAbstractProperty: Int = 15 // NOTE that DerivedClassB overrides both getter and setter but counted once } class DerivedClassB : DerivedClassA() { override var nonAbstractProperty: Int = 15 get() = 20 set(value) {field = value / 2} }
apache-2.0
30d8cd86347776b34dfc015f6fd8bd7d
29.130435
123
0.671965
4.193939
false
false
false
false
cdcalc/cdcalc
core/src/test/kotlin/com/github/cdcalc/CutReleaseBranchTest.kt
1
1369
package com.github.cdcalc import com.github.cdcalc.git.taggedCommits import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Constants import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class CutReleaseBranchTest { lateinit var sut: CutReleaseBranch lateinit var git: Git @BeforeEach fun before() { git = initGitFlow() sut = CutReleaseBranch(git) } @AfterEach fun after() { git.close() } @Test() fun shouldThrowIfTryingToCreateReleaseBranchFromDevelop() { git.checkout("master") assertThrows<InvalidBranchException> { sut.cutReleaseBranch() } } @Test fun shouldBeAbleToCutReleaseBranch() { sut.cutReleaseBranch() val releaseBranch = sut.git.branchList().call().single { it.name == "refs/heads/release/1.1.0" } val head = git.repository.resolve(Constants.HEAD) assertEquals(head, releaseBranch.objectId) } @Test fun shouldCreatePreReleaseTag() { sut.cutReleaseBranch() val head = git.repository.resolve(Constants.HEAD) val commitTag = git.taggedCommits()[head] assertEquals("refs/tags/v1.1.0-rc.0", commitTag!!.tagName) } }
mit
b7d8fa38d42c8510656ca8b890467f5e
25.326923
71
0.686633
3.867232
false
true
false
false
JesusM/FingerprintManager
sample/src/main/java/jesusm/com/fingerprintmanager/sample/MainActivity.kt
1
6388
package jesusm.com.fingerprintmanager.sample import android.os.Bundle import android.support.annotation.StyleRes import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import com.jesusm.kfingerprintmanager.KFingerprintManager import com.jesusm.kfingerprintmanager.utils.bind class MainActivity : AppCompatActivity() { private val KEY = "my_key" private var messageTextView = bind<TextView>(R.id.message) private var messageToBeEncryptedEditText = bind<EditText>(R.id.editText) private var authenticateButton = bind<Button>(R.id.buttonAuthenticate) private var encryptTextButton = bind<Button>(R.id.buttonEncrypt) private var decryptTextButton = bind<Button>(R.id.buttonDecrypt) @StyleRes private var dialogTheme: Int = 0 private var messageToDecrypt: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) selectView(findViewById(R.id.buttonDialogThemeLight)) initClickListeners() } private fun initClickListeners() { findViewById<Button>(R.id.buttonDialogThemeLight).setOnClickListener { v -> selectView(v) deselectView(findViewById(R.id.buttonDialogThemeDark)) dialogTheme = R.style.DialogThemeLight } findViewById<Button>(R.id.buttonDialogThemeDark).setOnClickListener { v -> selectView(v) deselectView(findViewById(R.id.buttonDialogThemeLight)) dialogTheme = R.style.DialogThemeDark } authenticateButton.value.setOnClickListener { createFingerprintManagerInstance().authenticate(object : KFingerprintManager.AuthenticationCallback { override fun onAuthenticationFailedWithHelp(help: String?) { messageTextView.value.text = help } override fun onAuthenticationSuccess() { messageTextView.value.text = "Successfully authenticated" } override fun onSuccessWithManualPassword(password: String) { messageTextView.value.text = "Manual password: " + password } override fun onFingerprintNotRecognized() { messageTextView.value.text = "Fingerprint not recognized" } override fun onFingerprintNotAvailable() { messageTextView.value.text = "Fingerprint not available" } override fun onCancelled() { messageTextView.value.text = "Operation cancelled by user" } }, supportFragmentManager) } encryptTextButton.value.setOnClickListener { messageToDecrypt = messageToBeEncryptedEditText.value.text.toString() createFingerprintManagerInstance().encrypt(messageToDecrypt, object : KFingerprintManager.EncryptionCallback { override fun onFingerprintNotRecognized() { messageTextView.value.text = "Fingerprint not recognized" } override fun onAuthenticationFailedWithHelp(help: String?) { messageTextView.value.text = help } override fun onFingerprintNotAvailable() { messageTextView.value.text = "Fingerprint not available" } override fun onEncryptionSuccess(messageEncrypted: String) { val message = getString(R.string.encrypt_message_success, messageEncrypted) messageTextView.value.text = message messageToBeEncryptedEditText.value.setText(messageEncrypted) encryptTextButton.value.visibility = View.GONE decryptTextButton.value.visibility = View.VISIBLE } override fun onEncryptionFailed() { messageTextView.value.text = "Encryption failed" } override fun onCancelled() { messageTextView.value.text = "Operation cancelled by user" } }, supportFragmentManager) } decryptTextButton.value.setOnClickListener { messageToDecrypt = messageToBeEncryptedEditText.value.text.toString() createFingerprintManagerInstance().decrypt(messageToDecrypt, object : KFingerprintManager.DecryptionCallback { override fun onDecryptionSuccess(messageDecrypted: String) { val message = getString(R.string.decrypt_message_success, messageDecrypted) messageTextView.value.text = message messageToBeEncryptedEditText.value.setText("") decryptTextButton.value.visibility = View.GONE encryptTextButton.value.visibility = View.VISIBLE } override fun onDecryptionFailed() { messageTextView.value.text = "Decryption failed" } override fun onFingerprintNotRecognized() { messageTextView.value.text = "Fingerprint not recognized" } override fun onAuthenticationFailedWithHelp(help: String?) { messageTextView.value.text = help } override fun onFingerprintNotAvailable() { messageTextView.value.text = "Fingerprint not available" } override fun onCancelled() { messageTextView.value.text = "Operation cancelled by user" } }, supportFragmentManager) } } private fun createFingerprintManagerInstance(): KFingerprintManager { val fingerprintManager = KFingerprintManager(this, KEY) fingerprintManager.setAuthenticationDialogStyle(dialogTheme) return fingerprintManager } private fun selectView(view: View) { view.apply { isSelected = true elevation = 32f } } private fun deselectView(view: View) { view.apply { isSelected = false elevation = 0f } } }
mit
96babab9574ea120acbfef7170484851
37.251497
122
0.621634
5.724014
false
false
false
false
paplorinc/intellij-community
platform/lang-api/src/com/intellij/configurationStore/UnknownElementManager.kt
7
2744
/* * 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.configurationStore import gnu.trove.THashMap import gnu.trove.THashSet import org.jdom.Element import java.util.function.Consumer import java.util.function.Function // Empty unknown tags supported to simplify client write code (with and without unknown elements) class UnknownElementWriter internal constructor(private val unknownElements: Map<String, Element> = emptyMap()) { companion object { @JvmField val EMPTY: UnknownElementWriter = UnknownElementWriter() } fun <T> write(outElement: Element, items: Collection<T>, itemToTagName: Function<T, String>, writer: Consumer<T>) { val knownNameToWriter = THashMap<String, T>(items.size) for (item in items) { knownNameToWriter.put(itemToTagName.apply(item), item) } write(outElement, knownNameToWriter, writer) } fun <T> write(outElement: Element, knownNameToWriter: Map<String, T>, writer: Consumer<T>) { val names: Set<String> if (unknownElements.isEmpty()) { names = knownNameToWriter.keys } else { names = THashSet<String>(unknownElements.keys) names.addAll(knownNameToWriter.keys) } val sortedNames = names.toTypedArray() sortedNames.sort() for (name in sortedNames) { val known = knownNameToWriter.get(name) if (known == null) { outElement.addContent(unknownElements.get(name)!!.clone()) } else { writer.accept(known) } } } } class UnknownElementCollector { private val knownTagNames = THashSet<String>() fun addKnownName(name: String) { knownTagNames.add(name) } fun createWriter(element: Element): UnknownElementWriter? { var unknownElements: MutableMap<String, Element>? = null val iterator = element.children.iterator() for (child in iterator) { if (child.name != "option" && !knownTagNames.contains(child.name)) { if (unknownElements == null) { unknownElements = THashMap() } unknownElements.put(child.name, child) iterator.remove() } } return unknownElements?.let(::UnknownElementWriter) ?: UnknownElementWriter.EMPTY } }
apache-2.0
3e0336c2e26f0c2ab46c6132fe895297
31.294118
117
0.700802
4.071217
false
false
false
false
indianpoptart/RadioControl
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/fragments/SlideFragment.kt
1
1182
package com.nikhilparanjape.radiocontrol.fragments /** * Created by Nikhil on 4/24/2016. * * @author Nikhil Paranjape * * */ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class SlideFragment : Fragment(){ private var layoutResId: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null && requireArguments().containsKey(ARG_LAYOUT_RES_ID)) layoutResId = requireArguments().getInt(ARG_LAYOUT_RES_ID) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(layoutResId, container, false) } companion object { private const val ARG_LAYOUT_RES_ID = "layoutResId" fun newInstance(layoutResId: Int): SlideFragment { val sampleSlide = SlideFragment() val args = Bundle() args.putInt(ARG_LAYOUT_RES_ID, layoutResId) sampleSlide.arguments = args return sampleSlide } } }
gpl-3.0
6cc96ee456181cf16fda2a9d254c8f97
23.142857
116
0.676819
4.653543
false
false
false
false
google/intellij-community
plugins/settings-repository/src/actions/ConfigureIcsAction.kt
3
3070
// 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.settingsRepository.actions import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.stateStore import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.ui.components.dialog import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.builder.text import com.intellij.ui.dsl.gridLayout.HorizontalAlign import kotlinx.coroutines.runBlocking import org.jetbrains.settingsRepository.IcsBundle import org.jetbrains.settingsRepository.createMergeActions import org.jetbrains.settingsRepository.icsManager import org.jetbrains.settingsRepository.icsMessage import kotlin.properties.Delegates internal class ConfigureIcsAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { runBlocking { icsManager.runInAutoCommitDisabledMode { var urlTextField: TextFieldWithBrowseButton by Delegates.notNull() val panel = panel { row(icsMessage("settings.upstream.url")) { urlTextField = textFieldWithBrowseButton(browseDialogTitle = icsMessage("configure.ics.choose.local.repository.dialog.title"), fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()) .text(icsManager.repositoryManager.getUpstream() ?: "") .horizontalAlign(HorizontalAlign.FILL) .component } row { comment(IcsBundle.message("message.see.help.pages.for.more.info", "https://www.jetbrains.com/help/idea/sharing-your-ide-settings.html#settings-repository")) } } dialog(title = icsMessage("settings.panel.title"), panel = panel, focusedComponent = urlTextField, project = e.project, createActions = { createMergeActions(e.project, urlTextField, it) }) .show() } } } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val application = ApplicationManager.getApplication() if (application.isUnitTestMode) { return } e.presentation.isEnabledAndVisible = icsManager.isActive || !(application.stateStore.storageManager as StateStorageManagerImpl).compoundStreamProvider.isExclusivelyEnabled if (!e.presentation.isEnabledAndVisible && ActionPlaces.MAIN_MENU == e.place) { e.presentation.isVisible = true } e.presentation.icon = null } }
apache-2.0
a8e8d12971943ada57fa883e6bf7257e
44.161765
175
0.726059
5.229983
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/Conversions.kt
1
4118
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.nj2k.tree.JKTreeElement import org.jetbrains.kotlin.nj2k.types.JKTypeFactory interface Conversion { val context: NewJ2kConverterContext val symbolProvider: JKSymbolProvider get() = context.symbolProvider val typeFactory: JKTypeFactory get() = context.typeFactory fun runConversion(treeRoots: Sequence<JKTreeElement>, context: NewJ2kConverterContext): Boolean } interface SequentialBaseConversion : Conversion { fun runConversion(treeRoot: JKTreeElement, context: NewJ2kConverterContext): Boolean override fun runConversion(treeRoots: Sequence<JKTreeElement>, context: NewJ2kConverterContext): Boolean { return treeRoots.maxOfOrNull { runConversion(it, context) } ?: false } } abstract class MatchBasedConversion(override val context: NewJ2kConverterContext) : SequentialBaseConversion { fun <R : JKTreeElement, T> applyRecursive(element: R, data: T, func: (JKTreeElement, T) -> JKTreeElement): R = org.jetbrains.kotlin.nj2k.tree.applyRecursive(element, data, ::onElementChanged, func) fun <R : JKTreeElement> applyRecursive(element: R, func: (JKTreeElement) -> JKTreeElement): R { return applyRecursive(element, null) { it, _ -> func(it) } } private inline fun <T> applyRecursiveToList( element: JKTreeElement, child: List<JKTreeElement>, iter: MutableListIterator<Any>, data: T, func: (JKTreeElement, T) -> JKTreeElement ): List<JKTreeElement> { val newChild = child.map { func(it, data) } child.forEach { it.detach(element) } iter.set(child) newChild.forEach { it.attach(element) } newChild.zip(child).forEach { (old, new) -> if (old !== new) { onElementChanged(new, old) } } return newChild } abstract fun onElementChanged(new: JKTreeElement, old: JKTreeElement) } abstract class RecursiveApplicableConversionBase(context: NewJ2kConverterContext) : MatchBasedConversion(context) { override fun onElementChanged(new: JKTreeElement, old: JKTreeElement) { somethingChanged = true } override fun runConversion(treeRoot: JKTreeElement, context: NewJ2kConverterContext): Boolean { val root = applyToElement(treeRoot) assert(root === treeRoot) return somethingChanged } private var somethingChanged = false abstract fun applyToElement(element: JKTreeElement): JKTreeElement fun <T : JKTreeElement> recurse(element: T): T = applyRecursive(element, ::applyToElement) } val RecursiveApplicableConversionBase.languageVersionSettings: LanguageVersionSettings get() { val converter = context.converter return converter.targetModule?.languageVersionSettings ?: converter.project.languageVersionSettings } val RecursiveApplicableConversionBase.moduleApiVersion: ApiVersion get() = languageVersionSettings.apiVersion abstract class RecursiveApplicableConversionWithState<S>( context: NewJ2kConverterContext, private val initialState: S ) : MatchBasedConversion(context) { override fun onElementChanged(new: JKTreeElement, old: JKTreeElement) { somethingChanged = true } private var somethingChanged = false override fun runConversion(treeRoot: JKTreeElement, context: NewJ2kConverterContext): Boolean { val root = applyToElement(treeRoot, initialState) assert(root === treeRoot) return somethingChanged } abstract fun applyToElement(element: JKTreeElement, state: S): JKTreeElement fun <T : JKTreeElement> recurse(element: T, state: S): T = applyRecursive(element, state, ::applyToElement) }
apache-2.0
7a4fdf199e03d5a85a83106c4a07ef82
35.776786
158
0.723652
4.805134
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/project/convertModuleGroupsToQualifiedNames.kt
3
9286
// 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.ide.actions.project import com.intellij.CommonBundle import com.intellij.codeInsight.intention.IntentionManager import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionProfileWrapper import com.intellij.codeInspection.ex.InspectionToolsSupplier import com.intellij.codeInspection.ex.LocalInspectionToolWrapper import com.intellij.configurationStore.runInAllowSaveMode import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LineExtensionInfo import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileTypes.PlainTextLanguage import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.module.impl.ModulePointerManagerImpl import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import java.awt.Color import java.awt.Font import java.util.function.Function import javax.swing.Action import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JPanel internal class ConvertModuleGroupsToQualifiedNamesDialog(val project: Project) : DialogWrapper(project) { private val editorArea: EditorTextField private val document: Document get() = editorArea.document private lateinit var modules: List<Module> private val recordPreviousNamesCheckBox: JCheckBox private var modified = false init { title = ProjectBundle.message("convert.module.groups.dialog.title") isModal = false setOKButtonText(ProjectBundle.message("convert.module.groups.button.text")) editorArea = EditorTextFieldProvider.getInstance().getEditorField(PlainTextLanguage.INSTANCE, project, listOf(EditorCustomization { it.settings.apply { isLineNumbersShown = false isLineMarkerAreaShown = false isFoldingOutlineShown = false isRightMarginShown = false additionalLinesCount = 0 additionalColumnsCount = 0 isAdditionalPageAtBottom = false isShowIntentionBulb = false } (it as? EditorImpl)?.registerLineExtensionPainter(this::generateLineExtension) setupHighlighting(it) }, MonospaceEditorCustomization.getInstance())) document.addDocumentListener(object: DocumentListener { override fun documentChanged(event: DocumentEvent) { modified = true } }, disposable) recordPreviousNamesCheckBox = JCheckBox(ProjectBundle.message("convert.module.groups.record.previous.names.text"), true) importRenamingScheme(emptyMap()) init() } private fun setupHighlighting(editor: Editor) { editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false) val inspections = InspectionToolsSupplier.Simple(listOf(LocalInspectionToolWrapper(ModuleNamesListInspection()))) val file = PsiDocumentManager.getInstance(project).getPsiFile(document) file?.putUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY, Function { val profile = InspectionProfileImpl("Module names", inspections, null) for (spellCheckingToolName in SpellCheckingEditorCustomizationProvider.getInstance().spellCheckingToolNames) { profile.getToolsOrNull(spellCheckingToolName, project)?.isEnabled = false } InspectionProfileWrapper(profile) }) } override fun createCenterPanel(): JPanel { val text = XmlStringUtil.wrapInHtml(ProjectBundle.message("convert.module.groups.description.text")) val recordPreviousNames = com.intellij.util.ui.UI.PanelFactory.panel(recordPreviousNamesCheckBox) .withTooltip(ProjectBundle.message("convert.module.groups.record.previous.names.tooltip", ApplicationNamesInfo.getInstance().fullProductName)).createPanel() return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP) .addToCenter(editorArea) .addToTop(JBLabel(text)) .addToBottom(recordPreviousNames) } override fun getPreferredFocusedComponent(): JComponent = editorArea.focusTarget private fun generateLineExtension(line: Int): Collection<LineExtensionInfo> { val lineText = document.charsSequence.subSequence(document.getLineStartOffset(line), document.getLineEndOffset(line)).toString() if (line !in modules.indices || modules[line].name == lineText) return emptyList() val name = LineExtensionInfo(" <- ${modules[line].name}", JBColor.GRAY, null, null, Font.PLAIN) val groupPath = ModuleManager.getInstance(project).getModuleGroupPath(modules[line]) if (groupPath == null) { return listOf(name) } @NlsSafe val pathString = groupPath.joinToString(separator = "/", prefix = " (", postfix = ")") val group = LineExtensionInfo(pathString, Color.GRAY, null, null, Font.PLAIN) return listOf(name, group) } fun importRenamingScheme(renamingScheme: Map<String, String>) { val moduleManager = ModuleManager.getInstance(project) fun getDefaultName(module: Module) = (moduleManager.getModuleGroupPath(module)?.let { it.joinToString(".") + "." } ?: "") + module.name val names = moduleManager.modules.associateBy({ it }, { renamingScheme.getOrElse(it.name, { getDefaultName(it) }) }) modules = moduleManager.modules.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { names[it]!! })) runWriteAction { document.setText(modules.joinToString("\n") { names[it]!! }) } modified = false } fun getRenamingScheme(): Map<String, String> { val lines = document.charsSequence.split('\n') return modules.withIndex().filter { lines[it.index] != it.value.name }.associateByTo(LinkedHashMap(), { it.value.name }, { if (it.index in lines.indices) lines[it.index] else it.value.name }) } override fun doCancelAction() { if (modified) { val answer = Messages.showYesNoCancelDialog(project, ProjectBundle.message("convert.module.groups.do.you.want.to.save.scheme"), ProjectBundle.message("convert.module.groups.dialog.title"), null) when (answer) { Messages.CANCEL -> return Messages.YES -> { if (!saveModuleRenamingScheme(this)) { return } } } } super.doCancelAction() } override fun doOKAction() { ModuleNamesListInspection.checkModuleNames(document.charsSequence.lines(), project) { line, message -> Messages.showErrorDialog(project, ProjectBundle.message("convert.module.groups.error.at.text", line + 1, StringUtil.decapitalize(message)), CommonBundle.getErrorTitle()) return } val renamingScheme = getRenamingScheme() if (renamingScheme.isNotEmpty()) { val model = ModuleManager.getInstance(project).modifiableModel val byName = modules.associateBy { it.name } for (entry in renamingScheme) { model.renameModule(byName[entry.key]!!, entry.value) } modules.forEach { model.setModuleGroupPath(it, null) } runInAllowSaveMode(isSaveAllowed = false) { runWriteAction { model.commit() } if (recordPreviousNamesCheckBox.isSelected) { (ModulePointerManager.getInstance(project) as ModulePointerManagerImpl).setRenamingScheme(renamingScheme) } } project.save() } super.doOKAction() } override fun createActions(): Array<Action> { return arrayOf(okAction, SaveModuleRenamingSchemeAction(this) { modified = false }, LoadModuleRenamingSchemeAction(this), cancelAction) } } internal class ConvertModuleGroupsToQualifiedNamesAction : DumbAwareAction(ProjectBundle.message("convert.module.groups.action.text"), ProjectBundle.message("convert.module.groups.action.description"), null) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return ConvertModuleGroupsToQualifiedNamesDialog(project).show() } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null && ModuleManager.getInstance(e.project!!).hasModuleGroups() } }
apache-2.0
9c838bcc9b126f47129445a15a4bfc0a
43.219048
140
0.734762
4.754736
false
false
false
false
allotria/intellij-community
platform/build-scripts/dev-server/src/PluginBuilder.kt
2
5973
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.devServer import com.intellij.openapi.util.Pair import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.impl.DistributionJARsBuilder import org.jetbrains.intellij.build.impl.LayoutBuilder import org.jetbrains.intellij.build.impl.PluginLayout import org.jetbrains.intellij.build.impl.projectStructureMapping.ProjectStructureMapping import org.jetbrains.intellij.build.tasks.reorderJar import java.io.File import java.nio.file.DirectoryStream import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.util.concurrent.Executor import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference data class BuildItem(val dir: Path, val layout: PluginLayout) class PluginBuilder(private val builder: DistributionJARsBuilder, val buildContext: BuildContext, private val outDir: Path) { private val dirtyPlugins = HashSet<BuildItem>() @Synchronized fun addDirtyPluginDir(item: BuildItem, reason: Any) { if (dirtyPlugins.add(item)) { LOG.info("${item.dir.fileName} is changed (at least ${if (reason is Path) outDir.relativize(reason) else reason} is changed)") } } @Synchronized private fun getDirtyPluginsAndClear(): Collection<BuildItem> { if (dirtyPlugins.isEmpty()) { return emptyList() } val result = dirtyPlugins.toList() dirtyPlugins.clear() return result } fun buildChanged(): String { val dirtyPlugins = getDirtyPluginsAndClear() if (dirtyPlugins.isEmpty()) { return "All plugins are up to date" } val layoutBuilder = LayoutBuilder(buildContext, false) for (plugin in dirtyPlugins) { try { clearDirContent(plugin.dir) buildPlugin(plugin, buildContext, builder, layoutBuilder) } catch (e: Throwable) { // put back (that's ok to add already processed plugins - doesn't matter, no need to complicate) for (dirtyPlugin in dirtyPlugins) { addDirtyPluginDir(dirtyPlugin, "<internal error>") } throw e } } return "Plugins ${dirtyPlugins.joinToString { it.dir.fileName.toString() }} were updated" } } fun buildPlugins(@Suppress("SameParameterValue") parallelCount: Int, buildContext: BuildContext, plugins: List<BuildItem>, builder: DistributionJARsBuilder) { val executor: Executor = if (parallelCount == 1) { Executor(Runnable::run) } else { Executors.newWorkStealingPool(parallelCount) } val errorRef = AtomicReference<Throwable>() var sharedLayoutBuilder: LayoutBuilder? = null for (plugin in plugins) { if (errorRef.get() != null) { break } val buildContextForPlugin = if (parallelCount == 1) buildContext else buildContext.forkForParallelTask("Build ${plugin.layout.mainModule}") executor.execute(Runnable { if (errorRef.get() != null) { return@Runnable } try { val layoutBuilder: LayoutBuilder if (parallelCount == 1) { if (sharedLayoutBuilder == null) { sharedLayoutBuilder = LayoutBuilder(buildContext, false) } layoutBuilder = sharedLayoutBuilder!! } else { layoutBuilder = LayoutBuilder(buildContextForPlugin, false) } buildPlugin(plugin, buildContextForPlugin, builder, layoutBuilder) } catch (e: Throwable) { if (errorRef.compareAndSet(null, e)) { throw e } } }) } if (executor is ExecutorService) { executor.shutdown() executor.awaitTermination(5, TimeUnit.MINUTES) } errorRef.get()?.let { throw it } } private fun buildPlugin(plugin: BuildItem, buildContext: BuildContext, builder: DistributionJARsBuilder, layoutBuilder: LayoutBuilder) { val mainModule = plugin.layout.mainModule if (skippedPluginModules.contains(mainModule)) { return } buildContext.messages.info("Build ${mainModule}") val generatedResources = getGeneratedResources(plugin.layout, buildContext) if (mainModule != "intellij.platform.builtInHelp") { builder.checkOutputOfPluginModules(mainModule, plugin.layout.moduleJars, plugin.layout.moduleExcludes) } val layoutSpec = layoutBuilder.createLayoutSpec(ProjectStructureMapping(), true) builder.processLayout(layoutBuilder, plugin.layout, plugin.dir, layoutSpec, plugin.layout.moduleJars, generatedResources) val stream: DirectoryStream<Path> try { stream = Files.newDirectoryStream(plugin.dir.resolve("lib")) } catch (ignore: NoSuchFileException) { return } stream.use { for (path in it) { if (path.toString().endsWith(".jar")) { reorderJar(path, emptyList(), path) } } } } private fun getGeneratedResources(plugin: PluginLayout, buildContext: BuildContext): List<Pair<File, String>> { if (plugin.resourceGenerators.isEmpty()) { return emptyList() } val generatedResources = ArrayList<Pair<File, String>>(plugin.resourceGenerators.size) for (resourceGenerator in plugin.resourceGenerators) { val className = resourceGenerator.first::class.java.name if (className == "org.jetbrains.intellij.build.sharedIndexes.PreSharedIndexesGenerator" || className.endsWith("PrebuiltIndicesResourcesGenerator")) { continue } val resourceFile = resourceGenerator.first.generateResources(buildContext) if (resourceFile != null) { generatedResources.add(Pair(resourceFile, resourceGenerator.second)) } } return generatedResources.takeIf { it.isNotEmpty() } ?: emptyList() }
apache-2.0
8efb68cbe78f0860625d625269c55fc5
32.188889
143
0.697639
4.626646
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/project/FileUtils.kt
2
4340
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.project import com.intellij.UtilBundle import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.URLUtil import org.apache.commons.lang.StringUtils import java.io.* import java.net.URL import java.util.jar.JarFile object FileUtils { private val LOG = Logger.getInstance(FileUtils::class.java) @Throws(IOException::class) fun copyJarResourcesRecursively(destDir: File, jarPath: String, destinationFilter: FileFilter? = null): Boolean { val splitJarPath = splitJarPath(jarPath) val mayBeEscapedFile = URL(splitJarPath.first).file val file = URLUtil.unescapePercentSequences(mayBeEscapedFile) val jarFile = JarFile(file) val prefix = splitJarPath.second val entries = jarFile.entries() while (entries.hasMoreElements()) { val entry = entries.nextElement() if (entry.name.startsWith(prefix)) { val filename = StringUtils.removeStart(entry.name, prefix) val f = File(destDir, filename) if (destinationFilter != null && !destinationFilter.accept(f)) continue if (!entry.isDirectory) { if (!ensureDirectoryExists(f.parentFile)) { LOG.error("Cannot create directory: " + f.parentFile) } val entryInputStream = jarFile.getInputStream(entry) if (!copyStream(entryInputStream, f)) { return false } entryInputStream.close() } } } return true } fun copyResourcesRecursively(originUrl: URL, destination: File, destinationFilter: FileFilter? = null): Boolean { try { if (originUrl.protocol == URLUtil.JAR_PROTOCOL) { copyJarResourcesRecursively(destination, originUrl.file, destinationFilter) } else if (originUrl.protocol == URLUtil.FILE_PROTOCOL) { copyDirWithDestFilter(File(originUrl.path), destination, destinationFilter) } return true } catch (e: IOException) { LOG.error(e) } return false } // Copied from FileUtil#copyDir but with filter for destination instead of source private fun copyDirWithDestFilter(fromDir: File, toDir: File, destinationFilter: FileFilter?) { FileUtil.ensureExists(toDir) if (FileUtil.isAncestor(fromDir, toDir, true)) { LOG.error(fromDir.absolutePath + " is ancestor of " + toDir + ". Can't copy to itself.") return } val files = fromDir.listFiles() ?: throw IOException(UtilBundle.message("exception.directory.is.invalid", fromDir.path)) if (!fromDir.canRead()) throw IOException(UtilBundle.message("exception.directory.is.not.readable", fromDir.path)) for (file in files) { val destinationFile = File(toDir, file.name) if (file.isDirectory) { copyDirWithDestFilter(file, destinationFile, destinationFilter) } else { if (destinationFilter == null || destinationFilter.accept(destinationFile)) { FileUtil.copy(file, destinationFile) } } } } private fun copyStream(inputStream: InputStream, f: File): Boolean { try { return copyStream(inputStream, FileOutputStream(f)) } catch (e: FileNotFoundException) { LOG.error(e) } return false } private fun copyStream(inputStream: InputStream, os: OutputStream): Boolean { try { val buf = ByteArray(1024) var len = inputStream.read(buf) while (len > 0) { os.write(buf, 0, len) len = inputStream.read(buf) } inputStream.close() os.close() return true } catch (e: IOException) { LOG.error(e) } return false } fun ensureDirectoryExists(f: File): Boolean = f.exists() || f.mkdirs() private fun splitJarPath(path: String): Pair<String, String> { val lastIndexOf = path.lastIndexOf(".jar!/") if (lastIndexOf == -1) throw IOException("Invalid Jar path format") val splitIdx = lastIndexOf + 4 // ".jar" val filePath = path.substring(0, splitIdx) val pathInsideJar = path.substring(splitIdx + 2 ,path.length) // remove "!/" return Pair(filePath, pathInsideJar) } }
apache-2.0
dab977e572d1a650b35c057137d4fb56
33.181102
140
0.662442
4.250735
false
false
false
false
allotria/intellij-community
java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/MethodExtractor.kt
2
16937
// 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.refactoring.extractMethod.newImpl import com.intellij.codeInsight.Nullability import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.ide.util.PropertiesComponent import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.application.WriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.WindowManager import com.intellij.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.util.PsiEditorUtil import com.intellij.refactoring.HelpID import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.ExtractMethodDialog import com.intellij.refactoring.extractMethod.ExtractMethodHandler import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.addSiblingAfter import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.guessMethodName import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.wrapWithCodeBlock import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.selectTargetClass import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.withFilteredAnnotations import com.intellij.refactoring.extractMethod.newImpl.MapFromDialog.mapFromDialog import com.intellij.refactoring.extractMethod.newImpl.inplace.* import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions import com.intellij.refactoring.introduceVariable.IntroduceVariableBase import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.ConflictsUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.NonNls class MethodExtractor { data class ExtractedElements(val callElements: List<PsiElement>, val method: PsiMethod) fun doExtract(file: PsiFile, range: TextRange) { val project = file.project val editor = PsiEditorUtil.findEditor(file) ?: return val activeExtractor = InplaceMethodExtractor.getActiveExtractor(editor) if (activeExtractor != null) { activeExtractor.restartInDialog() return } try { if (!CommonRefactoringUtil.checkReadOnlyStatus(file.project, file)) return val statements = ExtractSelector().suggestElementsToExtract(file, range) if (statements.isEmpty()) { throw ExtractException(RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"), file) } val extractOptions = findExtractOptions(statements) selectTargetClass(extractOptions) { options -> val targetClass = options.anchor.containingClass ?: throw IllegalStateException("Failed to find target class") val annotate = PropertiesComponent.getInstance(options.project).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, false) val parameters = ExtractParameters(targetClass, range, "", annotate, options.isStatic) val extractor = getDefaultInplaceExtractor(options) if (Registry.`is`("java.refactoring.extractMethod.inplace") && EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled) { val popupSettings = createInplaceSettingsPopup(options) val guessedNames = suggestSafeMethodNames(options) val methodName = guessedNames.first() val suggestedNames = guessedNames.takeIf { it.size > 1 }.orEmpty() doInplaceExtract(editor, extractor, parameters.copy(methodName = methodName), popupSettings, suggestedNames) } else { val elements = ExtractSelector().suggestElementsToExtract(parameters.targetClass.containingFile, parameters.range) extractor.extractInDialog(parameters.targetClass, elements, parameters.methodName, parameters.static) } } } catch (e: ExtractException) { val message = JavaRefactoringBundle.message("extract.method.error.prefix") + " " + (e.message ?: "") CommonRefactoringUtil.showErrorHint(project, editor, message, ExtractMethodHandler.getRefactoringName(), HelpID.EXTRACT_METHOD) showError(editor, e.problems) } } fun getDefaultInplaceExtractor(options: ExtractOptions): InplaceExtractMethodProvider { val enabled = Registry.`is`("java.refactoring.extractMethod.newImplementation") val possible = ExtractMethodHandler.canUseNewImpl(options.project, options.anchor.containingFile, options.elements.toTypedArray()) return if (enabled && possible) DefaultMethodExtractor() else LegacyMethodExtractor() } fun suggestSafeMethodNames(options: ExtractOptions): List<String> { val unsafeNames = guessMethodName(options) val safeNames = unsafeNames.filterNot { name -> hasConflicts(options.copy(methodName = name)) } if (safeNames.isNotEmpty()) return safeNames val baseName = unsafeNames.firstOrNull() ?: "extracted" val generatedNames = sequenceOf(baseName) + generateSequence(1) { seed -> seed + 1 }.map { number -> "$baseName$number" } return generatedNames.filterNot { name -> hasConflicts(options.copy(methodName = name)) }.take(1).toList() } private fun hasConflicts(options: ExtractOptions): Boolean { val (_, method) = prepareRefactoringElements(options) val conflicts = MultiMap<PsiElement, String>() ConflictsUtil.checkMethodConflicts(options.anchor.containingClass, null, method, conflicts) return ! conflicts.isEmpty } fun createInplaceSettingsPopup(options: ExtractOptions): ExtractMethodPopupProvider { val isStatic = options.isStatic val analyzer = CodeFragmentAnalyzer(options.elements) val optionsWithStatic = ExtractMethodPipeline.withForcedStatic(analyzer, options) val makeStaticAndPassFields = optionsWithStatic?.inputParameters?.size != options.inputParameters.size val showStatic = ! isStatic && optionsWithStatic != null val hasAnnotation = options.dataOutput.nullability != Nullability.UNKNOWN && options.dataOutput.type !is PsiPrimitiveType val annotationAvailable = ExtractMethodHelper.isNullabilityAvailable(options) return ExtractMethodPopupProvider( annotateDefault = if (hasAnnotation && annotationAvailable) needsNullabilityAnnotations(options.project) else null, makeStaticDefault = if (showStatic) false else null, staticPassFields = makeStaticAndPassFields ) } fun doInplaceExtract(editor: Editor, extractor: InplaceExtractMethodProvider, parameters: ExtractParameters, settingsPanel: ExtractMethodPopupProvider, suggestedNames: List<String>) { executeRefactoringCommand(parameters.targetClass.project) { InplaceMethodExtractor(editor, parameters, extractor, settingsPanel) .performInplaceRefactoring(LinkedHashSet(suggestedNames)) } } fun doDialogExtract(options: ExtractOptions){ val dialogOptions = mapFromDialog(options, RefactoringBundle.message("extract.method.title"), HelpID.EXTRACT_METHOD) if (dialogOptions != null) { executeRefactoringCommand(dialogOptions.project) { doRefactoring(dialogOptions) } } } private fun executeRefactoringCommand(project: Project, command: () -> Unit){ CommandProcessor.getInstance().executeCommand(project, command, ExtractMethodHandler.getRefactoringName(), null) } private fun doRefactoring(options: ExtractOptions) { try { sendRefactoringStartedEvent(options.elements.toTypedArray()) val extractedElements = extractMethod(options) sendRefactoringDoneEvent(extractedElements.method) } catch (e: IncorrectOperationException) { LOG.error(e) } } fun replaceElements(sourceElements: List<PsiElement>, callElements: List<PsiElement>, anchor: PsiMember, method: PsiMethod): ExtractedElements { return WriteAction.compute<ExtractedElements, Throwable> { val addedMethod = anchor.addSiblingAfter(method) as PsiMethod val replacedCallElements = replace(sourceElements, callElements) ExtractedElements(replacedCallElements, addedMethod) } } fun extractMethod(extractOptions: ExtractOptions): ExtractedElements { val elementsToExtract = prepareRefactoringElements(extractOptions) return replaceElements(extractOptions.elements, elementsToExtract.callElements, extractOptions.anchor, elementsToExtract.method) } fun doTestExtract( doRefactor: Boolean, editor: Editor, isConstructor: Boolean?, isStatic: Boolean?, returnType: PsiType?, newNameOfFirstParam: String?, targetClass: PsiClass?, @PsiModifier.ModifierConstant visibility: String?, vararg disabledParameters: Int ): Boolean { val project = editor.project ?: return false val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return false val range = ExtractMethodHelper.findEditorSelection(editor) ?: return false val elements = ExtractSelector().suggestElementsToExtract(file, range) if (elements.isEmpty()) throw ExtractException("Nothing to extract", file) var options = findExtractOptions(elements) val analyzer = CodeFragmentAnalyzer(elements) val candidates = ExtractMethodPipeline.findTargetCandidates(analyzer, options) val defaultTargetClass = candidates.firstOrNull { it !is PsiAnonymousClass } ?: candidates.first() options = ExtractMethodPipeline.withTargetClass(analyzer, options, targetClass ?: defaultTargetClass) ?: throw ExtractException("Fail", elements.first()) options = options.copy(methodName = "newMethod") if (isConstructor != options.isConstructor){ options = ExtractMethodPipeline.asConstructor(analyzer, options) ?: throw ExtractException("Fail", elements.first()) } if (! options.isStatic && isStatic == true) { options = ExtractMethodPipeline.withForcedStatic(analyzer, options) ?: throw ExtractException("Fail", elements.first()) } if (newNameOfFirstParam != null) { options = options.copy( inputParameters = listOf(options.inputParameters.first().copy(name = newNameOfFirstParam)) + options.inputParameters.drop(1) ) } if (returnType != null) { options = options.copy(dataOutput = options.dataOutput.withType(returnType)) } if (disabledParameters.isNotEmpty()) { options = options.copy( disabledParameters = options.inputParameters.filterIndexed { index, _ -> index in disabledParameters }, inputParameters = options.inputParameters.filterIndexed { index, _ -> index !in disabledParameters } ) } if (visibility != null) { options = options.copy(visibility = visibility) } if (options.anchor.containingClass?.isInterface == true) { options = ExtractMethodPipeline.adjustModifiersForInterface(options.copy(visibility = PsiModifier.PRIVATE)) } if (doRefactor) { extractMethod(options) } return true } fun showError(editor: Editor, ranges: List<TextRange>) { val project = editor.project ?: return if (ranges.isEmpty()) return val highlightManager = HighlightManager.getInstance(project) ranges.forEach { textRange -> highlightManager.addRangeHighlight(editor, textRange.startOffset, textRange.endOffset, EditorColors.SEARCH_RESULT_ATTRIBUTES, true, null) } WindowManager.getInstance().getStatusBar(project).info = RefactoringBundle.message("press.escape.to.remove.the.highlighting") } fun prepareRefactoringElements(extractOptions: ExtractOptions): ExtractedElements { val dependencies = withFilteredAnnotations(extractOptions) val factory = PsiElementFactory.getInstance(dependencies.project) val styleManager = CodeStyleManager.getInstance(dependencies.project) val codeBlock = BodyBuilder(factory) .build( dependencies.elements, dependencies.flowOutput, dependencies.dataOutput, dependencies.inputParameters, dependencies.disabledParameters, dependencies.requiredVariablesInside ) val method = SignatureBuilder(dependencies.project) .build( dependencies.anchor.context, dependencies.elements, dependencies.isStatic, dependencies.visibility, dependencies.typeParameters, dependencies.dataOutput.type.takeIf { !dependencies.isConstructor }, dependencies.methodName, dependencies.inputParameters, dependencies.dataOutput.annotations, dependencies.thrownExceptions, dependencies.anchor ) method.body?.replace(codeBlock) val parameters = dependencies.inputParameters.map { it.references.first() }.joinToString { it.text } val methodCall = findExtractQualifier(dependencies) + "(" + parameters + ")" val callBuilder = CallBuilder(dependencies.project, dependencies.elements.first().context) val expressionElement = (dependencies.elements.singleOrNull() as? PsiExpression) val callElements = if (expressionElement != null) { callBuilder.buildExpressionCall(methodCall, dependencies.dataOutput) } else { callBuilder.buildCall(methodCall, dependencies.flowOutput, dependencies.dataOutput, dependencies.exposedLocalVariables) } val formattedCallElements = callElements.map { styleManager.reformat(it) } if (needsNullabilityAnnotations(dependencies.project) && ExtractMethodHelper.isNullabilityAvailable(dependencies)) { updateMethodAnnotations(method, dependencies.inputParameters) } return ExtractedElements(formattedCallElements, method) } private fun replace(source: List<PsiElement>, target: List<PsiElement>): List<PsiElement> { val sourceAsExpression = source.singleOrNull() as? PsiExpression val targetAsExpression = target.singleOrNull() as? PsiExpression if (sourceAsExpression != null && targetAsExpression != null) { val replacedExpression = IntroduceVariableBase.replace(sourceAsExpression, targetAsExpression, sourceAsExpression.project) return listOf(replacedExpression) } val normalizedTarget = if (target.size > 1 && source.first().parent !is PsiCodeBlock) { wrapWithCodeBlock(target) } else { target } val replacedElements = normalizedTarget.reversed().map { statement -> source.last().addSiblingAfter(statement) }.reversed() source.first().parent.deleteChildRange(source.first(), source.last()) return replacedElements } private fun needsNullabilityAnnotations(project: Project): Boolean { return PropertiesComponent.getInstance(project).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, true) } companion object { private val LOG = Logger.getInstance(MethodExtractor::class.java) @NonNls const val refactoringId: String = "refactoring.extract.method" internal fun sendRefactoringDoneEvent(extractedMethod: PsiMethod) { val data = RefactoringEventData() data.addElement(extractedMethod) extractedMethod.project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringDone(refactoringId, data) } internal fun sendRefactoringStartedEvent(elements: Array<PsiElement>) { val project = elements.firstOrNull()?.project ?: return val data = RefactoringEventData() data.addElements(elements) val publisher = project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) publisher.refactoringStarted(refactoringId, data) } } } private fun findExtractQualifier(options: ExtractOptions): String { val callText = options.methodName + "(" + options.inputParameters.map { it.references.first() }.joinToString { it.text } + ")" val factory = PsiElementFactory.getInstance(options.project) val callElement = factory.createExpressionFromText(callText, options.elements.first().context) as PsiMethodCallExpression val targetClassName = options.anchor.containingClass?.name val member = findClassMember(options.elements.first()) if (member == options.anchor) return options.methodName return if (callElement.resolveMethod() != null && !options.isConstructor) { if (options.isStatic) "$targetClassName.${options.methodName}" else "$targetClassName.this.${options.methodName}" } else { options.methodName } }
apache-2.0
8d1496b330b60e778f763cf30580bca0
48.817647
185
0.762296
4.966862
false
false
false
false
allotria/intellij-community
platform/vcs-code-review/src/com/intellij/util/ui/codereview/commits/CommitNodeComponent.kt
2
2547
// 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.util.ui.codereview.commits import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBInsets import com.intellij.util.ui.MacUIUtil import com.intellij.vcs.log.paint.PaintParameters import java.awt.Graphics import java.awt.Graphics2D import java.awt.Rectangle import java.awt.RenderingHints import java.awt.geom.Ellipse2D import java.awt.geom.Rectangle2D import javax.swing.JComponent class CommitNodeComponent : JComponent() { var type = Type.SINGLE init { isOpaque = false } override fun getPreferredSize() = JBDimension( PaintParameters.getNodeWidth(PaintParameters.ROW_HEIGHT), PaintParameters.ROW_HEIGHT ) override fun paintComponent(g: Graphics) { val rect = Rectangle(size) JBInsets.removeFrom(rect, insets) val g2 = g as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, if (MacUIUtil.USE_QUARTZ) RenderingHints.VALUE_STROKE_PURE else RenderingHints.VALUE_STROKE_NORMALIZE) if (isOpaque) { g2.color = background g2.fill(Rectangle2D.Float(rect.x.toFloat(), rect.y.toFloat(), rect.width.toFloat(), rect.height.toFloat())) } g2.color = foreground drawNode(g2, rect) if (type == Type.LAST || type == Type.MIDDLE) { drawEdgeUp(g2, rect) } if (type == Type.FIRST || type == Type.MIDDLE) { drawEdgeDown(g2, rect) } } private fun drawNode(g: Graphics2D, rect: Rectangle) { val radius = PaintParameters.getCircleRadius(rect.height) val circle = Ellipse2D.Double(rect.centerX - radius, rect.centerY - radius, radius * 2.0, radius * 2.0) g.fill(circle) } private fun drawEdgeUp(g: Graphics2D, rect: Rectangle) { val y1 = 0.0 val y2 = rect.centerY drawEdge(g, rect, y1, y2) } private fun drawEdgeDown(g: Graphics2D, rect: Rectangle) { val y1 = rect.centerY val y2 = rect.maxY drawEdge(g, rect, y1, y2) } private fun drawEdge(g: Graphics2D, rect: Rectangle, y1: Double, y2: Double) { val x = rect.centerX val width = PaintParameters.getLineThickness(rect.height) val line = Rectangle2D.Double(x - width / 2, y1 - 0.5, width.toDouble(), y1 + y2 + 0.5) g.fill(line) } enum class Type { SINGLE, FIRST, MIDDLE, LAST } }
apache-2.0
e966dcecadeb95c0756cd7cb2327e947
30.073171
140
0.688653
3.522822
false
false
false
false
ursjoss/sipamato
public/public-entity/src/test/kotlin/ch/difty/scipamato/publ/entity/NewStudyTopicTest.kt
2
1002
package ch.difty.scipamato.publ.entity import nl.jqno.equalsverifier.EqualsVerifier import org.amshove.kluent.shouldBeEmpty import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldHaveSize import org.junit.jupiter.api.Test internal class NewStudyTopicTest : PublicDbEntityTest<NewStudyTopic>() { override fun newEntity() = NewStudyTopic( sort = 1, title = "title", studies = listOf(NewStudy(1, 1), NewStudy(2, 2)), ) override fun assertSpecificGetters() { entity.sort shouldBeEqualTo 1 entity.title shouldBeEqualTo "title" entity.studies.shouldHaveSize(2) } override fun verifyEquals() { EqualsVerifier.simple().forClass(NewStudyTopic::class.java).verify() } @Test fun secondaryConstructor_hasNoStudies() { val t = NewStudyTopic(2, "title2") t.sort shouldBeEqualTo 2 t.title shouldBeEqualTo "title2" t.studies.shouldBeEmpty() } }
gpl-3.0
158f80c994d36960863bd2000ff23ebe
27.628571
76
0.677645
4.26383
false
true
false
false
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/file/ImportedModuleIndex.kt
1
1978
package org.purescript.file import com.intellij.openapi.application.ReadAction import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.indexing.* import com.intellij.util.io.EnumeratorStringDescriptor import com.intellij.util.io.KeyDescriptor import org.jetbrains.annotations.NonNls class ImportedModuleIndex : ScalarIndexExtension<String>() { override fun getName(): ID<String, Void?> { return NAME } override fun getIndexer(): DataIndexer<String, Void?, FileContent> { return DataIndexer<String, Void?, FileContent> { when (val file = it.psiFile) { is PSFile -> file.module ?.importDeclarations ?.mapNotNull { it.moduleName?.name} ?.map { it to null} ?.toMap() ?: emptyMap() else -> emptyMap() } } } override fun getKeyDescriptor(): KeyDescriptor<String> = EnumeratorStringDescriptor.INSTANCE override fun getVersion(): Int = 0 override fun getInputFilter(): FileBasedIndex.InputFilter = DefaultFileTypeSpecificInputFilter(PSFileType.INSTANCE) override fun dependsOnFileContent(): Boolean = true companion object { @NonNls val NAME = ID.create<String, Void?>("org.purescript.file.ImportedModuleIndex") fun filesImportingModule( project: Project, moduleName: String ): MutableCollection<VirtualFile> { val fileBasedIndex = FileBasedIndex.getInstance() return ReadAction.compute<MutableCollection<VirtualFile>, Throwable> { fileBasedIndex.getContainingFiles( NAME, moduleName, GlobalSearchScope.allScope(project) ) } } } }
bsd-3-clause
08a341f3ecbdc19225b9bf3cd6127fa5
31.442623
82
0.620829
5.419178
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/intentions/PackageSearchQuickFix.kt
1
1864
package com.jetbrains.packagesearch.intellij.plugin.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Iconable import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.util.dataService import icons.PackageSearchIcons import java.util.regex.Pattern class PackageSearchQuickFix(private val ref: PsiReference) : IntentionAction, LowPriorityAction, Iconable { private val classnamePattern = Pattern.compile("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+") override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { PackageSearchToolWindowFactory.activateToolWindow(project) { project.dataService() .setSearchQuery(ref.canonicalText) } } override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = ref.element.run { isValid && classnamePattern.matcher(text).matches() } @Suppress("DialogTitleCapitalization") // It's the Package Search plugin name... override fun getText() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action") @Suppress("DialogTitleCapitalization") // It's the Package Search plugin name... override fun getFamilyName() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.family") override fun getIcon(flags: Int) = PackageSearchIcons.Package override fun startInWriteAction() = false }
apache-2.0
c72805b5ef2009914086a13b7be54f60
44.463415
124
0.780043
4.983957
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/internal/ml/WordsSplitter.kt
12
2934
// 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.internal.ml import com.intellij.ide.ui.search.PorterStemmerUtil import com.intellij.util.text.NameUtilCore import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal class WordsSplitter private constructor(private val skipLess: Int, private val ignoreStopWords: Boolean, private val stopWords: Set<String>, private val maxWords: Int, private val withStemming: Boolean, private val toLowerCase: Boolean) { fun split(name: String): List<String> = wordsFromName(name) .filter(::shouldInclude) .take(maxWords) .map(::normalize) .toList() private fun wordsFromName(name: String) = sequence { var start = 0 while (start < name.length) { val next = NameUtilCore.nextWord(name, start) yield(name.substring(start, next)) start = next } } private fun normalize(word: String): String { return word .let { if (toLowerCase) it.toLowerCase() else it } .let { if (withStemming) PorterStemmerUtil.stem(it) ?: it else it } } private fun shouldInclude(word: String): Boolean = word.isNotBlank() && word.all { it.isLetter() } && word.length >= skipLess && (!ignoreStopWords || word !in stopWords) class Builder { companion object { private val DEFAULT_STOP_WORDS = setOf("set", "get", "is") private const val DEFAULT_MAX_WORDS_COUNT = 7 private const val DEFAULT_MIN_WORD_LENGTH = 3 fun identifiers(): Builder = Builder() .skipShort(DEFAULT_MIN_WORD_LENGTH) .ignoreStopWords(DEFAULT_STOP_WORDS) .maxWords(DEFAULT_MAX_WORDS_COUNT) .toLowerCase() } private var toLowerCase: Boolean = false private var withStemming: Boolean = false private var ignoreStopWords: Boolean = false private var stopWords: Set<String> = DEFAULT_STOP_WORDS private var skipLess: Int = 0 private var maxWords: Int = Int.MAX_VALUE fun build(): WordsSplitter = WordsSplitter(skipLess, ignoreStopWords, stopWords, maxWords, withStemming, toLowerCase) fun ignoreStopWords(stopWords: Iterable<String>? = null): Builder = apply { ignoreStopWords = true if (stopWords != null) { this.stopWords = stopWords.toSet() } } fun skipShort(skipLess: Int = DEFAULT_MIN_WORD_LENGTH): Builder = apply { this.skipLess = skipLess } fun maxWords(count: Int = DEFAULT_MAX_WORDS_COUNT): Builder = apply { maxWords = count } fun withStemming(): Builder = apply { withStemming = true } fun toLowerCase(): Builder = apply { toLowerCase = true } } }
apache-2.0
1361f3a0b6d392c793f31515d76d2735
32.340909
140
0.632584
4.132394
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/super/innerClassQualifiedFunctionCall.kt
5
982
interface T { open fun baz(): String = "T.baz" } open class A { open val foo: String = "OK" open fun bar(): String = "OK" open fun boo(): String = "OK" } open class B : A(), T { override fun bar(): String = "B" override fun baz(): String = "B.baz" inner class E { val foo: String = super<A>@B.foo fun bar() = super<A>@B.bar() + [email protected]() + [email protected]() } } class C : B() { override fun bar(): String = "C" override fun boo(): String = "C" inner class D { val foo: String = super<B>@C.foo fun bar() = super<B>@C.bar() + super<B>@C.boo() } } fun box(): String { var r = "" r = B().E().foo if (r != "OK") return "fail 1; r = $r" r = "" r = B().E().bar() if (r != "OKOKT.baz") return "fail 2; r = $r" r = "" r = C().D().foo if (r != "OK") return "fail 3; r = $r" r = "" r = C().D().bar() if (r != "BOK") return "fail 4; r = $r" return "OK" }
apache-2.0
69accff2c5adf70a594984771ec40200
20.347826
68
0.464358
2.797721
false
false
false
false
blokadaorg/blokada
android5/app/src/engine/kotlin/engine/PacketLoopForPlusDoh.kt
1
16194
/* * This file is part of Blokada. * * 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 https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package engine import android.os.ParcelFileDescriptor import android.system.ErrnoException import android.system.Os import android.system.OsConstants import android.system.StructPollfd import com.cloudflare.app.boringtun.BoringTunJNI import engine.MetricsService.PACKET_BUFFER_SIZE import model.BlokadaException import model.GatewayId import model.ex import org.pcap4j.packet.* import org.pcap4j.packet.factory.PacketFactoryPropertiesLoader import org.pcap4j.util.PropertiesLoader import service.DozeService import ui.utils.cause import utils.Logger import java.io.FileDescriptor import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.net.DatagramPacket import java.net.DatagramSocket import java.net.Inet6Address import java.net.InetAddress import java.nio.ByteBuffer internal class PacketLoopForPlusDoh ( private val deviceIn: FileInputStream, private val deviceOut: FileOutputStream, private val userBoringtunPrivateKey: String, internal val gatewayId: GatewayId, private val gatewayIp: String, private val gatewayPort: Int, private val createSocket: () -> DatagramSocket, private val stoppedUnexpectedly: () -> Unit ): Thread("PacketLoopForPlusDoh") { private val log = Logger("PLPlusDoh") private val metrics = MetricsService // Constants private val TICK_INTERVAL_MS = 500 private val forwarder: Forwarder = Forwarder() // Memory buffers private val buffer = ByteBuffer.allocateDirect(2000) private val memory = ByteArray(PACKET_BUFFER_SIZE) private val packet = DatagramPacket(memory, 0, 1) private val op = ByteBuffer.allocateDirect(8) private val proxyMemory = ByteArray(PACKET_BUFFER_SIZE) private val proxyPacket = DatagramPacket(proxyMemory, 0, 1) private var boringtunHandle: Long = -1L private var devicePipe: FileDescriptor? = null private var errorPipe: FileDescriptor? = null private var gatewaySocket: DatagramSocket? = null private var gatewayParcelFileDescriptor: ParcelFileDescriptor? = null private var lastTickMs = 0L private var ticks = 0 private val rewriter = PacketRewriter(this::loopback, buffer) private fun createTunnel() { log.v("Creating boringtun tunnel for gateway: $gatewayId") boringtunHandle = BoringTunJNI.new_tunnel(userBoringtunPrivateKey, gatewayId) } override fun run() { log.v("Started packet loop thread: $this") try { val errors = setupErrorsPipe() val device = setupDevicePipe(deviceIn) createTunnel() openGatewaySocket() val gatewayPipe = setupGatewayPipe() while (true) { if (shouldInterruptLoop()) throw InterruptedException() val polls = setupPolls(errors, device, gatewayPipe) val gateway = polls[2] device.listenFor(OsConstants.POLLIN) gateway.listenFor(OsConstants.POLLIN) poll(polls) tick() fromOpenProxySockets(polls) fromDeviceToProxy(device, deviceIn) fromGatewayToProxy(gateway) purge() } } catch (ex: InterruptedException) { log.v("Tunnel thread ${this.hashCode()} interrupted, stopping") } catch (ex: Exception) { log.w("Unexpected failure, stopping (maybe just closed?): $this: ${ex.message}") } finally { cleanup() if (!isInterrupted) stoppedUnexpectedly() } } private fun fromDevice(fromDevice: ByteArray, length: Int) { if (rewriter.handleFromDevice(fromDevice, length)) return if (dstAddress4(fromDevice, length, DnsMapperService.proxyDnsIpBytes)) { try { // Forward localhost packets to our DNS proxy val originEnvelope = IpSelector.newPacket(fromDevice, 0, length) as IpPacket (originEnvelope.payload as? UdpPacket)?.let { udp -> udp.payload?.let { payload -> val proxiedDns = DatagramPacket( payload.rawData, 0, payload.length(), originEnvelope.header.dstAddr, udp.header.dstPort.valueAsInt() ) forwardLocally(proxiedDns, originEnvelope) return } } } catch (ex: Exception) { log.w("Failed reading packet: ${ex.message}") } } op.rewind() val destination = buffer destination.rewind() destination.limit(destination.capacity()) val response = BoringTunJNI.wireguard_write(boringtunHandle, fromDevice, length, destination, destination.capacity(), op) destination.limit(response) val opCode = op[0].toInt() when (opCode) { BoringTunJNI.WRITE_TO_NETWORK -> { forwardToGateway() } BoringTunJNI.WIREGUARD_ERROR -> { metrics.onRecoverableError("Wireguard error: ${BoringTunJNI.errors[response]}".ex()) } BoringTunJNI.WIREGUARD_DONE -> { metrics.onRecoverableError("Packet dropped, length: $length".ex()) } else -> { metrics.onRecoverableError("Wireguard write unknown response: $opCode".ex()) } } } private fun toDeviceFromGateway(source: ByteArray, length: Int) { var i = 0 do { op.rewind() val destination = buffer destination.rewind() destination.limit(destination.capacity()) val response = BoringTunJNI.wireguard_read( boringtunHandle, source, if (i++ == 0) length else 0, destination, destination.capacity(), op ) destination.limit(response) // TODO: what if -1 val opCode = op[0].toInt() when (opCode) { BoringTunJNI.WRITE_TO_NETWORK -> { forwardToGateway() } BoringTunJNI.WIREGUARD_ERROR -> { metrics.onRecoverableError("toDevice: wireguard error: ${BoringTunJNI.errors[response]}".ex()) } BoringTunJNI.WIREGUARD_DONE -> { // This conditional is ignoring the "normal operation" errors // It would be nice to know why exactly they happen. if (i == 1 && length != 32) metrics.onRecoverableError("toDevice: packet dropped, length: $length".ex()) } BoringTunJNI.WRITE_TO_TUNNEL_IPV4 -> { //if (adblocking) tunnelFiltering.handleToDevice(destination, length) rewriter.handleToDevice(destination, length) loopback() } BoringTunJNI.WRITE_TO_TUNNEL_IPV6 -> loopback() else -> { metrics.onRecoverableError("toDevice: wireguard unknown response: $opCode".ex()) } } } while (opCode == BoringTunJNI.WRITE_TO_NETWORK) } private fun toDeviceFromProxy(source: ByteArray, length: Int, originEnvelope: Packet) { originEnvelope as IpPacket val udp = originEnvelope.payload as UdpPacket val udpResponse = UdpPacket.Builder(udp) .srcAddr(originEnvelope.header.dstAddr) .dstAddr(originEnvelope.header.srcAddr) .srcPort(udp.header.dstPort) .dstPort(udp.header.srcPort) .correctChecksumAtBuild(true) .correctLengthAtBuild(true) .payloadBuilder(UnknownPacket.Builder().rawData(source)) .length(length.toShort()) val envelope: IpPacket if (originEnvelope is IpV4Packet) { envelope = IpV4Packet.Builder(originEnvelope) .srcAddr(originEnvelope.header.dstAddr) .dstAddr(originEnvelope.header.srcAddr) .correctChecksumAtBuild(true) .correctLengthAtBuild(true) .payloadBuilder(udpResponse) .build() } else { log.w("ipv6 not supported") envelope = IpV6Packet.Builder(originEnvelope as IpV6Packet) .srcAddr(originEnvelope.header.dstAddr as Inet6Address) .dstAddr(originEnvelope.header.srcAddr as Inet6Address) .correctLengthAtBuild(true) .payloadBuilder(udpResponse) .build() } buffer.clear() buffer.put(envelope.rawData) buffer.rewind() buffer.limit(envelope.rawData.size) rewriter.handleToDevice(buffer, envelope.rawData.size) loopback() } private fun forwardToGateway() { val b = buffer packet.setData(b.array(), b.arrayOffset() + b.position(), b.limit()) try { gatewaySocket!!.send(packet) } catch (ex: Exception) { if (handleForwardException(ex)) { sleep(500) // this did not work for some reason // closeGatewaySocket() // openGatewaySocket() throw BlokadaException("Requires thread restart: ${ex.message}") } } } private fun forwardLocally(udp: DatagramPacket, originEnvelope: IpPacket) { val socket = createSocket() try { socket.send(udp) forwarder.add(socket, originEnvelope) } catch (ex: Exception) { try { socket.close() } catch (ex: Exception) {} handleForwardException(ex) } } private fun loopback() { val b = buffer deviceOut.write(b.array(), b.arrayOffset() + b.position(), b.limit()) } private fun openGatewaySocket() { gatewaySocket = createSocket() gatewaySocket?.connect(InetAddress.getByName(gatewayIp), gatewayPort) log.v("Connect to gateway ip: $gatewayIp") } private fun closeGatewaySocket() { log.w("Closing gateway socket") try { gatewayParcelFileDescriptor?.close() } catch (ex: Exception) {} try { gatewaySocket?.close() } catch (ex: Exception) {} gatewayParcelFileDescriptor = null gatewaySocket = null } private fun setupErrorsPipe() = { val pipe = Os.pipe() errorPipe = pipe[0] val errors = StructPollfd() errors.fd = errorPipe errors.listenFor(OsConstants.POLLHUP or OsConstants.POLLERR) errors }() private fun setupDevicePipe(input: FileInputStream) = { this.devicePipe = input.fd val device = StructPollfd() device.fd = input.fd device }() private fun setupGatewayPipe() = { val parcel = ParcelFileDescriptor.fromDatagramSocket(gatewaySocket) val gateway = StructPollfd() gateway.fd = parcel.fileDescriptor gatewayParcelFileDescriptor = parcel gateway }() private fun setupPolls(errors: StructPollfd, device: StructPollfd, gateway: StructPollfd) = { val polls = arrayOfNulls<StructPollfd>(3 + forwarder.size()) as Array<StructPollfd> polls[0] = errors polls[1] = device polls[2] = gateway var i = 0 while (i < forwarder.size()) { polls[3 + i] = forwarder[i].pipe i++ } polls }() private fun poll(polls: Array<StructPollfd>) { while (true) { try { val result = Os.poll(polls, -1) if (result == 0) return if (polls[0].revents.toInt() != 0) { log.w("Poll interrupted") throw InterruptedException() } break } catch (e: ErrnoException) { if (e.errno == OsConstants.EINTR) continue throw e } } } private fun fromDeviceToProxy(device: StructPollfd, input: InputStream) { if (device.isEvent(OsConstants.POLLIN)) { try { val length = input.read(proxyMemory, 0, PACKET_BUFFER_SIZE) if (length > 0) { fromDevice(proxyMemory, length) } } catch (ex: Exception) { // It's safe to ignore read errors if we are just stopping the thread if (!isInterrupted) throw ex } } } private fun fromGatewayToProxy(gateway: StructPollfd) { if (gateway.isEvent(OsConstants.POLLIN)) { packet.setData(memory) gatewaySocket?.receive(packet) ?: log.e("No gateway socket") toDeviceFromGateway(memory, packet.length) } } private fun fromOpenProxySockets(polls: Array<StructPollfd>) { var pollIndex = 0 var socketIndex = 0 while (forwarder.size() > socketIndex) { val rule = forwarder[socketIndex] if (polls[3 + pollIndex++].isEvent(OsConstants.POLLIN)) { try { proxyPacket.data = proxyMemory rule.socket.receive(proxyPacket) toDeviceFromProxy(proxyMemory, proxyPacket.length, rule.originEnvelope) } catch (ex: Exception) { log.w("Failed receiving socket".cause(ex)) } forwarder.close(socketIndex) } else socketIndex++ } } private fun tick() { // TODO: system current time called to often? val now = System.currentTimeMillis() if (now > (lastTickMs + TICK_INTERVAL_MS)) { lastTickMs = now tickWireguard() ticks++ metrics.onLoopExit() metrics.onLoopEnter() DozeService.ensureNotDoze() } } private fun tickWireguard() { op.rewind() val destination = buffer destination.rewind() destination.limit(destination.capacity()) val response = BoringTunJNI.wireguard_tick(boringtunHandle, destination, destination.capacity(), op) destination.limit(response) val opCode = op[0].toInt() when (opCode) { BoringTunJNI.WRITE_TO_NETWORK -> { forwardToGateway() } BoringTunJNI.WIREGUARD_ERROR -> { metrics.onRecoverableError("tick: wireguard error: ${BoringTunJNI.errors[response]}".ex()) } BoringTunJNI.WIREGUARD_DONE -> { } else -> { metrics.onRecoverableError("tick: wireguard timer unknown response: $opCode".ex()) } } } private fun shouldInterruptLoop() = (isInterrupted || this.errorPipe == null) private fun cleanup() { log.v("Cleaning up resources: $this") closeGatewaySocket() try { Os.close(errorPipe) } catch (ex: Exception) {} errorPipe = null // This is managed by the SystemTunnel // try { Os.close(devicePipe) } catch (ex: Exception) {} // devicePipe = null } private var purgeCount = 0 private fun purge() { if (++purgeCount % 1024 == 0) { try { val l = PacketFactoryPropertiesLoader.getInstance() val field = l.javaClass.getDeclaredField("loader") field.isAccessible = true val loader = field.get(l) as PropertiesLoader loader.clearCache() } catch (e: Exception) {} } } }
mpl-2.0
544cd72473bec55c155967a7976e0b95
33.823656
114
0.579263
4.544766
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/blocks/MultiPartBlock.kt
1
6364
package net.ndrei.teslacorelib.blocks import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.client.Minecraft import net.minecraft.creativetab.CreativeTabs import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.RayTraceResult import net.minecraft.util.math.Vec3d import net.minecraft.world.IBlockAccess import net.minecraft.world.World import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import net.ndrei.teslacorelib.blocks.multipart.IBlockPart import net.ndrei.teslacorelib.blocks.multipart.IBlockPartProvider import net.ndrei.teslacorelib.blocks.multipart.MultiPartRayTraceResult import net.ndrei.teslacorelib.utils.getHeldItem abstract class MultiPartBlock(modId: String, tab: CreativeTabs?, registryName: String, material: Material) : RegisteredBlock(modId, tab, registryName, material) { protected open fun getParts(world: World, pos: BlockPos): List<IBlockPart> { val te = world.getTileEntity(pos) if (te is IBlockPartProvider) { // TODO: maybe make this a capability? return te.getParts() } return listOf() } override fun isFullCube(state: IBlockState?) = false override fun isFullBlock(state: IBlockState?) = false override fun getUseNeighborBrightness(state: IBlockState?) = true override fun doesSideBlockRendering(state: IBlockState?, world: IBlockAccess?, pos: BlockPos?, face: EnumFacing?) = false override fun shouldSideBeRendered(blockState: IBlockState?, blockAccess: IBlockAccess?, pos: BlockPos?, side: EnumFacing?) = true //#region RAY TRACE protected open fun transformCollisionAABB(aabb: AxisAlignedBB, state: IBlockState): AxisAlignedBB = aabb private fun AxisAlignedBB.transform(state: IBlockState) = [email protected](this, state) override fun addCollisionBoxToList(state: IBlockState, worldIn: World, pos: BlockPos, entityBox: AxisAlignedBB, collidingBoxes: MutableList<AxisAlignedBB>, entityIn: Entity?, isActualState: Boolean) { this.getParts(worldIn, pos).forEach { if (it.canBeHitWith(worldIn, pos, state, null, ItemStack.EMPTY)) { it.hitBoxes.forEach { Block.addCollisionBoxToList(pos, entityBox, collidingBoxes, it.aabb.transform(state)) } } } } fun rayTrace(world: World, pos: BlockPos, player: EntityPlayer, stack: ItemStack): RayTraceResult? { val start = player.positionVector.add(0.0, player.getEyeHeight().toDouble(), 0.0) var reachDistance = 5.0 if (player is EntityPlayerMP) { reachDistance = player.interactionManager.blockReachDistance } val end = start.add(player.lookVec.normalize().scale(reachDistance)) return this.rayTrace(world, pos, start, end, player, stack) } override fun collisionRayTrace(state: IBlockState, world: World, pos: BlockPos, start: Vec3d, end: Vec3d): RayTraceResult? { val player = Minecraft.getMinecraft().player return this.rayTrace(world, pos, start, end, player, player.getHeldItem()) } fun rayTrace(world: World, pos: BlockPos, start: Vec3d, end: Vec3d, player: EntityPlayer?, stack: ItemStack) = this.getParts(world, pos) .filter { it.canBeHitWith(world, pos, world.getBlockState(pos), player, stack) } .fold<IBlockPart, RayTraceResult?>(null) { b1, part -> part.hitBoxes.fold(b1) { b2, hitBox -> this.computeTrace(b2, pos, start, end, hitBox.aabb.transform(world.getBlockState(pos)), MultiPartRayTraceResult(part, hitBox)) } } private fun computeTrace(lastBest: RayTraceResult?, pos: BlockPos, start: Vec3d, end: Vec3d, aabb: AxisAlignedBB, info: MultiPartRayTraceResult?): RayTraceResult? { val next = super.rayTrace(pos, start, end, aabb) ?: return lastBest next.subHit = if (info == null) -1 else 42 next.hitInfo = info if (lastBest == null) { return next } val distLast = lastBest.hitVec.squareDistanceTo(start) val distNext = next.hitVec.squareDistanceTo(start) return if (distLast > distNext) next else lastBest } @SideOnly(Side.CLIENT) override fun getSelectedBoundingBox(state: IBlockState, world: World, pos: BlockPos): AxisAlignedBB { // val player = Minecraft.getMinecraft().player // val trace = rayTrace(world, pos, player, player.getHeldItem()) val trace = Minecraft.getMinecraft().objectMouseOver if (trace == null || trace.subHit < 0 || pos != trace.blockPos) { return FULL_BLOCK_AABB } val mainId = trace.subHit val info = trace.hitInfo as? MultiPartRayTraceResult val aabb = if ((mainId == 1) && (info != null)) { info.hitBox.aabb.transform(state) } else FULL_BLOCK_AABB return aabb.grow(1 / 32.0).offset(pos) } override fun onBlockActivated(worldIn: World?, pos: BlockPos?, state: IBlockState?, playerIn: EntityPlayer?, hand: EnumHand?, facing: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if ((worldIn != null) && (pos != null) && (playerIn != null)) { val trace = rayTrace(worldIn, pos, playerIn, playerIn.getHeldItem()) if (trace != null) { val info = if (trace.subHit == 42) trace.hitInfo as? MultiPartRayTraceResult else null if (info != null) { val te = worldIn.getTileEntity(pos) if (te is IBlockPartProvider) { // TODO: maybe make this a capability? return te.onPartActivated(playerIn, hand ?: EnumHand.MAIN_HAND, info.part, info.hitBox) } } } } return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ) } //#endregion }
mit
7286b6991455352894415c03640424df
46.849624
204
0.678661
4.189598
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/ieee754/equalsNullableDouble.kt
2
1069
fun equals1(a: Double, b: Double?) = a == b fun equals2(a: Double?, b: Double?) = a!! == b!! fun equals3(a: Double?, b: Double?) = a != null && a == b fun equals4(a: Double?, b: Double?) = if (a is Double) a == b else null!! fun equals5(a: Any?, b: Any?) = if (a is Double && b is Double?) a == b else null!! fun equals6(a: Any?, b: Any?) = if (a is Double? && b is Double) a == b else null!! fun equals7(a: Double?, b: Double?) = a == b fun equals8(a: Any?, b: Any?) = if (a is Double? && b is Double?) a == b else null!! fun box(): String { if (!equals1(-0.0, 0.0)) return "fail 1" if (!equals2(-0.0, 0.0)) return "fail 2" if (!equals3(-0.0, 0.0)) return "fail 3" if (!equals4(-0.0, 0.0)) return "fail 4" if (!equals5(-0.0, 0.0)) return "fail 5" if (!equals6(-0.0, 0.0)) return "fail 6" if (!equals7(-0.0, 0.0)) return "fail 7" if (!equals8(-0.0, 0.0)) return "fail 8" if (!equals8(null, null)) return "fail 9" if (equals8(null, 0.0)) return "fail 10" if (equals8(0.0, null)) return "fail 11" return "OK" }
apache-2.0
6e41a1382b540d26d32796d2d03bd909
30.441176
84
0.553789
2.582126
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/CodeCleanupCheckinHandler.kt
2
6323
// 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.openapi.vcs.checkin import com.intellij.analysis.AnalysisScope import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.CommonProblemDescriptor import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.InspectionProfile import com.intellij.codeInspection.actions.PerformFixesTask import com.intellij.codeInspection.ex.CleanupProblems import com.intellij.codeInspection.ex.GlobalInspectionContextBase import com.intellij.codeInspection.ex.GlobalInspectionContextImpl import com.intellij.lang.LangBundle import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.CommandProcessorEx import com.intellij.openapi.command.UndoConfirmationPolicy import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressWrapper import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.filterOutGeneratedAndExcludedFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.profile.codeInspection.InspectionProfileManager import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.util.SequentialModalProgressTask import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class CodeCleanupCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = CodeCleanupCheckinHandler(panel) } private class CodeCleanupCheckinHandler(private val panel: CheckinProjectPanel) : CheckinHandler(), CheckinMetaHandler, CommitCheck<CommitProblem> { private val project = panel.project private val settings get() = VcsConfiguration.getInstance(project) override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = ProfileChooser(panel, settings::CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT, settings::CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_LOCAL, settings::CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_PROFILE, "before.checkin.cleanup.code", "before.checkin.cleanup.code.profile") override fun runCheckinHandlers(runnable: Runnable) { if (settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT && !DumbService.isDumb(project)) { val filesToProcess = filterOutGeneratedAndExcludedFiles(panel.virtualFiles, project) val globalContext = InspectionManager.getInstance(project).createNewGlobalContext() as GlobalInspectionContextBase val profile = getProfile() globalContext.codeCleanup(AnalysisScope(project, filesToProcess), profile, null, runnable, true) } else { runnable.run() } } override fun isEnabled(): Boolean = settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT override suspend fun runCheck(indicator: ProgressIndicator): CommitProblem? { indicator.text = message("progress.text.inspecting.code") val cleanupProblems = findProblems(indicator) indicator.text = message("progress.text.applying.fixes") indicator.text2 = "" applyFixes(cleanupProblems, indicator) return null } override fun showDetails(problem: CommitProblem) = Unit private suspend fun findProblems(indicator: ProgressIndicator): CleanupProblems { val files = filterOutGeneratedAndExcludedFiles(panel.virtualFiles, project) val globalContext = InspectionManager.getInstance(project).createNewGlobalContext() as GlobalInspectionContextImpl val profile = getProfile() val scope = AnalysisScope(project, files) val wrapper = TextToText2Indicator(ProgressWrapper.wrap(indicator)) return withContext(Dispatchers.Default) { ProgressManager.getInstance().runProcess( Computable { globalContext.findProblems(scope, profile, wrapper) { true } }, wrapper ) } } private fun getProfile(): InspectionProfile { val cleanupProfile = settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_PROFILE if (cleanupProfile != null) { val profileManager = if (settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_LOCAL) InspectionProfileManager.getInstance() else InspectionProjectProfileManager.getInstance(project) return profileManager.getProfile(cleanupProfile) } return InspectionProjectProfileManager.getInstance(project).currentProfile } private suspend fun applyFixes(cleanupProblems: CleanupProblems, indicator: ProgressIndicator) { if (cleanupProblems.files.isEmpty()) return if (!FileModificationService.getInstance().preparePsiElementsForWrite(cleanupProblems.files)) return val commandProcessor = CommandProcessor.getInstance() as CommandProcessorEx commandProcessor.executeCommand { if (cleanupProblems.isGlobalScope) commandProcessor.markCurrentCommandAsGlobal(project) val runner = SequentialModalProgressTask(project, "", true) runner.setMinIterationTime(200) runner.setTask(ApplyFixesTask(project, cleanupProblems.problemDescriptors, indicator)) withContext(Dispatchers.IO) { runner.doRun(NoTextIndicator(indicator)) } } } private suspend fun CommandProcessorEx.executeCommand(block: suspend () -> Unit) { val commandToken = startCommand(project, LangBundle.message("code.cleanup"), null, UndoConfirmationPolicy.DEFAULT)!! try { block() } finally { finishCommand(commandToken, null) } } } private class ApplyFixesTask(project: Project, descriptors: List<CommonProblemDescriptor>, private val indicator: ProgressIndicator) : PerformFixesTask(project, descriptors, null) { override fun beforeProcessing(descriptor: CommonProblemDescriptor) { indicator.text2 = getPresentableText(descriptor) } }
apache-2.0
9be8f2b8eed8009043d469f390224383
42.916667
158
0.790448
4.924455
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/kdoc/IdeKDocLinkResolutionService.kt
1
7102
// 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.kdoc import com.intellij.openapi.project.Project import com.intellij.psi.impl.java.stubs.index.JavaMethodNameIndex import com.intellij.psi.impl.java.stubs.index.JavaShortClassNameIndex import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.isChildOf import org.jetbrains.kotlin.name.isOneSegmentFQN import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.utils.Printer class IdeKDocLinkResolutionService(val project: Project) : KDocLinkResolutionService { override fun resolveKDocLink( context: BindingContext, fromDescriptor: DeclarationDescriptor, resolutionFacade: ResolutionFacade, qualifiedName: List<String> ): Collection<DeclarationDescriptor> { val scope = KotlinSourceFilterScope.projectAndLibrariesSources(GlobalSearchScope.projectScope(project), project) val shortName = qualifiedName.lastOrNull() ?: return emptyList() val targetFqName = FqName.fromSegments(qualifiedName) val functions = KotlinFunctionShortNameIndex.getInstance().get(shortName, project, scope).asSequence() val classes = KotlinClassShortNameIndex.getInstance().get(shortName, project, scope).asSequence() val descriptors = (functions + classes).filter { it.fqName == targetFqName } .map { it.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL) } // TODO Filter out not visible due dependencies config descriptors .toList() if (descriptors.isNotEmpty()) return descriptors val javaClasses = JavaShortClassNameIndex.getInstance().get(shortName, project, scope).asSequence() .filter { it.getKotlinFqName() == targetFqName } .mapNotNull { it.getJavaClassDescriptor() } .toList() if (javaClasses.isNotEmpty()) { return javaClasses } val javaFunctions = JavaMethodNameIndex.getInstance().get(shortName, project, scope).asSequence() .filter { it.getKotlinFqName() == targetFqName } .mapNotNull { it.getJavaMethodDescriptor() } .toList() if (javaFunctions.isNotEmpty()) { return javaFunctions } if (!targetFqName.isRoot && PackageIndexUtil.packageExists(targetFqName, scope, project)) return listOf(GlobalSyntheticPackageViewDescriptor(targetFqName, project, scope)) return emptyList() } } private fun shouldNotBeCalled(): Nothing = throw UnsupportedOperationException("Synthetic PVD for KDoc link resolution") private class GlobalSyntheticPackageViewDescriptor( override val fqName: FqName, private val project: Project, private val scope: GlobalSearchScope ) : PackageViewDescriptor { override fun getContainingDeclaration(): PackageViewDescriptor? = if (fqName.isOneSegmentFQN()) null else GlobalSyntheticPackageViewDescriptor(fqName.parent(), project, scope) override val memberScope: MemberScope = object : MemberScope { override fun getContributedVariables(name: Name, location: LookupLocation): Collection<PropertyDescriptor> = shouldNotBeCalled() override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> = shouldNotBeCalled() override fun getFunctionNames(): Set<Name> = shouldNotBeCalled() override fun getVariableNames(): Set<Name> = shouldNotBeCalled() override fun getClassifierNames(): Set<Name> = shouldNotBeCalled() override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = shouldNotBeCalled() override fun printScopeStructure(p: Printer) { p.printIndent() p.print("GlobalSyntheticPackageViewDescriptorMemberScope (INDEX)") } fun getClassesByNameFilter(nameFilter: (Name) -> Boolean) = KotlinFullClassNameIndex.getInstance() .getAllKeys(project) .asSequence() .filter { it.startsWith(fqName.asString()) } .map(::FqName) .filter { it.isChildOf(fqName) } .filter { nameFilter(it.shortName()) } .flatMap { KotlinFullClassNameIndex.getInstance()[it.asString(), project, scope].asSequence() } .map { it.resolveToDescriptorIfAny() } fun getFunctionsByNameFilter(nameFilter: (Name) -> Boolean) = KotlinTopLevelFunctionFqnNameIndex.getInstance() .getAllKeys(project) .asSequence() .filter { it.startsWith(fqName.asString()) } .map(::FqName) .filter { it.isChildOf(fqName) } .filter { nameFilter(it.shortName()) } .flatMap { KotlinTopLevelFunctionFqnNameIndex.getInstance()[it.asString(), project, scope].asSequence() } .map { it.resolveToDescriptorIfAny() as? DeclarationDescriptor } fun getSubpackages(nameFilter: (Name) -> Boolean) = PackageIndexUtil.getSubPackageFqNames(fqName, scope, project, nameFilter) .map { GlobalSyntheticPackageViewDescriptor(it, project, scope) } override fun getContributedDescriptors( kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean ): Collection<DeclarationDescriptor> = (getClassesByNameFilter(nameFilter) + getFunctionsByNameFilter(nameFilter) + getSubpackages(nameFilter) ).filterNotNull().toList() } override val module: ModuleDescriptor get() = shouldNotBeCalled() override val fragments: List<PackageFragmentDescriptor> get() = shouldNotBeCalled() override fun getOriginal() = this override fun getName(): Name = fqName.shortName() override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R = shouldNotBeCalled() override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?) = shouldNotBeCalled() override val annotations = Annotations.EMPTY }
apache-2.0
41f33bdc6cc6f4b8deceaf0a28b4016e
46.033113
158
0.721909
5.347892
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgSettingBasalProfileAll_k.kt
1
2431
package info.nightscout.androidaps.danaRKorean.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.logging.LTag import java.util.* /** * Created by mike on 05.07.2016. * * * * * THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE */ class MsgSettingBasalProfileAll_k( injector: HasAndroidInjector ) : MessageBase(injector) { init { SetCommand(0x3206) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { danaPump.pumpProfiles = Array(4) { Array(48) { 0.0 } } if (danaPump.basal48Enable) { for (profile in 0..3) { val position = intFromBuff(bytes, 107 * profile, 1) for (index in 0..47) { var basal = intFromBuff(bytes, 107 * profile + 2 * index + 1, 2) if (basal < 10) basal = 0 danaPump.pumpProfiles!![position][index] = basal / 100 / 24.0 // in units/day } } } else { for (profile in 0..3) { val position = intFromBuff(bytes, 49 * profile, 1) aapsLogger.debug(LTag.PUMPCOMM, "position $position") for (index in 0..23) { var basal = intFromBuff(bytes, 59 * profile + 2 * index + 1, 2) if (basal < 10) basal = 0 aapsLogger.debug(LTag.PUMPCOMM, "position $position index $index") danaPump.pumpProfiles!![position][index] = basal / 100 / 24.0 // in units/day } } } if (danaPump.basal48Enable) { for (profile in 0..3) { for (index in 0..23) { aapsLogger.debug(LTag.PUMPCOMM, "Basal profile " + profile + ": " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaPump.pumpProfiles!![profile][index]) } } } else { for (profile in 0..3) { for (index in 0..47) { aapsLogger.debug(LTag.PUMPCOMM, "Basal profile " + profile + ": " + String.format(Locale.ENGLISH, "%02d", index / 2) + ":" + String.format(Locale.ENGLISH, "%02d", index % 2 * 30) + " : " + danaPump.pumpProfiles!![profile][index]) } } } } }
agpl-3.0
0a3de517ea859bf5679a2d0dd022c580
37
183
0.521596
4.155556
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAWSWAF.kt
1
5380
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.waf.AbstractAWSWAF import com.amazonaws.services.waf.AWSWAF import com.amazonaws.services.waf.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAWSWAF(val context: IacContext) : AbstractAWSWAF(), AWSWAF { override fun createByteMatchSet(request: CreateByteMatchSetRequest): CreateByteMatchSetResult { return with (context) { request.registerWithAutoName() CreateByteMatchSetResult().withByteMatchSet( makeProxy<CreateByteMatchSetRequest, ByteMatchSet>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateByteMatchSetRequest::getName to ByteMatchSet::getName ) ) ).registerWithSameNameAs(request) } } override fun createIPSet(request: CreateIPSetRequest): CreateIPSetResult { return with (context) { request.registerWithAutoName() CreateIPSetResult().withIPSet( makeProxy<CreateIPSetRequest, IPSet>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateIPSetRequest::getName to IPSet::getName ) ) ).registerWithSameNameAs(request) } } override fun createRule(request: CreateRuleRequest): CreateRuleResult { return with (context) { request.registerWithAutoName() CreateRuleResult().withRule( makeProxy<CreateRuleRequest, Rule>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateRuleRequest::getName to Rule::getName, CreateRuleRequest::getMetricName to Rule::getMetricName ) ) ).registerWithSameNameAs(request) } } override fun createSizeConstraintSet(request: CreateSizeConstraintSetRequest): CreateSizeConstraintSetResult { return with (context) { request.registerWithAutoName() CreateSizeConstraintSetResult().withSizeConstraintSet( makeProxy<CreateSizeConstraintSetRequest, SizeConstraintSet>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateSizeConstraintSetRequest::getName to SizeConstraintSet::getName ) ) ).registerWithSameNameAs(request) } } override fun createSqlInjectionMatchSet(request: CreateSqlInjectionMatchSetRequest): CreateSqlInjectionMatchSetResult { return with (context) { request.registerWithAutoName() CreateSqlInjectionMatchSetResult().withSqlInjectionMatchSet( makeProxy<CreateSqlInjectionMatchSetRequest, SqlInjectionMatchSet>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateSqlInjectionMatchSetRequest::getName to SqlInjectionMatchSet::getName ) ) ).registerWithSameNameAs(request) } } override fun createWebACL(request: CreateWebACLRequest): CreateWebACLResult { return with (context) { request.registerWithAutoName() CreateWebACLResult().withWebACL( makeProxy<CreateWebACLRequest, WebACL>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateWebACLRequest::getName to WebACL::getName, CreateWebACLRequest::getMetricName to WebACL::getMetricName, CreateWebACLRequest::getDefaultAction to WebACL::getDefaultAction ) ) ).registerWithSameNameAs(request) } } override fun createXssMatchSet(request: CreateXssMatchSetRequest): CreateXssMatchSetResult { return with (context) { request.registerWithAutoName() CreateXssMatchSetResult().withXssMatchSet( makeProxy<CreateXssMatchSetRequest, XssMatchSet>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateXssMatchSetRequest::getName to XssMatchSet::getName ) ) ).registerWithSameNameAs(request) } } } class DeferredAWSWAF(context: IacContext) : BaseDeferredAWSWAF(context)
mit
d04f18d1daefb71b34ce751d9c8e6943
40.705426
123
0.572305
5.899123
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/api/http/ApiResult.kt
1
837
package com.jetbrains.packagesearch.intellij.plugin.api.http internal sealed class ApiResult<T : Any> { data class Success<T : Any>(val result: T) : ApiResult<T>() data class Failure<T : Any>(val throwable: Throwable) : ApiResult<T>() val isSuccess: Boolean get() = this is Success val isFailure: Boolean get() = this !is Success inline fun <V : Any> mapSuccess(action: (T) -> V) = if (isSuccess) { Success(action((this as Success<T>).result)) } else { @Suppress("UNCHECKED_CAST") this as Failure<V> } inline fun onFailure(action: (Throwable) -> Unit) = apply { if (this is Failure<*>) action(throwable) } inline fun onSuccess(action: (T) -> Unit) = apply { if (this is Success<T>) action(result) } }
apache-2.0
942dc958d016cdb413c4829622da3fda
26.9
74
0.590203
3.948113
false
false
false
false
jwren/intellij-community
python/build/testSrc/org/jetbrains/intellij/build/pycharm/PyCharmCommunityBuildTest.kt
1
900
// 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.intellij.build.pycharm import com.intellij.openapi.application.PathManager import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.testFramework.runTestBuild import org.junit.Test class PyCharmCommunityBuildTest { @Test fun testBuild() { val homePath = PathManager.getHomePathFor(javaClass)!! val communityHomePath = "$homePath/community" runTestBuild( homePath = communityHomePath, communityHomePath = communityHomePath, productProperties = PyCharmCommunityProperties(communityHomePath), ) { it.projectClassesOutputDirectory = System.getProperty(BuildOptions.PROJECT_CLASSES_OUTPUT_DIRECTORY_PROPERTY) ?: "$homePath/out/classes" } } }
apache-2.0
899413e5dcf4899a3b67737adf44c8ac
38.173913
120
0.743333
4.761905
false
true
false
false
JetBrains/kotlin-native
performance/numerical/src/main/kotlin/pi.kt
4
3337
/* * Computation of the n'th decimal digit of \pi with very little memory. * Written by Fabrice Bellard on January 8, 1997. * * We use a slightly modified version of the method described by Simon * Plouffe in "On the Computation of the n'th decimal digit of various * transcendental numbers" (November 1996). We have modified the algorithm * to get a running time of O(n^2) instead of O(n^3log(n)^3). */ import kotlin.math.ln import kotlin.math.sqrt private fun mul_mod(a: Int, b: Int, m: Int) = ((a.toLong() * b.toLong()) % m).toInt() /* return the inverse of x mod y */ private fun inv_mod(x: Int, y: Int): Int { var u = x var v = y var c = 1 var a = 0 do { val q = v / u var t = c c = a - q * c a = t t = u u = v - q * u v = t } while (u != 0) a = a % y if (a < 0) a = y + a return a } /* return (a^b) mod m */ private fun pow_mod(a: Int, b: Int, m: Int): Int { var b = b var r = 1 var aa = a while (true) { if (b and 1 != 0) r = mul_mod(r, aa, m) b = b shr 1 if (b == 0) break aa = mul_mod(aa, aa, m) } return r } /* return true if n is prime */ private fun is_prime(n: Int): Boolean { if (n % 2 == 0) return false val r = sqrt(n.toDouble()).toInt() var i = 3 while (i <= r) { if (n % i == 0) return false i += 2 } return true } /* return the prime number immediatly after n */ private fun next_prime(n: Int): Int { var n = n do { n++ } while (!is_prime(n)) return n } fun pi_nth_digit(n: Int): Int { val N = ((n + 20) * ln(10.0) / ln(2.0)).toInt() var sum = 0.0 var a = 3 var t: Int while (a <= 2 * N) { val vmax = (ln((2 * N).toDouble()) / ln(a.toDouble())).toInt() var av = 1 var i = 0 while (i < vmax) { av = av * a i++ } var s = 0 var num = 1 var den = 1 var v = 0 var kq = 1 var kq2 = 1 var k = 1 while (k <= N) { t = k if (kq >= a) { do { t = t / a v-- } while (t % a == 0) kq = 0 } kq++ num = mul_mod(num, t, av) t = 2 * k - 1 if (kq2 >= a) { if (kq2 == a) { do { t = t / a v++ } while (t % a == 0) } kq2 -= a } den = mul_mod(den, t, av) kq2 += 2 if (v > 0) { t = inv_mod(den, av) t = mul_mod(t, num, av) t = mul_mod(t, k, av) i = v while (i < vmax) { t = mul_mod(t, a, av) i++ } s += t if (s >= av) s -= av } k++ } t = pow_mod(10, n - 1, av) s = mul_mod(s, t, av) sum = (sum + s.toDouble() / av.toDouble()) % 1.0 a = next_prime(a) } return (sum * 1e9).toInt() }
apache-2.0
67eb2dbc766e66e4d5ff2b8e5c6fd1f4
20.953947
74
0.38148
3.30396
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/support/utils/OsVersionUtils.kt
1
529
package com.maubis.scarlet.base.support.utils import android.os.Build object OsVersionUtils { fun canExtractReferrer() = Build.VERSION.SDK_INT >= 22 fun requiresPermissions() = Build.VERSION.SDK_INT >= 23 fun canSetStatusBarTheme() = Build.VERSION.SDK_INT >= 23 fun canExtractActiveNotifications() = Build.VERSION.SDK_INT >= 23 fun canAddLauncherShortcuts() = Build.VERSION.SDK_INT >= 26 fun canAddNotificationChannels() = Build.VERSION.SDK_INT >= 26 fun canUseSystemTheme() = Build.VERSION.SDK_INT >= 29 }
gpl-3.0
e1d270a0b5f42f55a0187448d37595ed
26.842105
67
0.741021
3.805755
false
false
false
false
c4akarl/Escalero
app/src/main/java/com/androidheads/vienna/escalero/BoardView.kt
1
31862
/* Escalero - An Android dice program. Copyright (C) 2016-2021 Karl Schreiner, [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.androidheads.vienna.escalero import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import androidx.core.content.ContextCompat import java.util.* import kotlin.math.min import kotlin.math.sqrt class BoardView(context: Context, attrs: AttributeSet) : View(context, attrs) { private var prefs = context.getSharedPreferences("prefs", 0) private var diceSize = 1 private var isInit = true private var diceIcons: IntArray? = null var mBoardWidth: Int = 0 var mBoardHeight: Int = 0 private var mBoardBorderWidth: Int = 0 private var mDiceSize = 50 private var mDiceSizeSmall = 0 private var mDiceSizeMedium = 0 private var mDiceSizeLarge = 0 private var mHoldAreaWidth = 5 * mDiceSize private var mHoldAreaHeight = mDiceSize private var mRoll = IntArray(5) // roll image values private var mHold = IntArray(5) // hold image values private var mDouble1 = IntArray(5) // double first playerName image values private var mColValues: String? = null // column values + bonus private var mIsSingle: Boolean = false // single/double private var mPlayerToMove: Char = ' ' // 'A' 'B' 'C' private var mPlayerInfo: String = "" // info playerName private var mPlayerInfoDouble: String = "" // info double first playerName var mOnlinePlayers: String = "" // online players private var mIsSelectable: Boolean = false // is roll/hold/double1 selectable ---> VALUES/state private var doubleState: Int = 0 // double state: 0=keine Anzeige, 1= Anzeige mit select, 2=nur Anzeige private val diceCnt = 5 // max number of dices private val diceValues = 7 // id,state,x,y,diceWidth,diceHeight,rotation (id : res/values/ids, state : 0=unvisible, 1=visible+click, 3=visible) private var mHoldIdx = IntArray(diceCnt) // [index from mHold] private var mRollValues = Array(diceCnt) { IntArray(diceValues) } // [index from mRoll][VALUES] private var mHoldValues = Array(diceCnt) { IntArray(diceValues) } // [index from mHold][VALUES] private var mDouble1Values = Array(diceCnt) { IntArray(diceValues) } // [index from mDouble1][VALUES] private var mControlValues = Array(diceCnt) { IntArray(diceValues) } // [1=double1Btn, 2=playerInfo, 3=playerInfoDouble][VALUES] private val mRand = Random() private var mPaint: Paint? = null private val mRect: Rect init { diceSize = prefs.getInt("diceSize", 2) mIsSingle = prefs.getBoolean("isSingleGame", true) if (diceSize == 3 && !mIsSingle) diceSize = 2 isInit = true initValues(true) mPaint = Paint() mRect = Rect() } private fun initValues(initRollValues: Boolean) { var initValues = initRollValues if (!initValues) { for (i in 0 until diceCnt) { for (j in 0 until diceValues) { if (mRollValues[i][2] <= 0) initValues = true if (mRollValues[i][3] <= 0) initValues = true if (mRollValues[i][4] <= 0) initValues = true if (mRollValues[i][5] <= 0) initValues = true } } } for (i in 0 until diceCnt) { for (j in 0 until diceValues) { if (j == 0) // id { when (i) { 0 -> { mRollValues[i][0] = R.id.dbRoll_1 mHoldValues[i][0] = R.id.dbHold_1 mDouble1Values[i][0] = R.id.dbDouble_1 mControlValues[i][0] = 0 } 1 -> { mRollValues[i][0] = R.id.dbRoll_2 mHoldValues[i][0] = R.id.dbHold_2 mDouble1Values[i][0] = R.id.dbDouble_2 mControlValues[i][0] = R.id.dbD1 } 2 -> { mRollValues[i][0] = R.id.dbRoll_3 mHoldValues[i][0] = R.id.dbHold_3 mDouble1Values[i][0] = R.id.dbDouble_3 mControlValues[i][0] = R.id.dbPlayerInfo } 3 -> { mRollValues[i][0] = R.id.dbRoll_4 mHoldValues[i][0] = R.id.dbHold_4 mDouble1Values[i][0] = R.id.dbDouble_4 mControlValues[i][0] = R.id.dbPlayerInfoDouble1 } 4 -> { mRollValues[i][0] = R.id.dbRoll_5 mHoldValues[i][0] = R.id.dbHold_5 mDouble1Values[i][0] = R.id.dbDouble_5 mControlValues[i][0] = 0 } } } else { if (initValues) mRollValues[i][j] = 0 mHoldValues[i][j] = 0 mDouble1Values[i][j] = 0 mControlValues[i][j] = 0 } } } } fun setDiceIcons(diceIcons: IntArray) { this.diceIcons = diceIcons } fun setDiceSize() { diceSize = prefs.getInt("diceSize", 2) if (diceSize == 3 && !mIsSingle) diceSize = 2 when (diceSize) { 1 -> mDiceSize = mDiceSizeSmall 2 -> mDiceSize = mDiceSizeMedium 3 -> mDiceSize = mDiceSizeLarge } mHoldAreaWidth = 5 * mDiceSize mHoldAreaHeight = mDiceSize } fun initBoard() { isInit = true invalidate() } fun setRoundValues(colValues: String, isSingle: Boolean, playerToMove: Char, playerInfo: String, playerInfoDouble: String, onlinePlayers: String) { // Log.i(TAG, "setRoundValues(), isSingle: $isSingle, playerInfoDouble: $playerInfoDouble") mColValues = colValues mIsSingle = isSingle mPlayerToMove = playerToMove mPlayerInfo = playerInfo mPlayerInfoDouble = playerInfoDouble mOnlinePlayers = onlinePlayers } fun updateBoard(roll: IntArray, hold: IntArray, double1: IntArray, isSelectable: Boolean, doubleState: Int, initRollValues: Boolean) { // Log.i(TAG, "updateBoard(), roll: $roll, hold: $hold, double1: $double1") // Log.i(TAG, "updateBoard(), mBoardWidth: $mBoardWidth, mBoardHeight: $mBoardHeight, initRollValues: $initRollValues") // Log.i(TAG, "updateBoard(), doubleState: $doubleState, double1.size: ${double1.size}") if ((mBoardWidth <= 0) or (mBoardHeight <= 0)) return isInit = false mRoll = roll mHold = hold // Log.i(TAG, "updateBoard(), mRoll: ${mRoll[0]}, ${mRoll[1]}, ${mRoll[2]}, ${mRoll[3]}, ${mRoll[4]}") // Log.i(TAG, "updateBoard(), mHold: ${mHold[0]}, ${mHold[1]}, ${mHold[2]}, ${mHold[3]}, ${mHold[4]}") mDouble1 = double1 mIsSelectable = isSelectable this.doubleState = doubleState initValues(initRollValues) // Log.i(TAG, "updateBoard(), mIsSingle: $mIsSingle, doubleState: $doubleState, mPlayerInfoDouble: $mPlayerInfoDouble") setControlValues(mIsSingle, doubleState, mPlayerInfo, mControlValues) setRollValues(mRoll, mRollValues, isSelectable, initRollValues) setHoldValues(mHold, mHoldIdx, mHoldValues, isSelectable) // Log.i(TAG, "updateBoard(), mDouble1: ${mDouble1[0]}, ${mDouble1[1]}, ${mDouble1[2]}, ${mDouble1[3]}, ${mDouble1[4]}") // Log.i(TAG, "updateBoard(), mDouble1Values: ${mDouble1Values[0]}, ${mDouble1Values[1]}, ${mDouble1Values[2]}, ${mDouble1Values[3]}, ${mDouble1Values[4]}") setDoubleValues(mDouble1, mDouble1Values) invalidate() } fun getIdFromTouchPoint(touchPoint: Point): Int { for (i in 0 until diceCnt) { if (mRollValues[i][1] == 1) // state: visible & selectable { val rollAreaWidth = sqrt((mRollValues[i][4] * mRollValues[i][4] + mRollValues[i][5] * mRollValues[i][5]).toDouble()).toInt() val x1 = mRollValues[i][2] val y1 = mRollValues[i][3] val x2 = mRollValues[i][2] + rollAreaWidth val y2 = mRollValues[i][3] + rollAreaWidth val rect = Rect(x1, y1, x2, y2) if (rect.contains(touchPoint.x, touchPoint.y)) return mRollValues[i][0] } } for (i in 0 until diceCnt) { if (mHoldValues[i][1] == 1) // state: visible & selectable { val x1 = mHoldValues[i][2] val y1 = mHoldValues[i][3] val x2 = mHoldValues[i][2] + mHoldValues[i][4] val y2 = mHoldValues[i][3] + mHoldValues[i][5] val rect = Rect(x1, y1, x2, y2) if (rect.contains(touchPoint.x, touchPoint.y)) return mHoldValues[i][0] } } for (i in 0 until diceCnt) { if (mControlValues[i][1] == 1) // state: visible & selectable { val x1 = mControlValues[i][2] val y1 = mControlValues[i][3] val x2 = mControlValues[i][2] + mControlValues[i][4] val y2 = mControlValues[i][3] + mControlValues[i][5] // Log.i(TAG, "getIdFromTouchPoint(), x1: $x1, y1: $y1, x2: $x2, y2: $y2") // Log.i(TAG, "getIdFromTouchPoint(), resId: ${mControlValues[i][0]}") val rect = Rect(x1, y1, x2, y2) if (rect.contains(touchPoint.x, touchPoint.y)) return mControlValues[i][0] } } return 0 } fun getHoldIdFromBoard(boardHoldId: Int): Int { return mHoldIdx[boardHoldId] } private fun setRollValues(roll: IntArray, rollValues: Array<IntArray>, isSelectable: Boolean, initRollValues: Boolean) { var r: Int for (i in 0 until diceCnt) { //Log.i(TAG, "bWidth: " + mBoardWidth + ", bHeight: " + mBoardHeight + ", x: " + pt.x + ", y: " + pt.y + ", mDiceWidth: " + mDiceWidth); rollValues[i][1] = 0 if (roll[i] >= 0) { if (isSelectable) rollValues[i][1] = 1 else rollValues[i][1] = 2 } if (initRollValues) { r = mRand.nextInt(360) // rotation val pt = getFreeRollPoint(i, rollValues) rollValues[i][2] = pt.x rollValues[i][3] = pt.y rollValues[i][4] = mDiceSize rollValues[i][5] = mDiceSize rollValues[i][6] = r } } } private fun setHoldValues(hold: IntArray, holdIdx: IntArray, holdValues: Array<IntArray>, isSelectable: Boolean) { var idx = 0 for (j in holdIdx.indices) { holdIdx[j] = -1 } // sort hold values val valuesHold = IntArray(6) val valuesRoll = IntArray(6) for (j in valuesHold.indices) { valuesHold[j] = 0 valuesRoll[j] = 0 } for (i in hold.indices) { if (hold[i] >= 0) valuesHold[hold[i]] = valuesHold[hold[i]] + 1 } var max = 0 for (i in valuesHold.indices) { if (valuesHold[i] + valuesRoll[i] > max) max = valuesHold[i] + valuesRoll[i] } var isStraight = false if ((max == 1) and !((valuesHold[0] + valuesRoll[0] == 1) and (valuesHold[5] + valuesRoll[5] == 1))) isStraight = true if (isStraight) // 9...A { for (i in 0..5) { for (j in hold.indices) { if (hold[j] == i) { holdIdx[idx] = j idx++ } } } } else // A...9 { for (i in 5 downTo 1) { for (h in valuesHold.indices.reversed()) { if (valuesHold[h] == i) { for (j in hold.indices) { if (hold[j] == h) { holdIdx[idx] = j idx++ } } } } } } var x = mBoardBorderWidth val y = mBoardHeight - mBoardBorderWidth - mDiceSize for (i in 0 until diceCnt) { holdValues[i][1] = 0 if (holdIdx[i] >= 0) { if (isSelectable) holdValues[i][1] = 1 else holdValues[i][1] = 2 } else { if (isSelectable) { holdValues[i][0] = R.id.dbHoldFast holdValues[i][1] = 1 } } holdValues[i][2] = x holdValues[i][3] = y holdValues[i][4] = mDiceSize holdValues[i][5] = mDiceSize holdValues[i][6] = 0 x += mDiceSize } } private fun setDoubleValues(double1: IntArray, double1Values: Array<IntArray>) { // sort doubleValues if (double1[0] >= 0) { val valuesDouble1 = IntArray(6) val doubleNew1 = IntArray(5) for (j in valuesDouble1.indices) { valuesDouble1[j] = 0 } for (i in double1.indices) { if (double1[i] >= 0) valuesDouble1[double1[i]] = valuesDouble1[double1[i]] + 1 } var max = 0 var idx = 0 for (i in valuesDouble1.indices) { if (valuesDouble1[i] > max) max = valuesDouble1[i] } var isStraight = false if ((max == 1) and !((valuesDouble1[0] == 1) and (valuesDouble1[5] == 1))) isStraight = true if (isStraight) // 9...A { for (i in 0..5) { for (j in double1.indices) { if (double1[j] == i) { doubleNew1[idx] = double1[j] idx++ } } } } else // A...9 { for (i in 5 downTo 1) { for (h in valuesDouble1.indices.reversed()) { if (valuesDouble1[h] == i) { for (j in double1.indices) { if (double1[j] == h) { doubleNew1[idx] = double1[j] idx++ } } } } } } mDouble1 = doubleNew1 } // setDoubleValues var x = mBoardWidth - mBoardBorderWidth - mHoldAreaWidth val y = mBoardBorderWidth for (i in 0 until diceCnt) { double1Values[i][1] = 2 if (double1[0] < 0) double1Values[i][1] = 0 double1Values[i][2] = x double1Values[i][3] = y double1Values[i][4] = mDiceSize double1Values[i][5] = mDiceSize double1Values[i][6] = 0 x += mDiceSize } } private fun setControlValues(isSingle: Boolean, doubleState: Int, playerInfo: String, controlValues: Array<IntArray>) { // Log.i(TAG, "setControlValues(), isSingle: $isSingle, doubleState: $doubleState, playerInfoDouble: $playerInfoDouble") // Log.i(TAG, "setControlValues(), bW: $mBoardWidth, bH: $mBoardWidth, bbW: $mBoardBorderWidth, haW: $mHoldAreaWidth, haH: $mHoldAreaHeight, dS: $mDiceSize") controlValues[0][1] = 0 controlValues[1][1] = 0 controlValues[2][1] = 0 controlValues[3][1] = 0 // init state if (!isSingle) { // Log.i(TAG, "setControlValues(), [1]") controlValues[1][1] = doubleState controlValues[1][2] = mBoardWidth - mBoardBorderWidth - mHoldAreaWidth - 20 controlValues[1][3] = mBoardBorderWidth + 10 controlValues[1][4] = mHoldAreaWidth controlValues[1][5] = mHoldAreaHeight controlValues[1][6] = 0 } if (playerInfo != "") { // Log.i(TAG, "setControlValues(), [2]") controlValues[2][1] = 1 controlValues[2][2] = mBoardWidth - 200 controlValues[2][3] = mBoardHeight - mBoardBorderWidth - mDiceSize * 2 - 10 controlValues[2][4] = 180 controlValues[2][5] = mDiceSize * 60 / 100 // 60 % of dice tableHeight controlValues[2][6] = 0 } if (!isSingle) { // Log.i(TAG, "setControlValues(), [3]") controlValues[3][1] = doubleState controlValues[3][2] = mBoardWidth - 200 controlValues[3][3] = mBoardBorderWidth + mDiceSize + 40 controlValues[3][4] = 180 controlValues[3][5] = mDiceSize * 60 / 100 // 60 % of dice tableHeight controlValues[3][6] = 0 } } private fun getFreeRollPoint(rollId: Int, rollValues: Array<IntArray>): Point { val numberOfHoldArea = if (mIsSingle) 1 else 2 val gridWidth = sqrt((mDiceSize * mDiceSize + mDiceSize * mDiceSize).toDouble()).toInt() val gridX = (mBoardWidth - 2 * mBoardBorderWidth) / gridWidth val gridY = (mBoardHeight - 2 * mBoardBorderWidth - numberOfHoldArea * mDiceSize) / gridWidth // 20190223, java.lang.NegativeArraySizeException: val gridPoints = arrayOfNulls<Point>(gridX * gridY) if (gridX < 0 || gridY < 0) return Point(mBoardBorderWidth, mBoardBorderWidth) var gridPointsSize = 0 for (k in 0 until gridX) // check all possible grid points if free for (j in 0 until gridY) { val xGridPoint = mBoardBorderWidth + k * gridWidth val yGridPoint = mBoardBorderWidth + (numberOfHoldArea - 1) * mDiceSize + j * gridWidth var isFree = true for (i in 0 until rollId) // check previous roll dices { if (rollValues[i][2] == xGridPoint && rollValues[i][3] == yGridPoint) { isFree = false break } } if (isFree) gridPoints[gridPointsSize++] = Point(xGridPoint, yGridPoint) } if (gridPointsSize > 0) { val n = mRand.nextInt(gridPointsSize) gridPoints[n]?.let { value -> return value} return Point(mBoardBorderWidth, mBoardBorderWidth + (numberOfHoldArea - 1) * mDiceSize) } else return Point(mBoardBorderWidth, mBoardBorderWidth + (numberOfHoldArea - 1) * mDiceSize) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // Log.i(TAG, "onDraw(), diceSize: $diceSize, mDiceSize: $mDiceSize, mRollValues[0][4]: ${mRollValues[0][4]}") drawBoard(canvas) if (!isInit && mRollValues[0][4] > 0) drawImages(canvas) isInit = false } private fun drawBoard(canvas: Canvas) { mPaint!!.style = Paint.Style.FILL mPaint!!.color = ContextCompat.getColor(context, R.color.colorBoard) mRect.set(0, 0, mBoardWidth - 1, mBoardHeight - 1) canvas.drawRect(mRect, mPaint!!) mPaint!!.style = Paint.Style.STROKE mPaint!!.color = ContextCompat.getColor(context, R.color.colorBoardBorder) mPaint!!.strokeWidth = (mBoardBorderWidth * 2).toFloat() mRect.set(0, 0, mBoardWidth - 1, mBoardHeight - 1) canvas.drawRect(mRect, mPaint!!) if (mColValues != null) { mPaint!!.reset() mPaint!!.color = ContextCompat.getColor(context, R.color.colorLabel) var textSize = mDiceSize if (diceSize == 3) textSize = (textSize * 0.6f).toInt() mPaint!!.textSize = textSize.toFloat() var bounds = Rect() val textEscalero = resources.getString(R.string.escalero) var text = "" val l = textEscalero.length for (i in 0 until l) { text = text + textEscalero[i] + " " } mPaint!!.getTextBounds(text, 0, text.length, bounds) var x = mBoardWidth / 2 - bounds.width() / 2 var y = mBoardHeight / 2 - bounds.height() / 2 + (mDiceSize * 0.6f).toInt() canvas.drawText(text, x.toFloat(), y.toFloat(), mPaint!!) mPaint!!.textSize = textSize * 0.6f bounds = Rect() var gameType = resources.getString(R.string.typeSingle) if (!mIsSingle) gameType = resources.getString(R.string.typeDouble) val game = "$gameType ($mColValues)" mPaint!!.getTextBounds(game, 0, game.length, bounds) x = mBoardWidth / 2 - bounds.width() / 2 y = mBoardHeight / 2 - bounds.height() / 2 + (mDiceSize * 0.6f).toInt() + (mDiceSize * 0.6f).toInt() canvas.drawText(game, x.toFloat(), y.toFloat(), mPaint!!) if (mOnlinePlayers.isNotEmpty()) { mPaint!!.textSize = textSize * 0.6f bounds = Rect() val strResult = mOnlinePlayers.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in strResult.indices) { mPaint!!.getTextBounds(strResult[i], 0, strResult[i].length, bounds) x = mBoardWidth / 2 - bounds.width() / 2 y = mBoardHeight / 2 - bounds.height() / 2 + (mDiceSize * 0.6f).toInt() when (strResult.size) { 1 -> { y -= textSize + (mDiceSize * 0.2f).toInt() } 2 -> { y -= if (i == 0) textSize + (mDiceSize * 0.8f).toInt() else textSize + (mDiceSize * 0.2f).toInt() } } canvas.drawText(strResult[i], x.toFloat(), y.toFloat(), mPaint!!) } } } } private fun drawImages(canvas: Canvas) { mPaint!!.isAntiAlias = true // hold area border button for (i in 0 until diceCnt) { if (mHoldValues[i][4] > 0) { var bm = BitmapFactory.decodeResource(resources, R.drawable.button_border) bm = Bitmap.createScaledBitmap(bm, mHoldValues[i][4], mHoldValues[i][5], false) canvas.drawBitmap(bm, mHoldValues[i][2].toFloat(), mHoldValues[i][3].toFloat(), mPaint) } } // double area border button if (!mIsSingle) { for (i in 0 until diceCnt) { if (mDouble1Values[i][4] > 0) { var bm = BitmapFactory.decodeResource(resources, R.drawable.button_border) bm = Bitmap.createScaledBitmap(bm, mDouble1Values[i][4], mDouble1Values[i][5], false) canvas.drawBitmap(bm, mDouble1Values[i][2].toFloat(), mDouble1Values[i][3].toFloat(), mPaint) } } } // roll for (i in 0 until diceCnt) { if ((mRollValues[i][1] != 0) and (mRoll[i] >= 0)) // state { var bm = BitmapFactory.decodeResource(resources, diceIcons!![mRoll[i]]) bm = Bitmap.createScaledBitmap(bm, mRollValues[i][4], mRollValues[i][5], false) val matrix = Matrix() matrix.preRotate(mRollValues[i][6].toFloat()) val bitmap = Bitmap.createBitmap(bm, 0, 0, mRollValues[i][4], mRollValues[i][5], matrix, false) canvas.drawBitmap(bitmap, mRollValues[i][2].toFloat(), mRollValues[i][3].toFloat(), mPaint) } } // hold for (i in 0 until diceCnt) { if ((mHoldValues[i][1] != 0) and (mHoldIdx[i] >= 0)) { if (mHold[mHoldIdx[i]] >= 0) { var bm = BitmapFactory.decodeResource(resources, diceIcons!![mHold[mHoldIdx[i]]]) bm = Bitmap.createScaledBitmap(bm, mHoldValues[i][4], mHoldValues[i][5], false) canvas.drawBitmap(bm, mHoldValues[i][2].toFloat(), mHoldValues[i][3].toFloat(), mPaint) } } } // double if (!mIsSingle and (mControlValues[1][1] != 0)) { for (i in 0 until diceCnt) { if ((mDouble1Values[i][1] != 0) and (mDouble1[i] >= 0)) // state { var bm = BitmapFactory.decodeResource(resources, diceIcons!![mDouble1[i]]) bm = Bitmap.createScaledBitmap(bm, mDouble1Values[i][4], mDouble1Values[i][5], false) canvas.drawBitmap(bm, mDouble1Values[i][2].toFloat(), mDouble1Values[i][3].toFloat(), mPaint) } } } // controls // btn info playerName if (mControlValues[2][1] != 0) { mPaint = Paint() mPaint!!.color = Color.BLACK mPaint!!.textSize = mControlValues[2][5].toFloat() val bounds = Rect() mPaint!!.getTextBounds(mPlayerInfo, 0, mPlayerInfo.length, bounds) val x = mBoardWidth - mBoardBorderWidth * 2 - bounds.width() val y = mBoardHeight - mBoardBorderWidth * 2 val b = 2 var color = ContextCompat.getColor(context, R.color.colorPlayerA) if (mPlayerToMove == 'B') color = ContextCompat.getColor(context, R.color.colorPlayerB) if (mPlayerToMove == 'C') color = ContextCompat.getColor(context, R.color.colorPlayerC) val paintRect = Paint() paintRect.style = Paint.Style.FILL paintRect.color = color mRect.set(x - b, y - bounds.height() - b, x + bounds.width() + b, y + b) canvas.drawRect(mRect, paintRect) canvas.drawText(mPlayerInfo, x.toFloat(), y.toFloat(), mPaint!!) } // info double first playerName if (mControlValues[3][1] != 0) { mPaint = Paint() mPaint!!.color = Color.BLACK mPaint!!.textSize = mControlValues[3][5].toFloat() val bounds = Rect() mPaint!!.getTextBounds(mPlayerInfoDouble, 0, mPlayerInfoDouble.length, bounds) val x = mBoardWidth - mBoardBorderWidth * 2 - bounds.width() val y = mBoardBorderWidth + mDiceSize val b = 2 var color = ContextCompat.getColor(context, R.color.colorPlayerA) if (mPlayerToMove == 'B') color = ContextCompat.getColor(context, R.color.colorPlayerB) if (mPlayerToMove == 'C') color = ContextCompat.getColor(context, R.color.colorPlayerC) val paintRect = Paint() paintRect.style = Paint.Style.FILL paintRect.color = color mRect.set(x - b, y - bounds.height() - b, x + bounds.width() + b, y + b) canvas.drawRect(mRect, paintRect) canvas.drawText(mPlayerInfoDouble, x.toFloat(), y.toFloat(), mPaint!!) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val desiredWidth = if (widthSize < heightSize) widthSize else heightSize / 3 * 4 // aspect ratio 4:3 val width = when { (widthMode == MeasureSpec.EXACTLY) -> widthSize (widthMode == MeasureSpec.AT_MOST) -> min(desiredWidth, widthSize) else -> desiredWidth } //Measure Height val desiredHeight = if (widthSize < heightSize) heightSize else widthSize / 4 * 3 // aspect ratio 4:3 val height = when { (heightMode == MeasureSpec.EXACTLY) -> heightSize (heightMode == MeasureSpec.AT_MOST) -> min(desiredHeight, heightSize) else -> desiredHeight } //Log.i(TAG, "onMeasure(), width: " + width + ", height: " + height); //MUST CALL THIS setMeasuredDimension(width, height) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { if ((w > 0) and (h > 0)) { mBoardWidth = w mBoardHeight = h mBoardBorderWidth = w / 40 // 2,5% border var mDiceWidthWidth = (mBoardWidth - 2 * mBoardBorderWidth) / SIZE1_SMALL var mDiceWidthHeight = ((mBoardHeight - 2 * mBoardBorderWidth).toDouble() / SIZE2_SMALL).toInt() mDiceSizeSmall = min(mDiceWidthWidth, mDiceWidthHeight) mDiceWidthWidth = (mBoardWidth - 2 * mBoardBorderWidth) / SIZE1_MEDIUM mDiceWidthHeight = ((mBoardHeight - 2 * mBoardBorderWidth).toDouble() / SIZE2_MEDIUM).toInt() mDiceSizeMedium = min(mDiceWidthWidth, mDiceWidthHeight) mDiceWidthWidth = (mBoardWidth - 2 * mBoardBorderWidth) / SIZE1_LARGE mDiceWidthHeight = ((mBoardHeight - 2 * mBoardBorderWidth).toDouble() / SIZE2_LARGE).toInt() mDiceSizeLarge = min(mDiceWidthWidth, mDiceWidthHeight) when (diceSize) { 1 -> mDiceSize = mDiceSizeSmall 2 -> mDiceSize = mDiceSizeMedium 3 -> mDiceSize = mDiceSizeLarge } mHoldAreaWidth = 5 * mDiceSize mHoldAreaHeight = mDiceSize //Log.i(TAG, "onSizeChanged(), mBoar/dWidth: " + mBoardWidth + ", mBoardHeight: " + mBoardHeight + ", mDiceSize: " + mDiceSize); } } companion object { // const val TAG = "BoardView" const val SIZE1_SMALL = 8 const val SIZE1_MEDIUM = 7 const val SIZE1_LARGE = 6 const val SIZE2_SMALL = 5.5 const val SIZE2_MEDIUM = 4.5 const val SIZE2_LARGE = 3.5 } }
mit
725d1c7562278352c0b2ca817bedde91
40.165375
164
0.516477
4.027557
false
false
false
false
kamerok/Orny
app/src/test/java/com/kamer/orny/utils/TestUtils.kt
1
2235
package com.kamer.orny.utils import android.annotation.SuppressLint import android.arch.core.executor.AppToolkitTaskExecutor import android.arch.core.executor.TaskExecutor import android.arch.lifecycle.LiveData import android.arch.lifecycle.Observer import java.util.concurrent.CountDownLatch class TestUtils { companion object { @SuppressLint("RestrictedApi") fun setupLiveDataExecutor() { val executor = object : TaskExecutor() { override fun executeOnDiskIO(p0: Runnable?) { p0?.run() } override fun isMainThread(): Boolean = true override fun postToMainThread(p0: Runnable?) { p0?.run() } } AppToolkitTaskExecutor.getInstance().setDelegate(executor) } } } @Suppress("UNCHECKED_CAST") @Throws(InterruptedException::class) fun <T> LiveData<T>.getResultValue(): T { val data = arrayOfNulls<Any>(1) val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(o: T?) { data[0] = o latch.countDown() removeObserver(this) } } observeForever(observer) return data[0] as T } @Throws(InterruptedException::class) fun <T> LiveData<T>.getResultValues(count: Int, postElements: () -> Unit = {}): List<T> { val data = mutableListOf<T>() val latch = CountDownLatch(count) val observer = object : Observer<T> { override fun onChanged(o: T?) { if (o == null) throw Exception("Null value in LiveData") data.add(o) latch.countDown() if (latch.count == 0L) { removeObserver(this) } } } observeForever(observer) postElements.invoke() return data } @Throws(InterruptedException::class) fun <T> LiveData<T>.hasValue(): Boolean { var hasValue = false val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(o: T?) { hasValue = true latch.countDown() removeObserver(this) } } observeForever(observer) return hasValue }
apache-2.0
f8ce86256cbc346965c0c6e1aa3dd0d5
26.256098
89
0.597315
4.44334
false
false
false
false
hotpodata/redchain
mobile/src/main/java/com/hotpodata/redchain/ChainMaster.kt
1
7041
package com.hotpodata.redchain import android.content.Context import android.content.SharedPreferences import android.os.Bundle import com.hotpodata.redchain.data.Chain import org.joda.time.LocalDateTime import org.json.JSONArray import timber.log.Timber import java.util.* /** * Created by jdrotos on 11/7/15. */ object ChainMaster { /** * PREF DATA MAPS -> * chainids = list of chain ids * active_chain_id = id of the currently selected chain * <id> = each chain is stored under the key of its id */ val PREFS_CORE = "core" val PREF_ACTIVE_CHAIN_ID = "active_chain_id" val PREF_ALL_CHAINS = "chainids" val DEFAULT_CHAIN_ID = "DEFAULT_CHAIN_ID" var context: Context? = null var selectedChainId: String = DEFAULT_CHAIN_ID var allChains: MutableMap<String, Chain> = HashMap() fun init(ctx: Context) { context = ctx; readDataFromPrefs() ensureValidData() } @Suppress("DEPRECATION") private fun ensureValidData() { if (allChains.size <= 0) { //WE DONT HAVE ANY REAL DATA?? var chain = Chain(DEFAULT_CHAIN_ID, context!!.getString(R.string.app_name), context!!.resources.getColor(R.color.primary), ArrayList<LocalDateTime>()) saveChain(chain) setSelectedChain(chain.id) Timber.d("ensureValidData - Setting selected chain:" + chain.title + " id:" + chain.id) } if (!allChains.containsKey(selectedChainId)) { //WE DONT HAVE DATA FOR OUR SELECTED CHAIN... Timber.d("ensureValidData - selectedChainId not found"); var chain = allChains.get(allChains.keys.first()) if (chain != null) { Timber.d("ensureValidData - Setting selected chain:" + chain.title + " id:" + chain.id) setSelectedChain(chain.id) } else { Timber.e("ensureValidData - fail") } } } public fun expireExpiredChains() { for (chainid in allChains.keys) { var chain = allChains.get(chainid) if (chain != null && chain.chainExpired()) { chain.clearDates() saveChain(chain) } } } private fun readDataFromPrefs() { selectedChainId = readSelectedChainId() allChains.clear() var chainIds = readChainIds() for (chainId in chainIds) { var chain = readChain(chainId) if (chain != null) { allChains.put(chainId, chain) } } } public fun getSelectedChain(): Chain { ensureValidData() return allChains.get(selectedChainId)!! } public fun getLongestRunOfAllChains(): Int{ var longest = 0 for(chain in allChains.values){ if(chain.longestRun > longest){ longest = chain.longestRun } } return longest } public fun getChain(chainId: String): Chain? { return allChains.get(chainId); } public fun setSelectedChain(chainId: String): Boolean { if (allChains.contains(chainId)) { if (!chainId.equals(selectedChainId)) { selectedChainId = chainId writeSelectedChainId(chainId) } return true } return false } public fun deleteChain(chainId: String) { if (allChains.containsKey(chainId)) { allChains.remove(chainId) writeChainIds(allChains.keys) } eraseChain(chainId) ensureValidData() } public fun saveChain(chain: Chain) { var needsIdUpdate = !allChains.containsKey(chain.id) allChains.put(chain.id, chain) if (needsIdUpdate) { writeChainIds(allChains.keys) } writeChain(chain) //This still seems like a weird spot, but it should do the trick scheduleChainNotifications(chain) } private fun scheduleChainNotifications(chain: Chain){ if (chain.chainLength == 0) { NotificationMaster.dismissBrokenNotification(chain.id) NotificationMaster.dismissReminderNotification(chain.id) } if (chain.chainContainsToday()) { NotificationMaster.dismissReminderNotification(chain.id) NotificationMaster.scheduleReminderNotification(chain) NotificationMaster.dismissBrokenNotification(chain.id) NotificationMaster.scheduleBrokenNotification(chain) } } private fun readChain(id: String): Chain? { var sharedPref = getSharedPrefs() var chainStr = sharedPref.getString(id, ""); Timber.d("readChain:" + id + " dat:" + chainStr) var chain = Chain.Serializer.chainFromJson(chainStr) return chain } private fun writeChain(chain: Chain) { var sharedPref = getSharedPrefs() var editor = sharedPref.edit(); var chainStr = Chain.Serializer.chainToJson(chain).toString() Timber.d("writeChain" + chainStr) editor.putString(chain.id, chainStr); editor.commit(); } private fun eraseChain(id: String) { var sharedPref = getSharedPrefs() var editor = sharedPref.edit(); editor.remove(id) editor.commit(); } private fun readSelectedChainId(): String { var sharedPref = getSharedPrefs() var id = sharedPref.getString(PREF_ACTIVE_CHAIN_ID, DEFAULT_CHAIN_ID); Timber.d("readSelectedChainId:" + id) return id } private fun writeSelectedChainId(id: String) { var sharedPref = getSharedPrefs() var editor = sharedPref.edit(); Timber.d("writeSelectedChainId:" + id) editor.putString(PREF_ACTIVE_CHAIN_ID, id); editor.commit(); } private fun readChainIds(): List<String> { var sharedPref = getSharedPrefs() var chainStr = sharedPref.getString(PREF_ALL_CHAINS, null); if (chainStr == null) { Timber.d("readChainIds:emptylist") return ArrayList() } else { var jsonChainIds = JSONArray(chainStr) var chainIds = ArrayList<String>() for (i in 0..(jsonChainIds.length() - 1)) { chainIds.add(jsonChainIds.getString(i)) } Timber.d("readChainIds:" + chainIds) return chainIds } } private fun writeChainIds(chainIds: MutableSet<String>) { var sharedPref = getSharedPrefs() var chainIdsJsonArr = JSONArray() for (chainId in chainIds) { chainIdsJsonArr.put(chainId) } var editor = sharedPref.edit(); Timber.d("writeChainIds" + chainIdsJsonArr.toString()) editor.putString(PREF_ALL_CHAINS, chainIdsJsonArr.toString()); editor.commit(); } private fun getSharedPrefs(): SharedPreferences { return context!!.getSharedPreferences(PREFS_CORE, Context.MODE_PRIVATE); } }
apache-2.0
b461b9a7bccc8bd000fcd283c056814f
30.4375
162
0.601619
4.311696
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/MultimapStorageIndex.kt
2
3133
// 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.indices import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.impl.EntityId import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.BidirectionalLongMultiMap import com.intellij.workspaceModel.storage.impl.containers.putAll import org.jetbrains.annotations.TestOnly private typealias BidirectionalMap = BidirectionalLongMultiMap<SymbolicEntityId<*>> //private typealias BidirectionalMap = BidirectionalMultiMap<EntityId, PersistentEntityId<*>> open class MultimapStorageIndex private constructor( internal open val index: BidirectionalMap ) { constructor() : this(BidirectionalMap()) internal fun getIdsByEntry(entitySource: SymbolicEntityId<*>): Set<EntityId> = index.getKeys(entitySource) internal fun getEntriesById(id: EntityId): Set<SymbolicEntityId<*>> = index.getValues(id) internal fun entries(): Collection<SymbolicEntityId<*>> = index.values internal fun toMap(): Map<Long, Set<SymbolicEntityId<*>>> { return index.toMap() } class MutableMultimapStorageIndex private constructor( // Do not write to [index] directly! Create a method in this index and call [startWrite] before write. override var index: BidirectionalMap ) : MultimapStorageIndex(index), WorkspaceMutableIndex<SymbolicEntityId<*>> { private var freezed = true internal fun index(id: EntityId, elements: Set<SymbolicEntityId<*>>? = null) { startWrite() index.removeKey(id) if (elements == null) return elements.forEach { index.put(id, it) } } internal fun index(id: EntityId, element: SymbolicEntityId<*>) { startWrite() index.put(id, element) } internal fun remove(id: EntityId, element: SymbolicEntityId<*>) { startWrite() index.remove(id, element) } @TestOnly internal fun clear() { startWrite() index.clear() } @TestOnly internal fun copyFrom(another: MultimapStorageIndex) { startWrite() this.index.putAll(another.index) } private fun startWrite() { if (!freezed) return freezed = false index = copyIndex() } private fun copyIndex(): BidirectionalMap = index.copy() fun toImmutable(): MultimapStorageIndex { freezed = true return MultimapStorageIndex(index) } companion object { fun from(other: MultimapStorageIndex): MutableMultimapStorageIndex { if (other is MutableMultimapStorageIndex) other.freezed = true return MutableMultimapStorageIndex(other.index) } } override fun index(entity: WorkspaceEntityData<*>, data: SymbolicEntityId<*>) { val id = entity.createEntityId() this.index(id, data) } override fun remove(entity: WorkspaceEntityData<*>, data: SymbolicEntityId<*>) { val id = entity.createEntityId() this.remove(id, data) } } }
apache-2.0
4c0343a474a02bf4e11cc69b4f895c62
31.635417
140
0.717523
4.94164
false
false
false
false
moshbit/Kotlift
test-src/20_propertyGetterSetter.kt
2
1256
class FunkyClass { var internalString = "" var wrappedProperty: String get() { return "My string is $internalString" } set(value) { internalString = "$value - previous=\"$internalString\"" } } val computedProperty1: Int get() { var a = 0 a++ return a } val computedProperty2: Int get() { return 2 } /*val computedProperty3: Int get() = 3*/ var _backingProperty: Int = 0 var computedProperty4: Int get() { return 4 + _backingProperty } set(value) { _backingProperty = value } var computedProperty5: Int get() { return 5 + _backingProperty } set(value) { _backingProperty = value } /*var computedProperty6: Int get() = 6 + _backingProperty set(value) { _backingProperty = value }*/ fun main(args: Array<String>) { val x = FunkyClass() println(x.wrappedProperty) x.wrappedProperty = "abc" println(x.wrappedProperty) x.wrappedProperty = "123" println(x.wrappedProperty) println(computedProperty1) println(computedProperty2) //println(computedProperty3) println(computedProperty4) println(computedProperty5) //println(computedProperty6) computedProperty4 = 1000 println(computedProperty4) println(computedProperty5) //println(computedProperty6) }
apache-2.0
664be359b31c3af313dcc15553471928
19.258065
62
0.68551
3.588571
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/BreakpointChecker.kt
4
3003
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core.breakpoints import com.intellij.debugger.ui.breakpoints.JavaLineBreakpointType import com.intellij.openapi.application.ApplicationManager import com.intellij.xdebugger.breakpoints.XBreakpointType import com.intellij.xdebugger.breakpoints.XLineBreakpointType import org.jetbrains.debugger.SourceInfo import org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinBreakpointType import org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFieldBreakpointType import org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinLineBreakpointType import org.jetbrains.kotlin.psi.KtFile import java.util.* class BreakpointChecker { private companion object { private val BREAKPOINT_TYPES = mapOf( KotlinLineBreakpointType::class.java to BreakpointType.Line, KotlinFieldBreakpointType::class.java to BreakpointType.Field, KotlinFunctionBreakpointType::class.java to BreakpointType.Function, JavaLineBreakpointType.LambdaJavaBreakpointVariant::class.java to BreakpointType.Lambda, KotlinLineBreakpointType.LineKotlinBreakpointVariant::class.java to BreakpointType.Line, KotlinLineBreakpointType.KotlinBreakpointVariant::class.java to BreakpointType.All ) } enum class BreakpointType(val prefix: String) { Line("L"), Field("F"), Function("M"), // method Lambda("λ"), All("*") // line & lambda } private val breakpointTypes: List<XLineBreakpointType<*>> = run { val extensionPoint = ApplicationManager.getApplication().extensionArea .getExtensionPoint<XBreakpointType<*, *>>(XBreakpointType.EXTENSION_POINT_NAME.name) extensionPoint.extensions .filterIsInstance<XLineBreakpointType<*>>() .filter { it is KotlinBreakpointType } } fun check(file: KtFile, line: Int): EnumSet<BreakpointType> { val actualBreakpointTypes = EnumSet.noneOf(BreakpointType::class.java) for (breakpointType in breakpointTypes) { val sign = BREAKPOINT_TYPES[breakpointType.javaClass] ?: continue val isApplicable = breakpointType.canPutAt(file.virtualFile, line, file.project) if (breakpointType is KotlinLineBreakpointType) { if (isApplicable) { val variants = breakpointType.computeVariants(file.project, SourceInfo(file.virtualFile, line)) if (variants.isNotEmpty()) { actualBreakpointTypes += variants.mapNotNull { BREAKPOINT_TYPES[it.javaClass] } } else { actualBreakpointTypes += sign } } } else if (isApplicable) { actualBreakpointTypes += sign } } return actualBreakpointTypes } }
apache-2.0
229af1dcf7fc2039c1894e67d7b8d680
43.161765
120
0.690207
5.239092
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/Node.kt
1
1961
// 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.analysis.problemsView.toolWindow import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.PresentableNodeDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.ui.preview.DescriptorSupplier import com.intellij.ui.tree.LeafState import com.intellij.ui.tree.TreePathUtil.pathToCustomNode abstract class Node : PresentableNodeDescriptor<Node?>, DescriptorSupplier, LeafState.Supplier { protected constructor(project: Project) : super(project, null) protected constructor(parent: Node) : super(parent.project, parent) protected abstract fun update(project: Project, presentation: PresentationData) abstract override fun getName(): String override fun toString() = name open fun getChildren(): Collection<Node> = emptyList() open fun getVirtualFile(): VirtualFile? = null open fun getNavigatable(): Navigatable? = descriptor override fun getElement() = this override fun update(presentation: PresentationData) { if (myProject == null || myProject.isDisposed) return update(myProject, presentation) } fun getPath() = pathToCustomNode(this) { node: Node? -> node?.getParent(Node::class.java) }!! fun <T> getParent(type: Class<T>): T? { val parent = parentDescriptor ?: return null @Suppress("UNCHECKED_CAST") if (type.isInstance(parent)) return parent as T throw IllegalStateException("unexpected node " + parent.javaClass) } fun <T> findAncestor(type: Class<T>): T? { var parent = parentDescriptor while (parent != null) { @Suppress("UNCHECKED_CAST") if (type.isInstance(parent)) return parent as T parent = parent.parentDescriptor } return null } }
apache-2.0
af55cf83487ff89f4d499b4bfd241c00
35.314815
158
0.750637
4.377232
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/slicer/GroovySliceTestCase.kt
12
2649
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.slicer import com.intellij.analysis.AnalysisScope import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.slicer.LanguageSlicing import com.intellij.slicer.SliceAnalysisParams import com.intellij.slicer.SliceHandler import com.intellij.slicer.SliceTestUtil import com.intellij.testFramework.UsefulTestCase import org.jetbrains.plugins.groovy.util.TestUtils abstract class GroovySliceTestCase(private val isDataFlowToThis: Boolean) : DaemonAnalyzerTestCase() { override fun getTestProjectJdk() = null private val testDataDir: String get() = if (isDataFlowToThis) "backward" else "forward" override fun getTestDataPath() = TestUtils.getAbsoluteTestDataPath() + "slicer/$testDataDir/" protected fun doTest(getTestFiles: (baseName: String) -> List<String> = { listOf("$it.groovy") }) { val psiManager = PsiManager.getInstance(project) val psiDocumentManager = PsiDocumentManager.getInstance(project) val testFiles = getTestFiles(getTestName(false)) val rootDir = configureByFiles(null, *testFiles.toTypedArray()) val documents = testFiles.reversed().map { val virtualFile = rootDir.findFileByRelativePath(it)!! val psiFile = psiManager.findFile(virtualFile)!! psiDocumentManager.getDocument(psiFile) } val sliceUsageName2Offset = SliceTestUtil.extractSliceOffsetsFromDocuments(documents) psiDocumentManager.commitAllDocuments() val element = SliceHandler.create(isDataFlowToThis).getExpressionAtCaret(editor, file)!! val tree = SliceTestUtil.buildTree(element, sliceUsageName2Offset) val errors = highlightErrors() UsefulTestCase.assertEmpty(errors) val params = SliceAnalysisParams().apply { scope = AnalysisScope(project) dataFlowToThis = isDataFlowToThis } val usage = LanguageSlicing.getProvider(element)!!.createRootUsage(element, params) SliceTestUtil.checkUsages(usage, tree) } }
apache-2.0
4a8262c614094484f60d47f7c75667be
38.552239
102
0.773122
4.583045
false
true
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/plugins/PluginsUsagesCollector.kt
1
3264
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.collectors.fus.plugins import com.intellij.ide.plugins.* import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventId1 import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.AllowedDuringStartupCollector import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.extensions.PluginId class PluginsUsagesCollector : ApplicationUsagesCollector(), AllowedDuringStartupCollector { companion object { private val GROUP = EventLogGroup("plugins", 6) private val DISABLED_PLUGIN = GROUP.registerEvent("disabled.plugin", EventFields.PluginInfo) private val ENABLED_NOT_BUNDLED_PLUGIN = GROUP.registerEvent("enabled.not.bundled.plugin", EventFields.PluginInfo) private val PER_PROJECT_ENABLED = GROUP.registerEvent("per.project.enabled", EventFields.Count) private val PER_PROJECT_DISABLED = GROUP.registerEvent("per.project.disabled", EventFields.Count) private val UNSAFE_PLUGIN = GROUP.registerEvent("unsafe.plugin", EventFields.String("unsafe_id", emptyList()), EventFields.Boolean("enabled")) } override fun getGroup(): EventLogGroup = GROUP override fun getMetrics() = HashSet<MetricEvent>().apply { addAll(getDisabledPlugins()) addAll(getEnabledNonBundledPlugins()) addAll(getPerProjectPlugins(PER_PROJECT_ENABLED, ProjectPluginTracker::enabledPluginsIds)) addAll(getPerProjectPlugins(PER_PROJECT_DISABLED, ProjectPluginTracker::disabledPluginsIds)) addAll(getNotBundledPlugins()) } private fun getDisabledPlugins() = DisabledPluginsState .disabledPlugins() .map { DISABLED_PLUGIN.metric(getPluginInfoById(it)) }.toSet() private fun getEnabledNonBundledPlugins() = PluginManagerCore .getLoadedPlugins() .filter { it.isEnabled && !it.isBundled } .map { getPluginInfoByDescriptor(it) } .map(ENABLED_NOT_BUNDLED_PLUGIN::metric) .toSet() private fun getPerProjectPlugins( eventId: EventId1<Int>, countProducer: (ProjectPluginTracker) -> Set<PluginId> ): Set<MetricEvent> { return when (val pluginEnabler = PluginEnabler.getInstance()) { is DynamicPluginEnabler -> pluginEnabler.trackers.values .map { countProducer(it) } .filter { it.isNotEmpty() } .map { eventId.metric(it.size) } .toSet() else -> emptySet() } } private fun getNotBundledPlugins() = PluginManagerCore .getPlugins().asSequence() .filter { !it.isBundled && !getPluginInfoByDescriptor(it).isSafeToReport() } // This will be validated by list of plugin ids from server // and ONLY provided ids will be reported .map { UNSAFE_PLUGIN.metric(it.pluginId.idString, it.isEnabled) } .toSet() }
apache-2.0
75c5b67e7c68464576dceed144aca432
44.347222
129
0.745404
4.636364
false
false
false
false
smmribeiro/intellij-community
platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringState.kt
4
9357
// 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.refactoring.suggested import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature import com.intellij.util.keyFMap.KeyFMap import org.jetbrains.annotations.Nls private var nextFeatureUsageId = 0 /** * Data class representing state of accumulated signature changes. */ class SuggestedRefactoringState( val declaration: PsiElement, val refactoringSupport: SuggestedRefactoringSupport, val errorLevel: ErrorLevel, val oldDeclarationText: String, val oldImportsText: String?, val oldSignature: Signature, val newSignature: Signature, val parameterMarkers: List<ParameterMarker>, val disappearedParameters: Map<String, Any> = emptyMap() /* last known parameter name to its id */, val featureUsageId: Int = nextFeatureUsageId++, val additionalData: AdditionalData = AdditionalData.Empty ) { data class ParameterMarker(val rangeMarker: RangeMarker, val parameterId: Any) fun withDeclaration(declaration: PsiElement): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData ) copyRestoredDeclaration(state) return state } fun withErrorLevel(errorLevel: ErrorLevel): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData ) copyRestoredDeclaration(state) return state } fun withOldSignature(oldSignature: Signature): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData ) copyRestoredDeclaration(state) return state } fun withNewSignature(newSignature: Signature): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData ) copyRestoredDeclaration(state) return state } fun withParameterMarkers(parameterMarkers: List<ParameterMarker>): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData ) copyRestoredDeclaration(state) return state } fun withDisappearedParameters(disappearedParameters: Map<String, Any>): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData ) copyRestoredDeclaration(state) return state } fun <T : Any> withAdditionalData(key: Key<T>, value: T): SuggestedRefactoringState { val state = SuggestedRefactoringState( declaration, refactoringSupport, errorLevel, oldDeclarationText, oldImportsText, oldSignature, newSignature, parameterMarkers, disappearedParameters, featureUsageId, additionalData.withData(key, value) ) copyRestoredDeclaration(state) return state } private fun copyRestoredDeclaration(toState: SuggestedRefactoringState) { if (toState.declaration == this.declaration) { // do not reset lazy calculated declaration copy for performance reasons toState.restoredDeclarationCopy = this.restoredDeclarationCopy } } private var restoredDeclarationCopy: PsiElement? = null fun restoredDeclarationCopy(): PsiElement { require(errorLevel != ErrorLevel.INCONSISTENT) { "restoredDeclarationCopy() should not be invoked for inconsistent state" } if (restoredDeclarationCopy == null) { restoredDeclarationCopy = createRestoredDeclarationCopy() } return restoredDeclarationCopy!! } private fun createRestoredDeclarationCopy(): PsiElement { val psiFile = declaration.containingFile val signatureRange = refactoringSupport.signatureRange(declaration)!! val importsRange = refactoringSupport.importsRange(psiFile) if (importsRange != null) { require(importsRange.endOffset < signatureRange.startOffset) } val fileCopy = psiFile.copy() as PsiFile val document = fileCopy.viewProvider.document!! document.replaceString(signatureRange.startOffset, signatureRange.endOffset, oldDeclarationText) if (oldImportsText != null) { document.replaceString(importsRange!!.startOffset, importsRange.endOffset, oldImportsText) } PsiDocumentManager.getInstance(psiFile.project).commitDocument(document) var originalSignatureStart = signatureRange.startOffset if (oldImportsText != null) { originalSignatureStart -= importsRange!!.length originalSignatureStart += oldImportsText.length } return refactoringSupport.declarationByOffset(fileCopy, originalSignatureStart)!! } class AdditionalData private constructor(private val map: KeyFMap){ operator fun <T : Any> get(key: Key<T>): T? = map[key] fun <T : Any> withData(key: Key<T>, data: T): AdditionalData = AdditionalData(map.plus(key, data)) companion object { val Empty: AdditionalData = AdditionalData(KeyFMap.EMPTY_MAP) } } enum class ErrorLevel { /** No syntax errors and refactoring may be suggested (if it makes sense) */ NO_ERRORS, /** There is a syntax error in the signature or duplicated parameter names in the signature */ SYNTAX_ERROR, /** The state is inconsistent: declaration is invalid or signature range marker does not match signature range anymore */ INCONSISTENT } } /** * Data representing suggested refactoring that can be performed. */ sealed class SuggestedRefactoringData { abstract val declaration: PsiElement } /** * Data representing suggested Rename refactoring. */ class SuggestedRenameData(override val declaration: PsiNamedElement, val oldName: String) : SuggestedRefactoringData() /** * Data representing suggested Change Signature refactoring. */ @Suppress("DataClassPrivateConstructor") data class SuggestedChangeSignatureData private constructor( val declarationPointer: SmartPsiElementPointer<PsiElement>, val oldSignature: Signature, val newSignature: Signature, val nameOfStuffToUpdate: String, val oldDeclarationText: String, val oldImportsText: String? ) : SuggestedRefactoringData() { override val declaration: PsiElement get() = declarationPointer.element!! fun restoreInitialState(refactoringSupport: SuggestedRefactoringSupport): () -> Unit { val file = declaration.containingFile val psiDocumentManager = PsiDocumentManager.getInstance(file.project) val document = psiDocumentManager.getDocument(file)!! require(psiDocumentManager.isCommitted(document)) val signatureRange = refactoringSupport.signatureRange(declaration)!! val importsRange = refactoringSupport.importsRange(file) ?.extendWithWhitespace(document.charsSequence) val newSignatureText = document.getText(signatureRange) val newImportsText = importsRange ?.let { document.getText(it) } ?.takeIf { it != oldImportsText } document.replaceString(signatureRange.startOffset, signatureRange.endOffset, oldDeclarationText) if (newImportsText != null) { document.replaceString(importsRange.startOffset, importsRange.endOffset, oldImportsText!!) } psiDocumentManager.commitDocument(document) return { require(psiDocumentManager.isCommitted(document)) val newSignatureRange = refactoringSupport.signatureRange(declaration)!! document.replaceString(newSignatureRange.startOffset, newSignatureRange.endOffset, newSignatureText) if (newImportsText != null) { val newImportsRange = refactoringSupport.importsRange(file)!! .extendWithWhitespace(document.charsSequence) document.replaceString(newImportsRange.startOffset, newImportsRange.endOffset, newImportsText) } psiDocumentManager.commitDocument(document) } } companion object { /** * Creates an instance of [SuggestedChangeSignatureData]. * * @param nameOfStuffToUpdate term to be used in the UI to describe usages to be updated. */ @JvmStatic fun create(state: SuggestedRefactoringState, @Nls nameOfStuffToUpdate: String): SuggestedChangeSignatureData { return SuggestedChangeSignatureData( state.declaration.createSmartPointer(), state.oldSignature, state.newSignature, nameOfStuffToUpdate, state.oldDeclarationText, state.oldImportsText ) } } }
apache-2.0
9aa108b1ae269b297af526be51d0fa70
37.825726
140
0.764882
5.149697
false
false
false
false
WillowChat/Kale
src/main/kotlin/chat/willow/kale/core/RplSourceTargetContent.kt
2
1743
package chat.willow.kale.core import chat.willow.kale.core.message.* object RplSourceTargetContent { open class Message(val source: String, val target: String, val content: String) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Message) return false if (source != other.source) return false if (target != other.target) return false if (content != other.content) return false return true } override fun hashCode(): Int { var result = source.hashCode() result = 31 * result + target.hashCode() result = 31 * result + content.hashCode() return result } } abstract class Parser(val command: String) : MessageParser<Message>() { override fun parseFromComponents(components: IrcMessageComponents): Message? { if (components.parameters.size < 2) { return null } val source = components.prefix ?: "" val target = components.parameters[0] val content = components.parameters[1] return Message(source = source, target = target, content = content) } } abstract class Serialiser(val command: String) : MessageSerialiser<Message>(command) { override fun serialiseToComponents(message: Message): IrcMessageComponents { return IrcMessageComponents(prefix = message.source, parameters = listOf(message.target, message.content)) } } abstract class Descriptor(command: String, parser: IMessageParser<Message>) : KaleDescriptor<Message>(matcher = commandMatcher(command), parser = parser) }
isc
3547946204afbe6a6258957fd401bb82
32.538462
157
0.623064
4.994269
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/checkers/AbstractKotlinHighlightWolfPassTest.kt
1
5020
// 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.checkers import com.intellij.codeInsight.problems.MockWolfTheProblemSolver import com.intellij.codeInsight.daemon.impl.WolfTheProblemSolverImpl import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.problems.ProblemListener import com.intellij.problems.WolfTheProblemSolver import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import com.intellij.util.ThrowableRunnable import junit.framework.TestCase import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.codeInsight.AbstractOutOfBlockModificationTest import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils.checkForUnexpectedErrors import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.test.InTextDirectivesUtils abstract class AbstractKotlinHighlightWolfPassTest: KotlinLightCodeInsightFixtureTestCase() { private val disposable = Disposer.newDisposable("wolfTheProblemSolverParentDisposable") private var wolfTheProblemSolver: MockWolfTheProblemSolver? = null override fun setUp() { super.setUp() wolfTheProblemSolver = prepareWolf(project, disposable) } override fun tearDown() { runAll( ThrowableRunnable { wolfTheProblemSolver?.resetDelegate() }, ThrowableRunnable { Disposer.dispose(disposable) }, ThrowableRunnable { super.tearDown() }, ) } private fun prepareWolf(project: Project, parentDisposable: Disposable): MockWolfTheProblemSolver { val wolfTheProblemSolver = WolfTheProblemSolver.getInstance(project) as MockWolfTheProblemSolver val theRealSolver = WolfTheProblemSolverImpl.createInstance(project) wolfTheProblemSolver.setDelegate(theRealSolver) Disposer.register(parentDisposable, (theRealSolver as Disposable)) return wolfTheProblemSolver } open fun doTest(filePath: String) { myFixture.configureByFile(fileName()) val ktFile = file as KtFile myFixture.doHighlighting() // have to analyze file before any change to support incremental analysis val diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithAllCompilerChecks().bindingContext.diagnostics } checkForUnexpectedErrors(ktFile, diagnosticsProvider) val wolf = WolfTheProblemSolver.getInstance(project) val virtualFile = ktFile.virtualFile val initialWolfErrors = wolfErrors(myFixture) TestCase.assertEquals(initialWolfErrors, wolf.isProblemFile(virtualFile) || wolf.hasSyntaxErrors(virtualFile)) var problemsAppeared = 0 var problemsChanged = 0 var problemsDisappeared = 0 project.messageBus.connect(disposable).subscribe(ProblemListener.TOPIC, object : ProblemListener { override fun problemsAppeared(file: VirtualFile) { problemsAppeared++ } override fun problemsChanged(file: VirtualFile) { problemsChanged++ } override fun problemsDisappeared(file: VirtualFile) { problemsDisappeared++ } }) myFixture.type(AbstractOutOfBlockModificationTest.stringToType(myFixture)) PsiDocumentManager.getInstance(project).commitDocument(myFixture.getDocument(ktFile)) myFixture.doHighlighting() val hasWolfErrors = hasWolfErrors(myFixture) assertEquals(hasWolfErrors, wolf.isProblemFile(virtualFile) || wolf.hasSyntaxErrors(virtualFile)) if (hasWolfErrors && !initialWolfErrors) { TestCase.assertTrue(problemsAppeared > 0) } else { assertEquals(0, problemsAppeared) } assertEquals(0, problemsDisappeared) } companion object { private const val HAS_WOLF_ERRORS_DIRECTIVE = "HAS-WOLF-ERRORS:" fun hasWolfErrors(fixture: JavaCodeInsightTestFixture): Boolean = findBooleanDirective(fixture, HAS_WOLF_ERRORS_DIRECTIVE) private const val WOLF_ERRORS_DIRECTIVE = "WOLF-ERRORS:" fun wolfErrors(fixture: JavaCodeInsightTestFixture): Boolean = findBooleanDirective(fixture, WOLF_ERRORS_DIRECTIVE) private fun findBooleanDirective( fixture: JavaCodeInsightTestFixture, wolfErrorsDirective: String ): Boolean { val text = fixture.getDocument(fixture.file).text return InTextDirectivesUtils.findStringWithPrefixes(text, wolfErrorsDirective) == "true" } } }
apache-2.0
f154d5ef9c33e5c927a156ee4cfba6b7
43.830357
158
0.74243
5.112016
false
true
false
false
smmribeiro/intellij-community
platform/lang-impl/testSources/com/intellij/openapi/roots/ModuleDependencyInRootModelTest.kt
4
15969
// 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.roots import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.module.Module import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.rules.ProjectModelRule import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test class ModuleDependencyInRootModelTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @Rule @JvmField val projectModel = ProjectModelRule() lateinit var mainModule: Module @Before fun setUp() { mainModule = projectModel.createModule("main") } @Test fun `add edit remove module dependency`() { val depModule = projectModel.createModule("dep") run { val model = createModifiableModel(mainModule) val entry = model.addModuleOrderEntry(depModule) assertThat(dropModuleSourceEntry(model, 1).single() as ModuleOrderEntry).isEqualTo(entry) assertThat(entry.scope).isEqualTo(DependencyScope.COMPILE) assertThat(entry.isExported).isFalse() assertThat(entry.isSynthetic).isFalse() assertThat(entry.isValid).isTrue() assertThat(entry.moduleName).isEqualTo("dep") assertThat(entry.presentableName).isEqualTo("dep") assertThat(entry.module).isEqualTo(depModule) assertThat(model.findModuleOrderEntry(depModule)).isEqualTo(entry) val committed = commitModifiableRootModel(model) val committedEntry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(committedEntry.scope).isEqualTo(DependencyScope.COMPILE) assertThat(committedEntry.isExported).isFalse() assertThat(committedEntry.isSynthetic).isFalse() assertThat(committedEntry.isValid).isTrue() assertThat(committedEntry.moduleName).isEqualTo("dep") assertThat(committedEntry.presentableName).isEqualTo("dep") assertThat(committedEntry.module).isEqualTo(depModule) } run { val model = createModifiableModel(mainModule) val entry = dropModuleSourceEntry(model, 1).single() as ModuleOrderEntry entry.scope = DependencyScope.RUNTIME entry.isExported = true assertThat(model.findModuleOrderEntry(depModule)).isEqualTo(entry) val committed = commitModifiableRootModel(model) val committedEntry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(committedEntry.module).isEqualTo(depModule) assertThat(committedEntry.scope).isEqualTo(DependencyScope.RUNTIME) assertThat(committedEntry.isExported).isTrue() } run { val model = createModifiableModel(mainModule) val entry = model.findModuleOrderEntry(depModule)!! model.removeOrderEntry(entry) assertThat(model.orderEntries).hasSize(1) assertThat(model.findModuleOrderEntry(depModule)).isNull() val committed = commitModifiableRootModel(model) assertThat(committed.orderEntries).hasSize(1) } } @Test fun `add same module twice`() { val depModule = projectModel.createModule("dep") run { val model = createModifiableModel(mainModule) val entry1 = model.addModuleOrderEntry(depModule) val entry2 = model.addModuleOrderEntry(depModule) assertThat(entry1.module).isEqualTo(depModule) assertThat(entry2.module).isEqualTo(depModule) assertThat(model.findModuleOrderEntry(depModule)).isEqualTo(entry1) val committed = commitModifiableRootModel(model) val (committedEntry1, committedEntry2) = dropModuleSourceEntry(committed, 2) assertThat((committedEntry1 as ModuleOrderEntry).module).isEqualTo(depModule) assertThat((committedEntry2 as ModuleOrderEntry).module).isEqualTo(depModule) } run { val model = createModifiableModel(mainModule) (model.orderEntries[2] as ModuleOrderEntry).scope = DependencyScope.RUNTIME model.removeOrderEntry(model.orderEntries[1]) val committed = commitModifiableRootModel(model) val committedEntry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(committedEntry.scope).isEqualTo(DependencyScope.RUNTIME) assertThat(committedEntry.module).isEqualTo(depModule) } } @Test fun `add multiple dependencies at once`() { val dep1 = projectModel.createModule("dep1") val dep2 = projectModel.createModule("dep2") val model = createModifiableModel(mainModule) model.addModuleEntries(listOf(dep1, dep2), DependencyScope.RUNTIME, true) fun checkEntry(entry: ModuleOrderEntry) { assertThat(entry.isExported).isTrue assertThat(entry.scope).isEqualTo(DependencyScope.RUNTIME) } val (entry1, entry2) = dropModuleSourceEntry(model, 2) assertThat((entry1 as ModuleOrderEntry).module).isEqualTo(dep1) checkEntry(entry1) assertThat((entry2 as ModuleOrderEntry).module).isEqualTo(dep2) checkEntry(entry2) val (committedEntry1, committedEntry2) = dropModuleSourceEntry(commitModifiableRootModel(model), 2) assertThat((committedEntry1 as ModuleOrderEntry).module).isEqualTo(dep1) checkEntry(committedEntry1) assertThat((committedEntry2 as ModuleOrderEntry).module).isEqualTo(dep2) checkEntry(committedEntry2) } @Test fun `remove module dependency if there are several equal entries`() { val dep1Module = projectModel.createModule("dep1") val dep2Module = projectModel.createModule("dep2") run { val model = createModifiableModel(mainModule) model.addModuleOrderEntry(dep1Module) model.addModuleOrderEntry(dep2Module) model.addModuleOrderEntry(dep1Module) model.addModuleOrderEntry(dep2Module) model.addModuleOrderEntry(dep1Module) commitModifiableRootModel(model) } run { val model = createModifiableModel(mainModule) val orderEntries = model.orderEntries assertThat((orderEntries[1] as ModuleOrderEntry).module).isEqualTo(dep1Module) assertThat((orderEntries[5] as ModuleOrderEntry).module).isEqualTo(dep1Module) model.removeOrderEntry(orderEntries[1]) model.removeOrderEntry(orderEntries[5]) val committed = commitModifiableRootModel(model) val (entry1, entry2, entry3) = dropModuleSourceEntry(committed, 3) assertThat((entry1 as ModuleOrderEntry).module).isEqualTo(dep2Module) assertThat((entry2 as ModuleOrderEntry).module).isEqualTo(dep1Module) assertThat((entry3 as ModuleOrderEntry).module).isEqualTo(dep2Module) } } @Test fun `remove referenced module`() { val depModule = projectModel.createModule("dep") run { val model = createModifiableModel(mainModule) model.addModuleOrderEntry(depModule) commitModifiableRootModel(model) } projectModel.removeModule(depModule) run { val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isNull() assertThat(entry.moduleName).isEqualTo("dep") } val newModule = projectModel.createModule("dep") run { val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(newModule) } } @Test fun `add invalid module`() { run { val model = createModifiableModel(mainModule) val uncommittedEntry = model.addInvalidModuleEntry("foo") assertThat(uncommittedEntry.isValid).isFalse() assertThat(uncommittedEntry.isSynthetic).isFalse() assertThat(uncommittedEntry.presentableName).isEqualTo("foo") val committed = commitModifiableRootModel(model) val entry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(entry.module).isNull() assertThat(entry.isValid).isFalse() assertThat(entry.isSynthetic).isFalse() assertThat(entry.moduleName).isEqualTo("foo") assertThat(entry.presentableName).isEqualTo("foo") } val fooModule = projectModel.createModule("foo") run { val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(fooModule) } } @Test fun `change order`() { val a = projectModel.createModule("a") val b = projectModel.createModule("b") run { val model = createModifiableModel(mainModule) model.addModuleOrderEntry(a) model.addModuleOrderEntry(b) val oldOrder = model.orderEntries assertThat(oldOrder).hasSize(3) assertThat((oldOrder[1] as ModuleOrderEntry).moduleName).isEqualTo("a") assertThat((oldOrder[2] as ModuleOrderEntry).moduleName).isEqualTo("b") val newOrder = arrayOf(oldOrder[0], oldOrder[2], oldOrder[1]) model.rearrangeOrderEntries(newOrder) assertThat((model.orderEntries[1] as ModuleOrderEntry).moduleName).isEqualTo("b") assertThat((model.orderEntries[2] as ModuleOrderEntry).moduleName).isEqualTo("a") val committed = commitModifiableRootModel(model) assertThat((committed.orderEntries[1] as ModuleOrderEntry).moduleName).isEqualTo("b") assertThat((committed.orderEntries[2] as ModuleOrderEntry).moduleName).isEqualTo("a") } run { val model = createModifiableModel(mainModule) val oldOrder = model.orderEntries assertThat((oldOrder[1] as ModuleOrderEntry).moduleName).isEqualTo("b") assertThat((oldOrder[2] as ModuleOrderEntry).moduleName).isEqualTo("a") val newOrder = arrayOf(oldOrder[0], oldOrder[2], oldOrder[1]) model.rearrangeOrderEntries(newOrder) assertThat((model.orderEntries[1] as ModuleOrderEntry).moduleName).isEqualTo("a") assertThat((model.orderEntries[2] as ModuleOrderEntry).moduleName).isEqualTo("b") model.removeOrderEntry(model.orderEntries[1]) val committed = commitModifiableRootModel(model) val entry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(b) } } @Test fun `rename module`() { val a = projectModel.createModule("a") ModuleRootModificationUtil.addDependency(mainModule, a) projectModel.renameModule(a, "b") val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(a) assertThat(entry.moduleName).isEqualTo("b") } @Test fun `rename module and commit after committing root model`() { val a = projectModel.createModule("a") val model = createModifiableModel(mainModule) model.addModuleOrderEntry(a) val moduleModel = runReadAction { projectModel.moduleManager.modifiableModel } moduleModel.renameModule(a, "b") val entry = dropModuleSourceEntry(model, 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(a) assertThat(entry.moduleName).isEqualTo("a") val committed = commitModifiableRootModel(model) val committedEntry1 = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(committedEntry1.module).isEqualTo(a) assertThat(committedEntry1.moduleName).isEqualTo("a") runWriteActionAndWait { moduleModel.commit() } val committedEntry2 = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(committedEntry2.module).isEqualTo(a) assertThat(committedEntry2.moduleName).isEqualTo("b") } @Test fun `add invalid module and rename module to that name`() { val module = projectModel.createModule("foo") val model = createModifiableModel(mainModule) model.addInvalidModuleEntry("bar") commitModifiableRootModel(model) projectModel.renameModule(module, "bar") val moduleEntry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(moduleEntry.module).isEqualTo(module) } @Test fun `dispose model without committing`() { val a = projectModel.createModule("a") val model = createModifiableModel(mainModule) val entry = model.addModuleOrderEntry(a) assertThat(entry.module).isEqualTo(a) model.dispose() dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 0) } @Test fun `add not yet committed module`() { val moduleModel = runReadAction { projectModel.moduleManager.modifiableModel } val a = projectModel.createModule("a", moduleModel) run { val model = createModifiableModel(mainModule) val entry = model.addModuleOrderEntry(a) assertThat(entry.moduleName).isEqualTo("a") val committed = commitModifiableRootModel(model) val moduleEntry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(moduleEntry.moduleName).isEqualTo("a") } runWriteActionAndWait { moduleModel.commit() } run { val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(a) } } @Test fun `add not yet committed module and do not commit it`() { val moduleModel = runReadAction { projectModel.moduleManager.modifiableModel } val a = projectModel.createModule("a", moduleModel) run { val model = createModifiableModel(mainModule) val entry = model.addModuleOrderEntry(a) assertThat(entry.moduleName).isEqualTo("a") val committed = commitModifiableRootModel(model) val moduleEntry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(moduleEntry.moduleName).isEqualTo("a") } runWriteActionAndWait { moduleModel.dispose() } run { val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isNull() assertThat(entry.moduleName).isEqualTo("a") } } @Test fun `add not yet committed module with configuration accessor`() { val moduleModel = runReadAction { projectModel.moduleManager.modifiableModel } val a = projectModel.createModule("a", moduleModel) run { val model = createModifiableModel(mainModule, object : RootConfigurationAccessor() { override fun getModule(module: Module?, moduleName: String?): Module? { return if (moduleName == "a") a else module } }) val entry = model.addModuleOrderEntry(a) assertThat(entry.module).isEqualTo(a) val committed = commitModifiableRootModel(model) val moduleEntry = dropModuleSourceEntry(committed, 1).single() as ModuleOrderEntry assertThat(moduleEntry.moduleName).isEqualTo("a") } runWriteActionAndWait { moduleModel.commit() } run { val moduleEntry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(moduleEntry.module).isEqualTo(a) } } @Test fun `edit order entry located after removed entry`() { val foo = projectModel.createModule("foo") ModuleRootModificationUtil.addDependency(mainModule, foo) val bar = projectModel.createModule("bar") ModuleRootModificationUtil.addDependency(mainModule, bar) val model = createModifiableModel(mainModule) val fooEntry = model.findModuleOrderEntry(foo)!! val barEntry = model.findModuleOrderEntry(bar)!! model.removeOrderEntry(fooEntry) barEntry.scope = DependencyScope.TEST commitModifiableRootModel(model) val entry = dropModuleSourceEntry(ModuleRootManager.getInstance(mainModule), 1).single() as ModuleOrderEntry assertThat(entry.module).isEqualTo(bar) assertThat(entry.scope).isEqualTo(DependencyScope.TEST) } }
apache-2.0
4f6602687bd5d964cde5199886c38ee0
41.137203
140
0.73912
4.823014
false
true
false
false
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/apps/ClassBuilders.kt
1
7606
// GENERATE package com.fkorotkov.kubernetes.apps import io.fabric8.kubernetes.api.model.apps.ControllerRevision as apps_ControllerRevision import io.fabric8.kubernetes.api.model.apps.ControllerRevisionList as apps_ControllerRevisionList import io.fabric8.kubernetes.api.model.apps.DaemonSet as apps_DaemonSet import io.fabric8.kubernetes.api.model.apps.DaemonSetCondition as apps_DaemonSetCondition import io.fabric8.kubernetes.api.model.apps.DaemonSetList as apps_DaemonSetList import io.fabric8.kubernetes.api.model.apps.DaemonSetSpec as apps_DaemonSetSpec import io.fabric8.kubernetes.api.model.apps.DaemonSetStatus as apps_DaemonSetStatus import io.fabric8.kubernetes.api.model.apps.DaemonSetUpdateStrategy as apps_DaemonSetUpdateStrategy import io.fabric8.kubernetes.api.model.apps.Deployment as apps_Deployment import io.fabric8.kubernetes.api.model.apps.DeploymentCondition as apps_DeploymentCondition import io.fabric8.kubernetes.api.model.apps.DeploymentList as apps_DeploymentList import io.fabric8.kubernetes.api.model.apps.DeploymentSpec as apps_DeploymentSpec import io.fabric8.kubernetes.api.model.apps.DeploymentStatus as apps_DeploymentStatus import io.fabric8.kubernetes.api.model.apps.DeploymentStrategy as apps_DeploymentStrategy import io.fabric8.kubernetes.api.model.apps.ReplicaSet as apps_ReplicaSet import io.fabric8.kubernetes.api.model.apps.ReplicaSetCondition as apps_ReplicaSetCondition import io.fabric8.kubernetes.api.model.apps.ReplicaSetList as apps_ReplicaSetList import io.fabric8.kubernetes.api.model.apps.ReplicaSetSpec as apps_ReplicaSetSpec import io.fabric8.kubernetes.api.model.apps.ReplicaSetStatus as apps_ReplicaSetStatus import io.fabric8.kubernetes.api.model.apps.RollingUpdateDaemonSet as apps_RollingUpdateDaemonSet import io.fabric8.kubernetes.api.model.apps.RollingUpdateDeployment as apps_RollingUpdateDeployment import io.fabric8.kubernetes.api.model.apps.RollingUpdateStatefulSetStrategy as apps_RollingUpdateStatefulSetStrategy import io.fabric8.kubernetes.api.model.apps.StatefulSet as apps_StatefulSet import io.fabric8.kubernetes.api.model.apps.StatefulSetCondition as apps_StatefulSetCondition import io.fabric8.kubernetes.api.model.apps.StatefulSetList as apps_StatefulSetList import io.fabric8.kubernetes.api.model.apps.StatefulSetSpec as apps_StatefulSetSpec import io.fabric8.kubernetes.api.model.apps.StatefulSetStatus as apps_StatefulSetStatus import io.fabric8.kubernetes.api.model.apps.StatefulSetUpdateStrategy as apps_StatefulSetUpdateStrategy fun newControllerRevision(block : apps_ControllerRevision.() -> Unit = {}): apps_ControllerRevision { val instance = apps_ControllerRevision() instance.block() return instance } fun newControllerRevisionList(block : apps_ControllerRevisionList.() -> Unit = {}): apps_ControllerRevisionList { val instance = apps_ControllerRevisionList() instance.block() return instance } fun newDaemonSet(block : apps_DaemonSet.() -> Unit = {}): apps_DaemonSet { val instance = apps_DaemonSet() instance.block() return instance } fun newDaemonSetCondition(block : apps_DaemonSetCondition.() -> Unit = {}): apps_DaemonSetCondition { val instance = apps_DaemonSetCondition() instance.block() return instance } fun newDaemonSetList(block : apps_DaemonSetList.() -> Unit = {}): apps_DaemonSetList { val instance = apps_DaemonSetList() instance.block() return instance } fun newDaemonSetSpec(block : apps_DaemonSetSpec.() -> Unit = {}): apps_DaemonSetSpec { val instance = apps_DaemonSetSpec() instance.block() return instance } fun newDaemonSetStatus(block : apps_DaemonSetStatus.() -> Unit = {}): apps_DaemonSetStatus { val instance = apps_DaemonSetStatus() instance.block() return instance } fun newDaemonSetUpdateStrategy(block : apps_DaemonSetUpdateStrategy.() -> Unit = {}): apps_DaemonSetUpdateStrategy { val instance = apps_DaemonSetUpdateStrategy() instance.block() return instance } fun newDeployment(block : apps_Deployment.() -> Unit = {}): apps_Deployment { val instance = apps_Deployment() instance.block() return instance } fun newDeploymentCondition(block : apps_DeploymentCondition.() -> Unit = {}): apps_DeploymentCondition { val instance = apps_DeploymentCondition() instance.block() return instance } fun newDeploymentList(block : apps_DeploymentList.() -> Unit = {}): apps_DeploymentList { val instance = apps_DeploymentList() instance.block() return instance } fun newDeploymentSpec(block : apps_DeploymentSpec.() -> Unit = {}): apps_DeploymentSpec { val instance = apps_DeploymentSpec() instance.block() return instance } fun newDeploymentStatus(block : apps_DeploymentStatus.() -> Unit = {}): apps_DeploymentStatus { val instance = apps_DeploymentStatus() instance.block() return instance } fun newDeploymentStrategy(block : apps_DeploymentStrategy.() -> Unit = {}): apps_DeploymentStrategy { val instance = apps_DeploymentStrategy() instance.block() return instance } fun newReplicaSet(block : apps_ReplicaSet.() -> Unit = {}): apps_ReplicaSet { val instance = apps_ReplicaSet() instance.block() return instance } fun newReplicaSetCondition(block : apps_ReplicaSetCondition.() -> Unit = {}): apps_ReplicaSetCondition { val instance = apps_ReplicaSetCondition() instance.block() return instance } fun newReplicaSetList(block : apps_ReplicaSetList.() -> Unit = {}): apps_ReplicaSetList { val instance = apps_ReplicaSetList() instance.block() return instance } fun newReplicaSetSpec(block : apps_ReplicaSetSpec.() -> Unit = {}): apps_ReplicaSetSpec { val instance = apps_ReplicaSetSpec() instance.block() return instance } fun newReplicaSetStatus(block : apps_ReplicaSetStatus.() -> Unit = {}): apps_ReplicaSetStatus { val instance = apps_ReplicaSetStatus() instance.block() return instance } fun newRollingUpdateDaemonSet(block : apps_RollingUpdateDaemonSet.() -> Unit = {}): apps_RollingUpdateDaemonSet { val instance = apps_RollingUpdateDaemonSet() instance.block() return instance } fun newRollingUpdateDeployment(block : apps_RollingUpdateDeployment.() -> Unit = {}): apps_RollingUpdateDeployment { val instance = apps_RollingUpdateDeployment() instance.block() return instance } fun newRollingUpdateStatefulSetStrategy(block : apps_RollingUpdateStatefulSetStrategy.() -> Unit = {}): apps_RollingUpdateStatefulSetStrategy { val instance = apps_RollingUpdateStatefulSetStrategy() instance.block() return instance } fun newStatefulSet(block : apps_StatefulSet.() -> Unit = {}): apps_StatefulSet { val instance = apps_StatefulSet() instance.block() return instance } fun newStatefulSetCondition(block : apps_StatefulSetCondition.() -> Unit = {}): apps_StatefulSetCondition { val instance = apps_StatefulSetCondition() instance.block() return instance } fun newStatefulSetList(block : apps_StatefulSetList.() -> Unit = {}): apps_StatefulSetList { val instance = apps_StatefulSetList() instance.block() return instance } fun newStatefulSetSpec(block : apps_StatefulSetSpec.() -> Unit = {}): apps_StatefulSetSpec { val instance = apps_StatefulSetSpec() instance.block() return instance } fun newStatefulSetStatus(block : apps_StatefulSetStatus.() -> Unit = {}): apps_StatefulSetStatus { val instance = apps_StatefulSetStatus() instance.block() return instance } fun newStatefulSetUpdateStrategy(block : apps_StatefulSetUpdateStrategy.() -> Unit = {}): apps_StatefulSetUpdateStrategy { val instance = apps_StatefulSetUpdateStrategy() instance.block() return instance }
mit
296649cedff0571b570ab2688e077452
32.359649
143
0.777676
4.065206
false
true
false
false
timrijckaert/LottieSwipeRefreshLayout
lib/src/main/kotlin/be/rijckaert/tim/lib/SimplePullToRefreshLayout.kt
1
10486
package be.rijckaert.tim.lib import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams import android.view.animation.DecelerateInterpolator @SuppressLint("DrawAllocation") open class SimplePullToRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : ViewGroup(context, attrs, defStyle), RefreshView { var triggerOffSetTop = 0 private set var maxOffSetTop = 0 private set private var downX = 0F private var downY = 0F private var offsetY = 0F private var lastPullFraction = 0F private var currentState: State = State.IDLE private val onProgressListeners: MutableCollection<(Float) -> Unit> = mutableListOf() private val onTriggerListeners: MutableCollection<() -> Unit> = mutableListOf() companion object { private const val STICKY_FACTOR = 0.66F private const val STICKY_MULTIPLIER = 0.75F private const val ROLL_BACK_DURATION = 500L } init { context.theme.obtainStyledAttributes(attrs, R.styleable.SimplePullToRefreshLayout, defStyle, 0).let { val defaultValue = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, -1f, context.resources.displayMetrics).toInt() triggerOffSetTop = it.getDimensionPixelOffset(R.styleable.SimplePullToRefreshLayout_trigger_offset_top, defaultValue) maxOffSetTop = it.getDimensionPixelOffset(R.styleable.SimplePullToRefreshLayout_max_offset_top, defaultValue) it.recycle() } } private lateinit var topChildView: ChildView private lateinit var contentChildView: ChildView override fun onFinishInflate() { super.onFinishInflate() if (childCount != 2) { throw IllegalStateException("Only a topView and a contentView are allowed. Exactly 2 children are expected, but was $childCount") } (0 until childCount).map { val child = getChildAt(it) val layoutParams = child.layoutParams as LayoutParams when (layoutParams.type) { SimplePullToRefreshLayout.ViewType.UNKNOWN -> throw IllegalStateException("Could not parse layout type") SimplePullToRefreshLayout.ViewType.TOP_VIEW -> topChildView = ChildView(child) SimplePullToRefreshLayout.ViewType.CONTENT -> contentChildView = ChildView(child) } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) fun measureChild(childView: ChildView, widthMeasureSpec: Int, heightMeasureSpec: Int) { measureChildWithMargins(childView.view, widthMeasureSpec, 0, heightMeasureSpec, 0) } fun setInitialValues() { val topView = topChildView.view val layoutParams = topView.layoutParams as LayoutParams val topViewHeight = topView.measuredHeight + layoutParams.topMargin + layoutParams.bottomMargin topChildView = topChildView.copy(positionAttr = PositionAttr(height = topViewHeight)) triggerOffSetTop = if (triggerOffSetTop < 0) topViewHeight / 2 else triggerOffSetTop maxOffSetTop = if (maxOffSetTop < 0) topViewHeight else maxOffSetTop } measureChild(topChildView, widthMeasureSpec, heightMeasureSpec) measureChild(contentChildView, widthMeasureSpec, heightMeasureSpec) setInitialValues() } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { fun layoutTopView() { val topView = topChildView.view val topViewAttr = topChildView.positionAttr val lp = topView.layoutParams as LayoutParams val left: Int = paddingLeft + lp.leftMargin val top: Int = (paddingTop + lp.topMargin) - topViewAttr.height val right: Int = left + topView.measuredWidth val bottom = 0 topChildView = topChildView.copy(positionAttr = PositionAttr(left = left, top = top, right = right, bottom = bottom)) topView.layout(left, top, right, bottom) } fun layoutContentView() { val contentView = contentChildView.view val lp = contentView.layoutParams as LayoutParams val left: Int = paddingLeft + lp.leftMargin val top: Int = paddingTop + lp.topMargin val right: Int = left + contentView.measuredWidth val bottom: Int = top + contentView.measuredHeight contentChildView = contentChildView.copy(positionAttr = PositionAttr(left = left, top = top, right = right, bottom = bottom)) contentView.layout(left, top, right, bottom) } layoutTopView() layoutContentView() } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { fun checkIfScrolledFurther(ev: MotionEvent, dy: Float, dx: Float) = if (!contentChildView.view.canScrollVertically(-1)) { ev.y > downY && Math.abs(dy) > Math.abs(dx) } else { false } var shouldStealTouchEvents = false if (currentState != State.IDLE) { shouldStealTouchEvents = false } when (ev.action) { MotionEvent.ACTION_DOWN -> { downX = ev.x downY = ev.y } MotionEvent.ACTION_MOVE -> { val dx = ev.x - downX val dy = ev.y - downY shouldStealTouchEvents = checkIfScrolledFurther(ev, dy, dx) } } return shouldStealTouchEvents } override fun onTouchEvent(event: MotionEvent): Boolean { var handledTouchEvent = true if (currentState != State.IDLE) { handledTouchEvent = false } parent.requestDisallowInterceptTouchEvent(true) when (event.action) { MotionEvent.ACTION_MOVE -> { offsetY = (event.y - downY) * (1 - STICKY_FACTOR * STICKY_MULTIPLIER) move() } MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> { currentState = State.ROLLING stopRefreshing() } } return handledTouchEvent } private fun move() { val pullFraction: Float = if (offsetY == 0F) 0F else if (triggerOffSetTop > offsetY) offsetY / triggerOffSetTop else 1F offsetY = if (offsetY < 0) 0f else if (offsetY > maxOffSetTop) maxOffSetTop.toFloat() else offsetY onProgressListeners.forEach { it(pullFraction) } lastPullFraction = pullFraction topChildView.view.y = topChildView.positionAttr.top + offsetY contentChildView.view.y = contentChildView.positionAttr.top + offsetY } override fun stopRefreshing() { val rollBackOffset = if (offsetY > triggerOffSetTop) offsetY - triggerOffSetTop else offsetY val triggerOffset = if (rollBackOffset != offsetY) triggerOffSetTop else 0 ValueAnimator.ofFloat(1F, 0F).apply { duration = ROLL_BACK_DURATION interpolator = DecelerateInterpolator() addUpdateListener { topChildView.view.y = topChildView.positionAttr.top + triggerOffset + rollBackOffset * animatedValue as Float contentChildView.view.y = contentChildView.positionAttr.top + triggerOffset + rollBackOffset * animatedValue as Float } addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { if (triggerOffset != 0 && currentState == State.ROLLING) { currentState = State.TRIGGERING offsetY = triggerOffset.toFloat() onTriggerListeners.forEach { it() } } else { currentState = State.IDLE offsetY = 0f } } }) start() } } //<editor-fold desc="Helpers"> fun onProgressListener(onProgressListener: (Float) -> Unit) { onProgressListeners.add(onProgressListener) } fun onTriggerListener(onTriggerListener: () -> Unit) { onTriggerListeners.add(onTriggerListener) } fun removeOnTriggerListener(onTriggerListener: () -> Unit) { onTriggerListeners.remove(onTriggerListener) } override fun checkLayoutParams(p: ViewGroup.LayoutParams?) = null != p && p is LayoutParams override fun generateDefaultLayoutParams() = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) override fun generateLayoutParams(attrs: AttributeSet?) = LayoutParams(context, attrs) override fun generateLayoutParams(p: ViewGroup.LayoutParams?) = LayoutParams(p) class LayoutParams : ViewGroup.MarginLayoutParams { var type: ViewType = ViewType.UNKNOWN constructor(c: Context, attrs: AttributeSet?) : super(c, attrs) { c.theme.obtainStyledAttributes(attrs, R.styleable.EasyPullLayout_LayoutParams, 0, 0).let { type = ViewType.fromValue(it.getInt(R.styleable.EasyPullLayout_LayoutParams_layout_type, ViewType.UNKNOWN.value)) it.recycle() } } constructor(width: Int, height: Int) : super(width, height) constructor(source: MarginLayoutParams) : super(source) constructor(source: ViewGroup.LayoutParams) : super(source) } enum class ViewType(val value: Int) { UNKNOWN(-1), TOP_VIEW(0), CONTENT(1); companion object { fun fromValue(value: Int) = values().first { it.value == value } } } enum class State { IDLE, ROLLING, TRIGGERING } data class ChildView(val view: View, val positionAttr: PositionAttr = PositionAttr()) data class PositionAttr(val left: Int = 0, val top: Int = 0, val right: Int = 0, val bottom: Int = 0, val height: Int = 0) //</editor-fold> }
mit
be1a3f9c48daf6dbde544b90c3547814
37.551471
141
0.640759
4.916081
false
false
false
false
quran/quran_android
common/data/src/main/java/com/quran/data/core/QuranConstants.kt
2
252
package com.quran.data.core object QuranConstants { const val NUMBER_OF_SURAS = 114 const val PAGES_FIRST = 1 const val FIRST_SURA = 1 const val LAST_SURA = 114 const val MIN_AYAH = 1 const val MAX_AYAH = 286 const val JUZ2_COUNT = 30 }
gpl-3.0
99e90c0af313af7195e9fbf85ee032db
21.909091
33
0.698413
3.230769
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/event/EventUtils.kt
1
9214
package org.fossasia.openevent.general.event import android.content.Context import android.content.Intent import android.view.LayoutInflater import androidx.appcompat.app.AlertDialog import androidx.preference.PreferenceManager import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.dialog_login_to_like.view.getStartedButton import kotlinx.android.synthetic.main.dialog_login_to_like.view.eventImage import kotlinx.android.synthetic.main.dialog_login_to_like.view.eventName import org.fossasia.openevent.general.OpenEventGeneral import org.fossasia.openevent.general.R import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.settings.LOCAL_TIMEZONE import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime import org.threeten.bp.format.DateTimeFormatter import timber.log.Timber import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone object EventUtils { fun loadMapUrl(event: Event) = "geo:<${event.latitude}>,<${event.longitude}>" + "?q=<${event.latitude}>,<${event.longitude}>" fun getEventDateTime(dateString: String, timeZone: String?): ZonedDateTime { try { return when (PreferenceManager.getDefaultSharedPreferences(OpenEventGeneral.appContext) .getBoolean(LOCAL_TIMEZONE, false) && !timeZone.isNullOrBlank()) { true -> ZonedDateTime.parse(dateString) .toOffsetDateTime() .atZoneSameInstant(ZoneId.systemDefault()) false -> ZonedDateTime.parse(dateString) .toOffsetDateTime() .atZoneSameInstant(ZoneId.of(timeZone)) } } catch (e: NullPointerException) { return ZonedDateTime.parse(dateString) .toOffsetDateTime() .atZoneSameInstant(ZoneId.systemDefault()) } } fun getTimeInMilliSeconds(dateString: String, timeZone: String?): Long { return getEventDateTime(dateString, timeZone).toInstant().toEpochMilli() } fun getFormattedDate(date: ZonedDateTime): String { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("EEEE, MMM d, y") return try { dateFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting Date") "" } } fun getSimpleFormattedDate(date: Date): String { val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) return try { dateFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting Date") "" } } fun getFormattedDateShort(date: ZonedDateTime): String { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE, MMM d") return try { dateFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting Date") "" } } fun getFormattedDateWithoutYear(date: ZonedDateTime): String { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("EEEE, MMM d") return try { dateFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting Date") "" } } fun getFormattedTime(date: ZonedDateTime): String { val timeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a") return try { timeFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting time") "" } } fun getFormattedTimeZone(date: ZonedDateTime): String { val timeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("z") return try { timeFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting time") "" } } fun getFormattedEventDateTimeRange(startsAt: ZonedDateTime, endsAt: ZonedDateTime): String { val startingDate = getFormattedDate(startsAt) val endingDate = getFormattedDate(endsAt) return try { if (startingDate != endingDate) "${getFormattedDateShort(startsAt)}, ${getFormattedTime(startsAt)}" else "${getFormattedDateWithoutYear(startsAt)}" } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting time") "" } } fun getFormattedEventDateTimeRangeSecond(startsAt: ZonedDateTime, endsAt: ZonedDateTime): String { val startingDate = getFormattedDate(startsAt) val endingDate = getFormattedDate(endsAt) return try { if (startingDate != endingDate) "- ${getFormattedDateShort(endsAt)}, ${getFormattedTime(endsAt)} ${getFormattedTimeZone(endsAt)}" else "${getFormattedTime(startsAt)} - ${getFormattedTime(endsAt)} ${getFormattedTimeZone(endsAt)}" } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting time") "" } } fun getFormattedDateTimeRangeDetailed(startsAt: ZonedDateTime, endsAt: ZonedDateTime): String { val startingDate = getFormattedDate(startsAt) val endingDate = getFormattedDate(endsAt) return try { if (startingDate != endingDate) "$startingDate at ${getFormattedTime(startsAt)} - $endingDate" + " at ${getFormattedTime(endsAt)} (${getFormattedTimeZone(endsAt)})" else "$startingDate from ${getFormattedTime(startsAt)}" + " to ${getFormattedTime(endsAt)} (${getFormattedTimeZone(endsAt)})" } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting time") "" } } fun getFormattedDateTimeRangeBulleted(startsAt: ZonedDateTime, endsAt: ZonedDateTime): String { val startingDate = getFormattedDateShort(startsAt) val endingDate = getFormattedDateShort(endsAt) return try { if (startingDate != endingDate) "$startingDate - $endingDate • ${getFormattedTime(startsAt)} ${getFormattedTimeZone(startsAt)}" else "$startingDate • ${getFormattedTime(startsAt)} ${getFormattedTimeZone(startsAt)}" } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting time") "" } } fun getFormattedDateWithoutWeekday(date: ZonedDateTime): String { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("MMM d, y") return try { dateFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting Date") "" } } fun getFormattedWeekDay(date: ZonedDateTime): String { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE") return try { dateFormat.format(date) } catch (e: IllegalArgumentException) { Timber.e(e, "Error formatting Date") "" } } fun getDayDifferenceFromToday(date: String): Long { return (System.currentTimeMillis() - getTimeInMilliSeconds(date, null)) / (1000 * 60 * 60 * 24) } /** * share event detail along with event image * if image loading is successful then imageView tag will be set to String * So if imageView tag is not null then share image else only event details * */ fun share(event: Event, context: Context) { val sendIntent = Intent() val resources = Resource() sendIntent.action = Intent.ACTION_SEND sendIntent.type = "text/plain" sendIntent.putExtra(Intent.EXTRA_SUBJECT, event.name) sendIntent.putExtra(Intent.EXTRA_TEXT, "https://${resources.getString(R.string.FRONTEND_HOST)}/e/${event.identifier}") context.startActivity(Intent.createChooser(sendIntent, "Share Event Details")) } fun getTimeInISO8601(date: Date): String { val tz = TimeZone.getTimeZone(TimeZone.getDefault().id) val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.getDefault()) df.timeZone = tz return df.format(date) } fun showLoginToLikeDialog( context: Context, inflater: LayoutInflater, redirectToLogin: RedirectToLogin, eventImage: String?, eventName: String ) { val view = inflater.inflate(R.layout.dialog_login_to_like, null, false) val dialog = AlertDialog.Builder(context) .setView(view).create() view.getStartedButton.setOnClickListener { redirectToLogin.goBackToLogin() dialog.cancel() } view.eventName.text = "Sign in to like $eventName" Picasso.get() .load(eventImage) .placeholder(R.drawable.header) .into(view.eventImage) dialog.show() } } interface RedirectToLogin { fun goBackToLogin() }
apache-2.0
25e8ab66729c16c40eb7be6059160afd
36.439024
113
0.632139
4.922501
false
false
false
false
timakden/advent-of-code
src/main/kotlin/ru/timakden/aoc/util/PowerSet.kt
1
2364
package ru.timakden.aoc.util /** * Creates the set of all possible subsets of this set. For example, `PowerSet(setOf(1, 2))` * returns the set `{{}, {1}, {2}, {1, 2}}`. * * https://www.baeldung.com/java-power-set-of-a-set */ class PowerSet<E>(private val set: Set<E>) : AbstractSet<Set<E>>() { private val map: MutableMap<E, Int> = mutableMapOf() private val reverseMap: MutableList<E> = mutableListOf() init { initializeMap() } private abstract class ListIterator<K>(private val size: Int) : Iterator<K> { protected var position = 0 override fun hasNext() = position < size } private class Subset<E>( private val map: Map<E, Int>, private val reverseMap: List<E>, private val mask: Int ) : AbstractSet<E>() { override fun iterator(): Iterator<E> { return object : Iterator<E> { var remainingSetBits = mask override fun hasNext() = remainingSetBits != 0 override fun next(): E { val index = Integer.numberOfTrailingZeros(remainingSetBits) if (index == 32) throw NoSuchElementException() remainingSetBits = remainingSetBits and (1 shl index).inv() return reverseMap[index] } } } override val size: Int get() = Integer.bitCount(mask) override fun contains(element: E): Boolean { val index = map[element] return index != null && mask and (1 shl index) != 0 } } override fun iterator(): Iterator<Set<E>> { return object : ListIterator<Set<E>>(size) { override fun next() = Subset(map, reverseMap, position++) } } override val size: Int get() = 1 shl set.size override fun contains(element: Set<E>): Boolean { return reverseMap.containsAll(element) } override fun equals(other: Any?): Boolean { if (other is PowerSet<*>) { return set == other.set // Set equals check to have the same element regardless of the order of the items } return super.equals(other) } private fun initializeMap() { for ((mapId, c) in set.withIndex()) { map[c] = mapId reverseMap.add(c) } } }
apache-2.0
7dcdefa845cc60939b15f2de6941a4b1
29.701299
117
0.561337
4.337615
false
false
false
false
SourceUtils/hl2-hud-editor
src/main/kotlin/com/timepath/hl2/hudeditor/HUDEditor.kt
1
16165
package com.timepath.hl2.hudeditor import com.timepath.Utils import com.timepath.hl2.io.VMT import com.timepath.hl2.io.image.VTF import com.timepath.plaf.IconList import com.timepath.plaf.x.filechooser.BaseFileChooser import com.timepath.plaf.x.filechooser.NativeFileChooser import com.timepath.steam.io.VDF import com.timepath.steam.io.VDFNode import com.timepath.steam.io.storage.ACF import com.timepath.steam.io.storage.VPK import com.timepath.vfs.provider.ExtendedVFile import com.timepath.vfs.provider.local.LocalFileProvider import com.timepath.vgui.Element import com.timepath.vgui.VGUIRenderer import com.timepath.vgui.VGUIRenderer.ResourceLocator import com.timepath.vgui.swing.VGUICanvas import java.awt.* import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.io.File import java.io.IOException import java.io.InputStream import java.text.MessageFormat import java.util.LinkedList import java.util.concurrent.ExecutionException import java.util.logging.Level import java.util.logging.Logger import java.util.regex.Pattern import javax.swing.* import javax.swing.event.HyperlinkListener import javax.swing.event.TreeSelectionEvent import javax.swing.event.TreeSelectionListener import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.TreePath public class HUDEditor : Application() { var editorMenuBar: EditorMenuBar var canvas: VGUICanvas? = null var lastLoaded: File? = null set(root) { editorMenuBar.reloadItem.setEnabled(root != null) if ((root == null) || !root.exists()) return lastLoaded = root Main.prefs.put("lastLoaded", root.getPath()) } var spinnerWidth: JSpinner? = null var spinnerHeight: JSpinner? = null var linkListener: HyperlinkListener? = Utils.getLinkListener() init { setIconImages(IconList("/com/timepath/hl2/hudeditor/res/Icon", "png", *intArrayOf(16, 22, 24, 32, 40, 48, 64, 128, 512, 1024)).getIcons()) setTitle(Main.getString("Title")) editorMenuBar = EditorMenuBar(this) setJMenuBar(editorMenuBar) val str = Main.prefs.get("lastLoaded", null) str?.let { lastLoaded = File(str) } object : SwingWorker<Image, Void>() { override fun doInBackground(): Image? { return BackgroundLoader.fetch() } override fun done() { try { canvas!!.setBackgroundImage(get()) } catch (e: InterruptedException) { LOG.log(Level.SEVERE, null, e) } catch (e: ExecutionException) { LOG.log(Level.SEVERE, null, e) } } }.execute() mount(440) val gc = getGraphicsConfiguration() val screenBounds = gc.getBounds() val screenInsets = getToolkit().getScreenInsets(gc) val workspace = Dimension(screenBounds.width - screenInsets.left - screenInsets.right, screenBounds.height - screenInsets.top - screenInsets.bottom) setMinimumSize(Dimension(Math.max(workspace.width / 2, 640), Math.max((3 * workspace.height) / 4, 480))) setPreferredSize(Dimension((workspace.getWidth() / 1.5).toInt(), (workspace.getHeight() / 1.5).toInt())) pack() setLocationRelativeTo(null) } init { fileTree.addTreeSelectionListener(object : TreeSelectionListener { override fun valueChanged(e: TreeSelectionEvent) { val node = fileTree.getLastSelectedPathComponent() ?: return propTable.clear() // val model = propTable.getModel() val nodeInfo = node.getUserObject() // TODO: introspection if (nodeInfo is VDFNode) { val element = Element.importVdf(nodeInfo) element.file = (node.getParent().toString()) // TODO loadProps(element) canvas!!.r.load(element) } } }) canvas = VGUICanvas() // canvas = object : VGUICanvas() { // override fun placed() { // val node = fileTree.getLastSelectedPathComponent() // if (node == null) return // val nodeInfo = node.getUserObject() // if (nodeInfo is Element) { // val element = nodeInfo as Element // loadProps(element) // } // } // } tabbedContent.add(Main.getString("Canvas"), object : JScrollPane(canvas) { init { // setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); getVerticalScrollBar().setBlockIncrement(30) getVerticalScrollBar().setUnitIncrement(20) // setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); getHorizontalScrollBar().setBlockIncrement(30) getHorizontalScrollBar().setUnitIncrement(20) } }) } override fun preferences() { info("No app-specific preferences yet", "Preferences") } override fun about() { val pane = JEditorPane("text/html", "") pane.setEditable(false) pane.setOpaque(false) pane.setBackground(Color(0, 0, 0, 0)) pane.addHyperlinkListener(linkListener) var aboutText = "<html><h2>This is to be a What You See Is What You Get HUD Editor for TF2,</h2>" aboutText += "for graphically editing TF2 HUDs!" val p1 = aboutText pane.setText(p1) info(pane, "About") } override fun fileDropped(f: File) { loadAsync(f) } override val dockIconImage: Image get() { val url = javaClass.getResource("/com/timepath/hl2/hudeditor/res/Icon.png") return Toolkit.getDefaultToolkit().getImage(url) } fun locateHudDirectory() { try { val selection = NativeFileChooser().setParent(this).setTitle(Main.getString("LoadHudDir")).setDirectory(lastLoaded).setFileMode(BaseFileChooser.FileMode.DIRECTORIES_ONLY).choose() selection?.let { loadAsync(it[0]) } } catch (ex: IOException) { LOG.log(Level.SEVERE, null, ex) } } fun loadAsync(f: File) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)) val start = System.currentTimeMillis() object : SwingWorker<DefaultMutableTreeNode, Void>() { override fun doInBackground(): DefaultMutableTreeNode? { return load(f) } override fun done() { try { val project = get() setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)) if (project == null) return LOG.log(Level.INFO, "Loaded hud - took {0}ms", System.currentTimeMillis() - start) fileSystemRoot.add(project) fileTree.expandPath(TreePath(project.getPath())) fileTree.setSelectionRow(fileSystemRoot.getIndex(project)) fileTree.requestFocusInWindow() } catch (t: Throwable) { LOG.log(Level.SEVERE, null, t) } } }.execute() } fun load(root: File?): DefaultMutableTreeNode? { if (root == null) return null if (!root.exists()) { error(MessageFormat(Main.getString("FileAccessError")).format(arrayOf(root))) } lastLoaded = root LOG.log(Level.INFO, "You have selected: {0}", root.getAbsolutePath()) if (root.isDirectory()) { var valid = true // TODO: find resource and scripts if there is a parent directory for (folder in root.listFiles() ?: arrayOfNulls<File>(0)) { if (folder!!.isDirectory() && ("resource".equals(folder.getName(), ignoreCase = true) || "scripts".equals(folder.getName(), ignoreCase = true))) { valid = true break } } if (!valid) { error("Selection not valid. Please choose a folder containing \'resources\' or \'scripts\'.") locateHudDirectory() return null } val project = DefaultMutableTreeNode(root.getName()) recurseDirectoryToNode(LocalFileProvider(root), project) return project } if (root.getName().endsWith("_dir.vpk")) { val project = DefaultMutableTreeNode(root.getName()) recurseDirectoryToNode(VPK.loadArchive(root)!!, project) return project } return null } fun changeResolution() { spinnerWidth?.setEnabled(false) spinnerHeight?.setEnabled(false) val dropDown = JComboBox<String>() val env = GraphicsEnvironment.getLocalGraphicsEnvironment() val listItems = LinkedList<String>() for (device in env.getScreenDevices()) { for (resolution in device.getDisplayModes()) { // TF2 has different resolutions val item = "${resolution.getWidth().toString()}x${resolution.getHeight()}" // TODO: Work out aspect ratios if (item !in listItems) { listItems.add(item) } } } dropDown.addItem("Custom") for (listItem in listItems) { dropDown.addItem(listItem) } dropDown.setSelectedIndex(1) dropDown.addActionListener(object : ActionListener { override fun actionPerformed(e: ActionEvent) { val item = dropDown.getSelectedItem().toString() val isRes = "x" in item spinnerWidth?.setEnabled(!isRes) spinnerHeight?.setEnabled(!isRes) if (isRes) { val xy = item.splitBy("x") spinnerWidth?.setValue(Integer.parseInt(xy[0])) spinnerHeight?.setValue(Integer.parseInt(xy[1])) } } }) val message = arrayOf("Presets: ", dropDown, "Width: ", spinnerWidth!!, "Height: ", spinnerHeight!!) val optionPane = JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null) val dialog = optionPane.createDialog(this, "Change resolution...") dialog.setContentPane(optionPane) dialog.pack() dialog.setVisible(true) optionPane.getValue()?.let { if (it == JOptionPane.YES_OPTION) { canvas!!.setPreferredSize(Dimension( Integer.parseInt(spinnerWidth?.getValue().toString()), Integer.parseInt(spinnerHeight?.getValue().toString()) )) } } } fun mount(appID: Int) { object : SwingWorker<DefaultMutableTreeNode, Void>() { override fun doInBackground(): DefaultMutableTreeNode? { LOG.log(Level.INFO, "Mounting {0}", appID) val a = ACF.fromManifest(appID) VGUIRenderer.registerLocator(object : ResourceLocator() { override fun locate(path: String): InputStream? { @suppress("NAME_SHADOWING") val path = path.replace('\\', '/').toLowerCase().let { when { it.startsWith("..") -> "vgui/$it" else -> it } } println("Looking for $path") val file = a.query("tf/materials/$path") ?: return null return file.openStream() } override fun locateImage(path: String): Image? { var vtfName = path if (!path.endsWith(".vtf")) { // It could be a vmt vtfName += ".vtf" locate("$path.vmt")?.let { try { val vmt = VMT.load(it) val next = vmt.root.getValue("\$baseTexture") as String if (next != path) return locateImage(next) // Stop recursion } catch (e: IOException) { LOG.log(Level.SEVERE, null, e) } } } // It's a vtf locate(vtfName)?.let { try { val vtf = VTF.load(it) ?: return null return vtf.getImage(0) } catch (e: IOException) { LOG.log(Level.SEVERE, null, e) } } return null } }) val child = DefaultMutableTreeNode(a) recurseDirectoryToNode(a, child) return child } override fun done() { try { get()?.let { archiveRoot.add(it) fileModel.reload(archiveRoot) LOG.log(Level.INFO, "Mounted {0}", appID) } } catch (ex: InterruptedException) { LOG.log(Level.SEVERE, null, ex) } catch (ex: ExecutionException) { LOG.log(Level.SEVERE, null, ex) } } }.execute() } fun loadProps(element: Element) { propTable.clear() val model = propTable.getModel() if (!element.props.isEmpty()) { element.validateDisplay() for (entry in element.props) { if ("\\n" == entry.getKey()) continue model.addRow(arrayOf(entry.getKey(), entry.getValue(), entry.info)) } model.fireTableDataChanged() propTable.repaint() } } companion object { private val LOG = Logger.getLogger(javaClass<HUDEditor>().getName()) private val VDF_PATTERN = Pattern.compile("^\\.(vdf|pop|layout|menu|styles)") public fun recurseDirectoryToNode(ar: ExtendedVFile, project: DefaultMutableTreeNode) { project.setUserObject(ar) analyze(project, true) } public fun analyze(top: DefaultMutableTreeNode, leaves: Boolean) { if (top.getUserObject() !is ExtendedVFile) return val root = top.getUserObject() as ExtendedVFile for (n in root.list()) { LOG.log(Level.FINE, "Loading {0}", n.name) val child = DefaultMutableTreeNode(n) if (n.isDirectory) { if (n.list().size() > 0) { top.add(child) analyze(child, leaves) } } else if (leaves) { try { n.openStream()!!.use { when { VDF_PATTERN.matcher(n.name).matches() -> VDF.load(it).toTreeNode() // TODO // n.name.endsWith(".res") -> RES.load(it).toTreeNode() else -> null } }?.let { child.add(it) top.add(child) } } catch (e: IOException) { LOG.log(Level.SEVERE, null, e) } } } } } }
artistic-2.0
1faee59342bb48f83df9363fab45e39e
39.820707
191
0.525271
4.958589
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/chatrooms/presentation/ChatRoomsPresenter.kt
2
7333
package chat.rocket.android.chatrooms.presentation import chat.rocket.android.R import chat.rocket.android.chatrooms.adapter.model.RoomUiModel import chat.rocket.android.chatrooms.domain.FetchChatRoomsInteractor import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.db.DatabaseManager import chat.rocket.android.db.model.ChatRoomEntity import chat.rocket.android.helper.UserHelper import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.main.presentation.MainNavigator import chat.rocket.android.server.domain.SettingsRepository import chat.rocket.android.server.domain.SortingAndGroupingInteractor import chat.rocket.android.server.domain.siteName import chat.rocket.android.server.domain.useRealName import chat.rocket.android.server.domain.useSpecialCharsOnRoom import chat.rocket.android.server.infrastructure.ConnectionManager import chat.rocket.android.util.extension.launchUI import chat.rocket.android.util.retryDB import chat.rocket.android.util.retryIO import chat.rocket.common.RocketChatException import chat.rocket.common.model.RoomType import chat.rocket.common.model.User import chat.rocket.common.model.roomTypeOf import chat.rocket.core.internal.rest.createDirectMessage import chat.rocket.core.internal.rest.me import chat.rocket.core.internal.rest.show import kotlinx.coroutines.withTimeout import timber.log.Timber import javax.inject.Inject import javax.inject.Named class ChatRoomsPresenter @Inject constructor( private val view: ChatRoomsView, private val strategy: CancelStrategy, private val navigator: MainNavigator, @Named("currentServer") private val currentServer: String?, private val sortingAndGroupingInteractor: SortingAndGroupingInteractor, private val dbManager: DatabaseManager, manager: ConnectionManager, private val localRepository: LocalRepository, private val userHelper: UserHelper, settingsRepository: SettingsRepository ) { private val client = manager.client private val settings = currentServer?.let { settingsRepository.get(it) } fun toCreateChannel() = navigator.toCreateChannel() fun toSettings() = navigator.toSettings() fun toDirectory() = navigator.toDirectory() fun getCurrentServerName() = currentServer?.let { view.setupToolbar(settings?.siteName() ?: it) } fun getSortingAndGroupingPreferences() { with(sortingAndGroupingInteractor) { currentServer?.let { view.setupSortingAndGrouping( getSortByName(it), getUnreadOnTop(it), getGroupByType(it), getGroupByFavorites(it) ) } } } fun loadChatRoom(roomId: String) { launchUI(strategy) { try { val room = dbManager.getRoom(roomId) if (room != null) { loadChatRoom(room.chatRoom, true) } else { Timber.e("Error loading channel") view.showGenericErrorMessage() } } catch (ex: Exception) { Timber.e(ex, "Error loading channel") view.showGenericErrorMessage() } } } fun loadChatRoom(chatRoom: RoomUiModel) { launchUI(strategy) { try { val room = retryDB("getRoom(${chatRoom.id}") { dbManager.getRoom(chatRoom.id) } if (room != null) { loadChatRoom(room.chatRoom, true) } else { with(chatRoom) { val entity = ChatRoomEntity( id = id, subscriptionId = "", parentId = null, type = type.toString(), name = username ?: name.toString(), fullname = name.toString(), open = open, muted = muted ) loadChatRoom(entity, false) } } } catch (ex: Exception) { Timber.e(ex, "Error loading channel") view.showGenericErrorMessage() } } } suspend fun loadChatRoom(chatRoom: ChatRoomEntity, local: Boolean = false) { with(chatRoom) { val isDirectMessage = roomTypeOf(type) is RoomType.DirectMessage val roomName = if ((settings?.useSpecialCharsOnRoom() == true) || (isDirectMessage && settings?.useRealName() == true)) { fullname ?: name } else { name } val myself = getCurrentUser() if (myself?.username == null) { view.showMessage(R.string.msg_generic_error) } else { val id = if (isDirectMessage && open == false) { // If from local database, we already have the roomId, no need to concatenate if (local) { retryIO { client.show(id, roomTypeOf(RoomType.DIRECT_MESSAGE)) } id } else { retryIO("createDirectMessage($name)") { withTimeout(10000) { try { client.createDirectMessage(name) } catch (ex: Exception) { Timber.e(ex) } } } val fromTo = mutableListOf(myself.id, id).apply { sort() } fromTo.joinToString("") } } else { id } FetchChatRoomsInteractor(client, dbManager).refreshChatRooms() navigator.toChatRoom( chatRoomId = id, chatRoomName = roomName, chatRoomType = type, isReadOnly = readonly ?: false, chatRoomLastSeen = lastSeen ?: -1, isSubscribed = open, isCreator = ownerId == myself.id || isDirectMessage, isFavorite = favorite ?: false ) } } } private suspend fun getCurrentUser(): User? { userHelper.user()?.let { return it } try { val myself = retryIO { client.me() } val user = User( id = myself.id, username = myself.username, name = myself.name, status = myself.status, utcOffset = myself.utcOffset, emails = null, roles = myself.roles ) currentServer?.let { localRepository.saveCurrentUser(url = it, user = user) } } catch (ex: RocketChatException) { Timber.e(ex) } return null } }
mit
351a4dab93291045623fa686a04a6c24
36.418367
97
0.538115
5.317621
false
false
false
false
dsvoronin/RxKotlin
src/main/kotlin/rx/lang/kotlin/observables.kt
1
5271
package rx.lang.kotlin import rx.Observable import rx.Subscriber import rx.Subscription import rx.observables.BlockingObservable public fun <T> emptyObservable(): Observable<T> = Observable.empty() public fun <T> observable(body: (s: Subscriber<in T>) -> Unit): Observable<T> = Observable.create(body) /** * Create deferred observable * @see [rx.Observable.defer] and [http://reactivex.io/documentation/operators/defer.html] */ public fun <T> deferredObservable(body: () -> Observable<T>): Observable<T> = Observable.defer(body) private fun <T> Iterator<T>.toIterable() = object : Iterable<T> { override fun iterator(): Iterator<T> = this@toIterable } public fun BooleanArray.toObservable(): Observable<Boolean> = this.toList().toObservable() public fun ByteArray.toObservable(): Observable<Byte> = this.toList().toObservable() public fun ShortArray.toObservable(): Observable<Short> = this.toList().toObservable() public fun IntArray.toObservable(): Observable<Int> = this.toList().toObservable() public fun LongArray.toObservable(): Observable<Long> = this.toList().toObservable() public fun FloatArray.toObservable(): Observable<Float> = this.toList().toObservable() public fun DoubleArray.toObservable(): Observable<Double> = this.toList().toObservable() public fun <T> Array<out T>.toObservable(): Observable<T> = Observable.from(this) public fun Progression<Int>.toObservable(): Observable<Int> = if (increment == 1 && end.toLong() - start < Integer.MAX_VALUE) Observable.range(start, Math.max(0, end - start + 1)) else Observable.from(this) public fun <T> Iterator<T>.toObservable(): Observable<T> = toIterable().toObservable() public fun <T> Iterable<T>.toObservable(): Observable<T> = Observable.from(this) public fun <T> Sequence<T>.toObservable(): Observable<T> = Observable.from(object : Iterable<T> { override fun iterator(): Iterator<T> = [email protected]() }) public fun <T> T.toSingletonObservable(): Observable<T> = Observable.just(this) public fun <T> Throwable.toObservable(): Observable<T> = Observable.error(this) public fun <T> Iterable<Observable<out T>>.merge(): Observable<T> = Observable.merge(this.toObservable()) public fun <T> Iterable<Observable<out T>>.mergeDelayError(): Observable<T> = Observable.mergeDelayError(this.toObservable()) public fun <T, R> Observable<T>.fold(initial: R, body: (R, T) -> R): Observable<R> = reduce(initial, { a, e -> body(a, e) }) public fun <T> Observable<T>.onError(block: (Throwable) -> Unit): Observable<T> = doOnError(block) @Suppress("BASE_WITH_NULLABLE_UPPER_BOUND") public fun <T> Observable<T>.firstOrNull(): Observable<T?> = firstOrDefault(null) public fun <T> BlockingObservable<T>.firstOrNull(): T = firstOrDefault(null) @Suppress("BASE_WITH_NULLABLE_UPPER_BOUND") public fun <T> Observable<T>.onErrorReturnNull(): Observable<T?> = onErrorReturn<T> { null } public fun <T, R> Observable<T>.lift(operator: (Subscriber<in R>) -> Subscriber<T>): Observable<R> = lift(object : Observable.Operator<R, T> { override fun call(t1: Subscriber<in R>?): Subscriber<in T> = operator(t1!!) }) /** * Returns [Observable] that requires all objects to be non null. Raising [NullPointerException] in case of null object */ public fun <T : Any> Observable<T?>.requireNoNulls(): Observable<T> = lift { s -> subscriber<T?>(). onCompleted { s.onCompleted() }. onError { t -> s.onError(t) }. onNext { v -> if (v == null) throw NullPointerException("null element found in rx observable") else s.onNext(v) } } /** * Returns [Observable] with non-null generic type T. Returned observable filter out null values */ public fun <T : Any> Observable<T?>.filterNotNull(): Observable<T> = lift { s -> subscriber<T?>(). onCompleted { s.onCompleted() }. onError { t -> s.onError(t) }. onNext { v -> if (v != null) s.onNext(v) } } /** * Returns Observable that wrap all values into [IndexedValue] and populates corresponding index value. * Works similar to [kotlin.withIndex] */ public fun <T> Observable<T>.withIndex(): Observable<IndexedValue<T>> = lift { s -> var index = 0 subscriber<T>(). onNext { v -> s.onNext(IndexedValue(index++, v)) }. onCompleted { s.onCompleted() }. onError { t -> s.onError(t) } } /** * Returns Observable that emits objects from kotlin [Sequence] returned by function you provided by parameter [body] for * each input object and merges all produced elements into one observable. * Works similar to [Observable.flatMap] and [Observable.flatMapIterable] but with [Sequence] * * @param body is a function that applied for each item emitted by source observable that returns [Sequence] * @returns Observable that merges all [Sequence]s produced by [body] functions */ public fun <T, R> Observable<T>.flatMapSequence(body: (T) -> Sequence<R>): Observable<R> = flatMap { body(it).toObservable() } /** * Subscribe with a subscriber that is configured inside body */ public inline fun <T> Observable<T>.subscribeWith(body: FunctionSubscriberModifier<T>.() -> Unit): Subscription { val modifier = FunctionSubscriberModifier(subscriber<T>()) modifier.body() return subscribe(modifier.subscriber) }
apache-2.0
f3eec8cd0e606b2abbb50a298cfd9072
46.918182
142
0.70461
3.867205
false
false
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/texture/AnimatedTexture.kt
1
5991
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.texture import com.almasb.fxgl.animation.AnimatedValue import com.almasb.fxgl.animation.Animation import com.almasb.fxgl.animation.AnimationBuilder import com.almasb.fxgl.animation.Interpolators import com.almasb.fxgl.core.util.EmptyRunnable import javafx.animation.Interpolator import javafx.util.Duration import kotlin.math.min /** * Represents an animated texture. * Animation channels, like WALK, RUN, IDLE, ATTACK, etc. can be set dynamically to alter the animation. * * @author Almas Baimagambetov ([email protected]) */ class AnimatedTexture(defaultChannel: AnimationChannel) : Texture(defaultChannel.image) { private var currentFrame = 0 private lateinit var animation: Animation<Int> var animationChannel: AnimationChannel = defaultChannel private set(value) { field = value updateAnimation() } var onCycleFinished: Runnable = EmptyRunnable var interpolator: Interpolator = Interpolators.LINEAR.EASE_OUT() set(value) { field = value animation.interpolator = interpolator } init { // force channel to apply settings to this texture updateImage() updateAnimation() } /** * Plays given animation [channel] from start to end once. * The animation will stop at the last frame. */ fun playAnimationChannel(channel: AnimationChannel) { animationChannel = channel animation.stop() animation.cycleCount = 1 animation.start() } /** * Loops given [channel]. * * Note: if the given channel is already playing or looping, then noop. */ fun loopNoOverride(channel: AnimationChannel) { if (animationChannel === channel) return loopAnimationChannel(channel) } /** * Loops given [channel]. * * Note: any channel that is already playing or looping will be overridden. */ fun loopAnimationChannel(channel: AnimationChannel) { animationChannel = channel animation.stop() animation.cycleCount = Int.MAX_VALUE animation.start() } /** * Play the last animation channel (or default) from end to start once. * The animation will stop at the first frame. */ fun playReverse(): AnimatedTexture { animation.stop() animation.cycleCount = 1 animation.startReverse() return this } /** * Loops the last animation channel (or default) from end to start. */ fun loopReverse(): AnimatedTexture { animation.stop() animation.cycleCount = Int.MAX_VALUE animation.startReverse() return this } /** * Play the last animation channel (or default) from start to end once. * The animation will stop at the last frame. */ fun play(): AnimatedTexture { playAnimationChannel(animationChannel) return this } /** * Loops the last animation channel (or default). */ fun loop(): AnimatedTexture { loopAnimationChannel(animationChannel) return this } /** * Stop the animation. * The frame will be set to 0th (i.e. the first frame). */ fun stop() { animation.stop() currentFrame = 0 updateImage() } // play and loop // play would stop at last frame // loop would set the 0th frame override fun onUpdate(tpf: Double) { animation.onUpdate(tpf) } private fun updateImage() { val frameData = animationChannel.getFrameData(currentFrame) image = animationChannel.image fitWidth = frameData.width.toDouble() fitHeight = frameData.height.toDouble() viewport = frameData.viewport layoutX = frameData.offsetX.toDouble() layoutY = frameData.offsetY.toDouble() } private fun updateAnimation() { animation = AnimationBuilder() .onCycleFinished { if (animation.cycleCount > 1) { currentFrame = 0 updateImage() } onCycleFinished.run() } .duration(Duration.seconds(animationChannel.frameDuration * animationChannel.sequence.size)) .interpolator(interpolator) .animate(PreciseAnimatedIntValue(0, animationChannel.sequence.size - 1)) .onProgress { frameNum -> currentFrame = min(frameNum, animationChannel.sequence.size - 1) updateImage() } .build() } } /** * This animated value provides higher accuracy for mapping progress to an int value. * * For example, the default AnimatedValue results for [0,3] (non-uniform!): 0.00: 0 0.05: 0 0.10: 0 0.15: 0 0.20: 1 0.25: 1 0.30: 1 0.35: 1 0.40: 1 0.45: 1 0.50: 2 0.55: 2 0.60: 2 0.65: 2 0.70: 2 0.75: 2 0.80: 2 0.85: 3 0.90: 3 0.95: 3 1.00: 3 */ private class PreciseAnimatedIntValue(start: Int, end: Int) : AnimatedValue<Int>(start, end) { private val mapping = linkedMapOf<ClosedFloatingPointRange<Double>, Int>() init { val numSegments = end - start + 1 val progressPerSegment = 1.0 / numSegments var progress = 0.0 for (i in start..end) { val progressEnd = if (i == end) 1.0 else (progress + progressPerSegment) mapping[progress..progressEnd] = i progress += progressPerSegment } } override fun animate(val1: Int, val2: Int, progress: Double, interpolator: Interpolator): Int { val p = interpolator.interpolate(0.0, 1.0, progress) return mapping.filterKeys { p in it } .values .lastOrNull() ?: val1 } }
mit
0a57a367414d724e2c09b9af54495c1b
24.389831
108
0.612252
4.369803
false
false
false
false
AlmasB/FXGL
fxgl-entity/src/test/kotlin/com/almasb/fxgl/pathfinding/CellMoveComponentTest.kt
1
7060
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ @file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE") package com.almasb.fxgl.pathfinding import com.almasb.fxgl.core.collection.grid.Cell import com.almasb.fxgl.entity.Entity import javafx.geometry.Point2D import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * * @author Almas Baimagambetov ([email protected]) */ class CellMoveComponentTest { private lateinit var e: Entity private lateinit var cellMove: CellMoveComponent @BeforeEach fun setUp() { e = Entity() cellMove = CellMoveComponent(40, 40, 40 * 1.0) e.addComponent(cellMove) } @Test fun `Local anchor affects the positioning of entity inside the cell`() { e.localAnchor = Point2D(20.0, 20.0) cellMove.setPositionToCell(1, 1) assertThat(e.x, `is`(40.0)) assertThat(e.y, `is`(40.0)) e.x += 25.0 assertThat(cellMove.cellX, `is`(2)) assertThat(cellMove.cellY, `is`(1)) } @Test fun `isAtDestination is only true when component has reached destination`() { val finishCell = object : Cell(0,0) {} assertTrue(cellMove.isAtDestination) assertThat(cellMove.cellX, `is`(0)) assertThat(cellMove.cellY, `is`(0)) assertThat(e.x, `is`(0.0)) assertThat(e.y, `is`(0.0)) cellMove.setPositionToCell(0, 0) assertTrue(cellMove.isAtDestination) assertFalse(cellMove.isMoving) assertThat(e.x, `is`(20.0)) assertThat(e.y, `is`(20.0)) // move right cellMove.moveToCell(2, 0) assertFalse(cellMove.isAtDestination) assertTrue(cellMove.isMoving) repeat(62) { cellMove.onUpdate(0.016) } assertThat(e.x, `is`(not(20.0))) assertThat(e.y, `is`(20.0)) assertTrue(cellMove.isMovingRight) assertThat(e.rotation, `is`(0.0)) repeat(65) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(2)) assertThat(cellMove.cellY, `is`(0)) assertTrue(cellMove.isAtDestination) assertFalse(cellMove.isMoving) assertFalse(cellMove.isMovingRight) assertThat(e.rotation, `is`(0.0)) // move down cellMove.moveToCell(2, 2) repeat(62) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(2)) assertThat(cellMove.cellY, `is`(1)) assertFalse(cellMove.isAtDestination) assertTrue(cellMove.isMovingDown) assertThat(e.rotation, `is`(0.0)) repeat(65) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(2)) assertThat(cellMove.cellY, `is`(2)) assertTrue(cellMove.isAtDestination) assertFalse(cellMove.isMoving) assertFalse(cellMove.isMovingDown) assertThat(e.rotation, `is`(0.0)) // move left cellMove.moveToCell(0, 2) repeat(62) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(1)) assertThat(cellMove.cellY, `is`(2)) assertFalse(cellMove.isAtDestination) assertTrue(cellMove.isMovingLeft) assertThat(e.rotation, `is`(0.0)) repeat(65) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(0)) assertThat(cellMove.cellY, `is`(2)) assertTrue(cellMove.isAtDestination) assertFalse(cellMove.isMoving) assertFalse(cellMove.isMovingLeft) assertThat(e.rotation, `is`(0.0)) // move up cellMove.moveToCell(finishCell) repeat(62) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(0)) assertThat(cellMove.cellY, `is`(1)) assertFalse(cellMove.isAtDestination) assertTrue(cellMove.isMovingUp) assertThat(e.rotation, `is`(0.0)) repeat(65) { cellMove.onUpdate(0.016) } assertThat(cellMove.cellX, `is`(0)) assertThat(cellMove.cellY, `is`(0)) assertTrue(cellMove.isAtDestination) assertFalse(cellMove.isMoving) assertFalse(cellMove.isMovingUp) assertThat(e.rotation, `is`(0.0)) } @Test fun `Component rotates while moving if its allowed`(){ val firstCell = object : Cell(0,0) {} val secondCell = object : Cell(1,0) {} val thirdCell = object : Cell(1,1) {} val fourthCell = object : Cell(0,1) {} cellMove.allowRotation(true) cellMove.setPositionToCell(firstCell) assertThat(e.rotation, `is`(0.0)) // Move right cellMove.moveToCell(secondCell) repeat(30) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(0.0)) repeat(35) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(0.0)) assertFalse(cellMove.isMoving) assertTrue(cellMove.atDestinationProperty().value) // Move down cellMove.moveToCell(thirdCell) repeat(30) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(90.0)) repeat(35) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(90.0)) assertFalse(cellMove.isMoving) assertTrue(cellMove.atDestinationProperty().value) // Move down cellMove.moveToCell(fourthCell) repeat(30) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(180.0)) repeat(35) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(180.0)) assertFalse(cellMove.isMoving) assertTrue(cellMove.atDestinationProperty().value) // Move up cellMove.moveToCell(firstCell) repeat(30) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(270.0)) repeat(35) { cellMove.onUpdate(0.016) } assertThat(e.rotation, `is`(270.0)) assertFalse(cellMove.isMoving) assertTrue(cellMove.atDestinationProperty().value) } @Test fun `CellMovementComponent width, height and speed are changeable after component creation`() { assertThat(cellMove.cellHeight, `is`(40)) assertThat(cellMove.cellWidth, `is`(40)) assertThat(cellMove.speed, `is`(40.0)) cellMove.cellHeight = 20 cellMove.cellWidth = 20 cellMove.speed = 20.0 assertThat(cellMove.cellHeight, `is`(20)) assertThat(cellMove.cellWidth, `is`(20)) assertThat(cellMove.speed, `is`(20.0)) } }
mit
caf3d6f3faaa2d761c0432d8a7bf1d44
24.128114
99
0.597875
3.70215
false
false
false
false
googlecodelabs/android-compose-codelabs
TestingCodelab/app/src/main/java/com/example/compose/rally/ui/components/DetailsScreen.kt
1
2948
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.compose.rally.ui.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp /** * Generic component used by the accounts and bills screens to show a chart and a list of items. */ @Composable fun <T> StatementBody( items: List<T>, colors: (T) -> Color, amounts: (T) -> Float, amountsTotal: Float, circleLabel: String, rows: @Composable (T) -> Unit ) { Column(modifier = Modifier.verticalScroll(rememberScrollState())) { Box(Modifier.padding(16.dp)) { val accountsProportion = items.extractProportions { amounts(it) } val circleColors = items.map { colors(it) } AnimatedCircle( accountsProportion, circleColors, Modifier .height(300.dp) .align(Alignment.Center) .fillMaxWidth() ) Column(modifier = Modifier.align(Alignment.Center)) { Text( text = circleLabel, style = MaterialTheme.typography.body1, modifier = Modifier.align(Alignment.CenterHorizontally) ) Text( text = formatAmount(amountsTotal), style = MaterialTheme.typography.h2, modifier = Modifier.align(Alignment.CenterHorizontally) ) } } Spacer(Modifier.height(10.dp)) Card { Column(modifier = Modifier.padding(12.dp)) { items.forEach { item -> rows(item) } } } } }
apache-2.0
95013d89827c32bf516b6386a1793e8f
34.95122
96
0.648575
4.679365
false
false
false
false
coil-kt/coil
coil-base/src/main/java/coil/request/DefaultRequestOptions.kt
1
4802
package coil.request import android.graphics.Bitmap import android.graphics.drawable.Drawable import coil.ImageLoader import coil.size.Precision import coil.transition.Transition import coil.util.DEFAULT_BITMAP_CONFIG import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers /** * A set of default options that are used to fill in unset [ImageRequest] values. * * @see ImageLoader.defaults * @see ImageRequest.defaults */ class DefaultRequestOptions( val interceptorDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate, val fetcherDispatcher: CoroutineDispatcher = Dispatchers.IO, val decoderDispatcher: CoroutineDispatcher = Dispatchers.IO, val transformationDispatcher: CoroutineDispatcher = Dispatchers.IO, val transitionFactory: Transition.Factory = Transition.Factory.NONE, val precision: Precision = Precision.AUTOMATIC, val bitmapConfig: Bitmap.Config = DEFAULT_BITMAP_CONFIG, val allowHardware: Boolean = true, val allowRgb565: Boolean = false, val placeholder: Drawable? = null, val error: Drawable? = null, val fallback: Drawable? = null, val memoryCachePolicy: CachePolicy = CachePolicy.ENABLED, val diskCachePolicy: CachePolicy = CachePolicy.ENABLED, val networkCachePolicy: CachePolicy = CachePolicy.ENABLED, ) { fun copy( interceptorDispatcher: CoroutineDispatcher = this.interceptorDispatcher, fetcherDispatcher: CoroutineDispatcher = this.fetcherDispatcher, decoderDispatcher: CoroutineDispatcher = this.decoderDispatcher, transformationDispatcher: CoroutineDispatcher = this.transformationDispatcher, transitionFactory: Transition.Factory = this.transitionFactory, precision: Precision = this.precision, bitmapConfig: Bitmap.Config = this.bitmapConfig, allowHardware: Boolean = this.allowHardware, allowRgb565: Boolean = this.allowRgb565, placeholder: Drawable? = this.placeholder, error: Drawable? = this.error, fallback: Drawable? = this.fallback, memoryCachePolicy: CachePolicy = this.memoryCachePolicy, diskCachePolicy: CachePolicy = this.diskCachePolicy, networkCachePolicy: CachePolicy = this.networkCachePolicy, ) = DefaultRequestOptions( interceptorDispatcher = interceptorDispatcher, fetcherDispatcher = fetcherDispatcher, decoderDispatcher = decoderDispatcher, transformationDispatcher = transformationDispatcher, transitionFactory = transitionFactory, precision = precision, bitmapConfig = bitmapConfig, allowHardware = allowHardware, allowRgb565 = allowRgb565, placeholder = placeholder, error = error, fallback = fallback, memoryCachePolicy = memoryCachePolicy, diskCachePolicy = diskCachePolicy, networkCachePolicy = networkCachePolicy, ) override fun equals(other: Any?): Boolean { if (this === other) return true return other is DefaultRequestOptions && interceptorDispatcher == other.interceptorDispatcher && fetcherDispatcher == other.fetcherDispatcher && decoderDispatcher == other.decoderDispatcher && transformationDispatcher == other.transformationDispatcher && transitionFactory == other.transitionFactory && precision == other.precision && bitmapConfig == other.bitmapConfig && allowHardware == other.allowHardware && allowRgb565 == other.allowRgb565 && placeholder == other.placeholder && error == other.error && fallback == other.fallback && memoryCachePolicy == other.memoryCachePolicy && diskCachePolicy == other.diskCachePolicy && networkCachePolicy == other.networkCachePolicy } override fun hashCode(): Int { var result = interceptorDispatcher.hashCode() result = 31 * result + fetcherDispatcher.hashCode() result = 31 * result + decoderDispatcher.hashCode() result = 31 * result + transformationDispatcher.hashCode() result = 31 * result + transitionFactory.hashCode() result = 31 * result + precision.hashCode() result = 31 * result + bitmapConfig.hashCode() result = 31 * result + allowHardware.hashCode() result = 31 * result + allowRgb565.hashCode() result = 31 * result + placeholder.hashCode() result = 31 * result + error.hashCode() result = 31 * result + fallback.hashCode() result = 31 * result + memoryCachePolicy.hashCode() result = 31 * result + diskCachePolicy.hashCode() result = 31 * result + networkCachePolicy.hashCode() return result } }
apache-2.0
86226e128c1a054c7bfb30f1ed6f2e09
43.462963
86
0.695127
5.395506
false
true
false
false
guloggratis/srvc-google-analytics
src/main/kotlin/gg/main/MainVerticle.kt
1
3176
package gg.main import gg.util.Config import gg.util.DateTimeImport import gg.util.DateTimespan import gg.util.EventBusHandler import io.vertx.core.AbstractVerticle import io.vertx.core.DeploymentOptions import io.vertx.core.Future import org.slf4j.LoggerFactory import org.slf4j.MDC import java.util.* import java.util.concurrent.atomic.AtomicInteger /** * The main verticle which sets up the environment and starts the other verticles. */ @Suppress("unused") class MainVerticle : AbstractVerticle() { private val logger = LoggerFactory.getLogger(this::class.java) override fun start(startFuture: Future<Void>?) { MDC.put("verticle", "main") logger.info("Starting up service : srvc-google-analytics") Config.init(vertx, { _ -> /** Count of services. */ val serviceCount = AtomicInteger() /** List of verticles that we are starting. */ val verticles = Arrays.asList( "gg.analytics.ApiVerticle" , "gg.analytics.DataVerticle" ) DateTimeImport.updateDateTimeImport() DateTimespan.updateDateTimespanDefault() /* Starting API */ vertx.deployVerticle(verticles.get(0)) { deployResponse -> if (deployResponse.failed()) { logger.error("Unable to deploy verticle ${verticles.get(0)}", deployResponse.cause()) } else { logger.info("${verticles.get(0)} deployed") serviceCount.incrementAndGet() } } /* Starting Data Verticles as workers */ val options = DeploymentOptions() .setWorker(true) .setMaxWorkerExecuteTime(2147483647) .setWorkerPoolSize(20) .setInstances(6) vertx.deployVerticle(verticles.get(1),options) { deployResponse -> if (deployResponse.failed()) { logger.error("Unable to deploy verticle ${verticles.get(1)}", deployResponse.cause()) } else { logger.info("${verticles.get(1)} deployed") serviceCount.incrementAndGet() } } val conf = Config.get() val busConf = conf.getJsonObject("event_bus").getString("bus_name") /* Invoke using the event bus. */ EventBusHandler.sendIntEvent(busConf, 0, this) /** Wake up in five seconds and check to see if we are deployed if not complain. */ vertx.setTimer(5000) { _ -> if (serviceCount.get() != verticles.size) { val msg = "Main Verticle was unable to start all child verticles" val vertxCount = "(" + serviceCount + " - " + verticles.size + ")" logger.error(msg) logger.error(vertxCount) this.stop() } else { logger.info("Start up successful") } } }) } }
apache-2.0
fac423c6448f6dff04366fb998ea3f33
35.090909
96
0.546285
4.826748
false
false
false
false
Llullas/Activity-Analizer
app/src/main/java/com/dedudevgmail/activityanalyzer/model/database/Item.kt
1
2598
package com.dedudevgmail.activityanalyzer.model.database import android.location.Location import android.os.Parcel import android.os.Parcelable import java.text.SimpleDateFormat import java.util.* /** * com.dedudevgmail.activityanalyzer.model.storage * Created by Llullas on 07.04.2017. */ class Item : Parcelable { override fun describeContents(): Int = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(name) dest.writeInt(if (isAudio) 1 else 0) dest.writeLong(timestamp) location?.writeToParcel(dest, flags) dest.writeString(uid) } var name: String = "default" var isAudio: Boolean = false var timestamp: Long = 0L var location: Location? = null var uid: String = "default" constructor() constructor(userId: String, isAudio: Boolean, timestamp: Long) { this.name = getDate(timestamp) + "_" + userId.substring(SUBSTRING_BEGINNING_INDEX, SUBSTRING_END_INDEX) this.uid = userId this.isAudio = isAudio this.timestamp = timestamp this.location = null } constructor(userId: String, isAudio: Boolean, name: String, timestamp: Long) { this.name = getDate(timestamp) + "_" + name this.uid = userId this.isAudio = isAudio this.timestamp = timestamp this.location = null } override fun toString(): String { return "Item: name:" + name + " | " + "id:" + uid + " | " + "time:" + getDate(timestamp) } fun fileHeader(): String { return "File created on " + getDate(timestamp) + " at location " + "...\n" + "time" + TAB + "x" + TAB + "y" + TAB + "z" + TAB + "lat" + TAB + "lng" + TAB + "\n" } companion object { private val SUBSTRING_BEGINNING_INDEX = 0 private val SUBSTRING_END_INDEX = 10 val TAB = "\t" val SUFFIX = ".txt" private fun getDate(timestamp: Long): String { if (timestamp != 0L) { return SimpleDateFormat("YY-MM-dd_hh-mm-ss", Locale.getDefault()).format(Date(timestamp)) } else { return "error" } } @JvmField @Suppress("unused") val CREATOR = createParcel { Item(it) } } } inline fun <reified T : Parcelable> createParcel( crossinline createFromParcel: (Parcel) -> T?): Parcelable.Creator<T> = object : Parcelable.Creator<T> { override fun createFromParcel(source: Parcel): T? = createFromParcel(source) override fun newArray(size: Int): Array<out T?> = arrayOfNulls(size) } private fun Item(parcel: Parcel): Item { val item = Item() item.name = parcel.readString() item.isAudio = parcel.readInt() == 1 item.timestamp = parcel.readLong() item.location = Location.CREATOR.createFromParcel(parcel) item.uid = parcel.readString() return item }
apache-2.0
6869f2f45377e4fd82d6129665ffbda0
24.99
162
0.687837
3.322251
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackChaptersDialog.kt
3
2592
package eu.kanade.tachiyomi.ui.manga.track import android.app.Dialog import android.os.Bundle import android.widget.NumberPicker import com.afollestad.materialdialogs.MaterialDialog import com.bluelinelabs.conductor.Controller import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.ui.base.controller.DialogController import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class SetTrackChaptersDialog<T> : DialogController where T : Controller, T : SetTrackChaptersDialog.Listener { private val item: TrackItem constructor(target: T, item: TrackItem) : super(Bundle().apply { putSerializable(KEY_ITEM_TRACK, item.track) }) { targetController = target this.item = item } @Suppress("unused") constructor(bundle: Bundle) : super(bundle) { val track = bundle.getSerializable(KEY_ITEM_TRACK) as Track val service = Injekt.get<TrackManager>().getService(track.sync_id)!! item = TrackItem(track, service) } override fun onCreateDialog(savedViewState: Bundle?): Dialog { val item = item val dialog = MaterialDialog.Builder(activity!!) .title(R.string.chapters) .customView(R.layout.track_chapters_dialog, false) .positiveText(android.R.string.ok) .negativeText(android.R.string.cancel) .onPositive { dialog, _ -> val view = dialog.customView if (view != null) { // Remove focus to update selected number val np: NumberPicker = view.findViewById(R.id.chapters_picker) np.clearFocus() (targetController as? Listener)?.setChaptersRead(item, np.value) } } .build() val view = dialog.customView if (view != null) { val np: NumberPicker = view.findViewById(R.id.chapters_picker) // Set initial value np.value = item.track?.last_chapter_read ?: 0 // Don't allow to go from 0 to 9999 np.wrapSelectorWheel = false } return dialog } interface Listener { fun setChaptersRead(item: TrackItem, chaptersRead: Int) } private companion object { const val KEY_ITEM_TRACK = "SetTrackChaptersDialog.item.track" } }
apache-2.0
2a7d82ffd422fe328e91c53a138094c0
33.054054
88
0.607639
4.645161
false
false
false
false
tronalddump-io/tronald-app
src/main/kotlin/io/tronalddump/app/slack/SlackCommandRequest.kt
1
2707
package io.tronalddump.app.slack import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class) data class SlackCommandRequest( @JsonProperty("channel_id") var channelId: String? = null, @JsonProperty("channel_name") var channelName: String? = null, /** * The command that was typed in to trigger this request. * This value can be useful if you want to use a single * Request URL to service multiple Slash Commands, as it * lets you tell them apart. */ @JsonProperty("command") var command: String? = null, @JsonProperty("enterprise_id") var enterpriseId: String? = null, @JsonProperty("enterprise_name") var enterpriseName: String? = null, /** * A URL that you can use to respond to the command. */ @JsonProperty("enterprise_url") var responseUrl: String? = null, @JsonProperty("team_domain") var teamDomain: String? = null, @JsonProperty("team_id") var teamId: String? = null, /** * This is the part of the Slash Command after the command itself, and it can contain absolutely * anything that the user might decide to type. It is common to use this text parameter to provide * extra context for the command. */ @JsonProperty("text") var text: String? = null, /** * This is a verification token, a deprecated feature that you shouldn't use any more. It was used * to verify that requests were legitimately being sent by Slack to your app, but you should use * the signed secrets functionality to do this instead. */ @JsonProperty("token") var token: String? = null, /** * If you need to respond to the command by opening a dialog, you'll need this trigger ID to get * it to work. You can use this ID with dialog.open up to 3000ms after this data payload is sent. */ @JsonProperty("trigger_id") var triggerId: String? = null, /** * The ID of the user who triggered the command. */ @JsonProperty("user_id") var userId: String? = null, /** * The plain text name of the user who triggered the command. As above, do not rely on this field * as it is being phased out, use the user_id instead. */ @JsonProperty("user_name") var userName: String? = null )
gpl-3.0
97026e59653ab664948975138c798191
34.155844
106
0.617658
4.619454
false
false
false
false
cypressious/learning-spaces
app/src/androidTest/java/de/maxvogler/learningspaces/services/LocationServiceBaseTest.kt
2
3877
package de.maxvogler.learningspaces.services import de.maxvogler.learningspaces.BaseTest import de.maxvogler.learningspaces.R import de.maxvogler.learningspaces.helpers.toWeekday import de.maxvogler.learningspaces.models.Weekday import de.maxvogler.learningspaces.models.Weekday.FRIDAY import de.maxvogler.learningspaces.models.Weekday.MONDAY import de.maxvogler.learningspaces.models.Weekday.SATURDAY import de.maxvogler.learningspaces.models.Weekday.SUNDAY import org.joda.time.LocalDateTime import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue public open class LocationServiceBaseTest : BaseTest() { @Throws(Exception::class) public fun testSize() { assertEquals(TOTAL_SEATS.size(), locations.size()) } @Throws(Exception::class) public fun testNames() { TOTAL_SEATS.keySet().forEach { name -> assertEquals(1, locations.filterValues { it.name == name }.size()); } } @Throws(Exception::class) public fun testTotalSeats() { TOTAL_SEATS.forEach { data -> val name = data.getKey() val expectedSeats: Int = data.getValue() val seats: Int = locations.values().first { it.name == name }.totalSeats assertEquals(expectedSeats, seats, "$name has $seats instead of expected $expectedSeats seats") } } @Throws(Exception::class) public fun testOpeningHours() { val ib = locations["FBI"]!! val oh = ib.openingHours val baseDate = LocalDateTime(2014, 12, 14, 0, 17) assertEquals(SUNDAY, baseDate.dayOfWeek.toWeekday()) (MONDAY..FRIDAY).forEach { val date = baseDate.plusDays(it.toInt()) assertEquals(it, date.toWeekday()) (0..8).forEach { assertFalse(oh.containsDateTime(date.withHourOfDay(it))) } (9..21).forEach { assertTrue(oh.containsDateTime(date.withHourOfDay(it))) } (22..23).forEach { assertFalse(oh.containsDateTime(date.withHourOfDay(it))) } } val saturday = baseDate.plusDays(SATURDAY.toInt()) val sunday = baseDate.plusDays(SUNDAY.toInt()) (0..8).forEach { assertFalse(oh.containsDateTime(saturday.withHourOfDay(it))) } (9..12).forEach { assertTrue(oh.containsDateTime(saturday.withHourOfDay(it))) } (13..23).forEach { assertFalse(oh.containsDateTime(saturday.withHourOfDay(it))) } (0..23).forEach { assertFalse(oh.containsDateTime(sunday.withHourOfDay(it))) } } @Throws(Exception::class) public fun testOpeningHourDescriptions() { val ib = locations["FBI"]!! checkOpeningHourDescriptions(ib.openingHours.getHoursStrings()) } public fun checkOpeningHourDescriptions(strings: Map<Weekday, String>) { for (i in MONDAY..FRIDAY) { assertEquals("09:00 - 22:00", strings.get(i)) } assertEquals("09:00 - 12:30", strings.get(SATURDAY)) assertEquals(context.getString(R.string.closed), strings.get(SUNDAY)) } companion object { private fun <K, V> newHashMap(vararg items: Any): Map<K, V> { return (1..items.size() step 2).toMap( { items[it - 1] as K }, { items[it] as V } ) } private val TOTAL_SEATS = newHashMap<String, Int>("KIT-Bibliothek Süd (Altbau)", 314, "KIT-Bibliothek Süd (Neubau)", 532, "Fachbibliothek Chemie (FBC)", 193, "Lernzentrum am Fasanenschlösschen", 94, "Wirtschaftswissenschaftliche Fakultätsbibliothek", 90, "Fachbibliothek Physik (FBP)", 86, "Informatikbibliothek", 59, "Mathematische Bibliothek", 40, "Fakultätsbibliothek Architektur", 15, "KIT-Bibliothek Nord", 37, "Fachbibliothek Hochschule Karlsruhe (FBH)", 285, "Fachbibliothek an der DHBW Karlsruhe (FBD)", 38, "TheaBib im Badischen Staatstheater", 150) } }
gpl-2.0
b8f221ea58360356516cfb0e6bb8ec5e
39.333333
566
0.66813
3.796078
false
true
false
false
ejeinc/Meganekko
library/src/main/java/org/meganekkovr/xml/PositionHandler.kt
1
635
package org.meganekkovr.xml import android.content.Context import org.meganekkovr.Entity /** * Define `position` attribute. */ internal class PositionHandler : XmlAttributeParser.XmlAttributeHandler { override val attributeName = "position" override fun parse(entity: Entity, rawValue: String, context: Context) { val strs = rawValue.split("\\s+".toRegex(), 3) if (strs.size == 3) { val x = strs[0].toFloatOrNull() ?: return val y = strs[1].toFloatOrNull() ?: return val z = strs[2].toFloatOrNull() ?: return entity.setPosition(x, y, z) } } }
apache-2.0
55ccf0bbacdf134a0e601edb04cbd510
25.458333
76
0.625197
4.096774
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepDetermineFlowAfterPreflow.kt
1
5312
package io.particle.mesh.setup.flow.setupsteps import androidx.annotation.WorkerThread import io.particle.firmwareprotos.ctrl.Network.InterfaceEntry import io.particle.firmwareprotos.ctrl.Network.InterfaceType import io.particle.mesh.common.android.livedata.awaitUpdate import io.particle.mesh.common.android.livedata.nonNull import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate import io.particle.mesh.setup.flow.* import io.particle.mesh.setup.flow.FlowIntent.FIRST_TIME_SETUP import io.particle.mesh.setup.flow.FlowIntent.SINGLE_TASK_FLOW import io.particle.mesh.setup.flow.context.NetworkSetupType import io.particle.mesh.setup.flow.context.NetworkSetupType.AS_GATEWAY import io.particle.mesh.setup.flow.context.NetworkSetupType.NODE_JOINER import io.particle.mesh.setup.flow.context.NetworkSetupType.STANDALONE import io.particle.mesh.setup.flow.context.SetupContexts import io.particle.mesh.setup.flow.context.SetupDevice import mu.KotlinLogging class StepDetermineFlowAfterPreflow(private val flowUi: FlowUiDelegate) : MeshSetupStep() { private val log = KotlinLogging.logger {} @WorkerThread override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { when(ctxs.flowIntent!!) { SINGLE_TASK_FLOW -> log.info { "Single task flow; continue." } FIRST_TIME_SETUP -> onFirstTimeSetup(ctxs, scopes) } } private suspend fun onFirstTimeSetup(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.meshNetworkFlowAdded) { // we've already completed all this; bail! return } ctxs.currentFlow = determineRemainingFlow(ctxs, scopes) throw ExpectedFlowException("Restarting flow to run new steps") } private suspend fun determineRemainingFlow( ctxs: SetupContexts, scopes: Scopes ): List<FlowType> { ensureHasEthernetChecked(ctxs) val meshOnly = (ctxs.targetDevice.connectivityType == Gen3ConnectivityType.MESH_ONLY && !ctxs.hasEthernet!!) if (meshOnly) { ctxs.meshNetworkFlowAdded = true return listOf(FlowType.PREFLOW, FlowType.JOINER_FLOW) } if (!ctxs.currentFlow.contains(FlowType.INTERNET_CONNECTED_PREFLOW)) { // we're in an internet connected flow. Run through that flow and come back here. ctxs.mesh.showNewNetworkOptionInScanner = true return listOf(FlowType.PREFLOW, FlowType.INTERNET_CONNECTED_PREFLOW) } // if we get here, it's time to add the correct mesh network flow type & interface setup type return addInterfaceSetupAndMeshNetworkFlows(ctxs, scopes) } private suspend fun addInterfaceSetupAndMeshNetworkFlows( ctxs: SetupContexts, scopes: Scopes ): List<FlowType> { if (ctxs.mesh.hasThreadInterface != true) { ctxs.device.networkSetupTypeLD.nonNull(scopes).runBlockOnUiThreadAndAwaitUpdate { log.info { "No Thread interface on target device; forcing network setup type to STANDALONE" } ctxs.device.updateNetworkSetupType(STANDALONE) } } determineNetworkSetupType(ctxs, scopes) if (ctxs.device.networkSetupTypeLD.value!! == NetworkSetupType.NODE_JOINER) { ctxs.meshNetworkFlowAdded = true return listOf(FlowType.PREFLOW, FlowType.JOINER_FLOW) } val flows = mutableListOf(FlowType.PREFLOW) flows.add(getInterfaceSetupFlow(ctxs)) flows.add(when(ctxs.device.networkSetupTypeLD.value!!) { AS_GATEWAY -> FlowType.NETWORK_CREATOR_POSTFLOW STANDALONE -> FlowType.STANDALONE_POSTFLOW NODE_JOINER -> FlowType.JOINER_FLOW }) ctxs.meshNetworkFlowAdded = true return flows } private fun getInterfaceSetupFlow(ctxs: SetupContexts): FlowType { return if (ctxs.hasEthernet!!) { FlowType.ETHERNET_FLOW } else { when(ctxs.targetDevice.connectivityType!!) { Gen3ConnectivityType.WIFI -> FlowType.WIFI_FLOW Gen3ConnectivityType.CELLULAR -> FlowType.CELLULAR_FLOW Gen3ConnectivityType.MESH_ONLY -> FlowType.JOINER_FLOW } } } private suspend fun ensureHasEthernetChecked(ctxs: SetupContexts) { if (ctxs.hasEthernet != null) { return } suspend fun fetchInterfaceList(targetDevice: SetupDevice): List<InterfaceEntry> { val xceiver = targetDevice.transceiverLD.value!! val reply = xceiver.sendGetInterfaceList().throwOnErrorOrAbsent() return reply.interfacesList } val interfaces = fetchInterfaceList(ctxs.targetDevice) ctxs.hasEthernet = null != interfaces.firstOrNull { it.type == InterfaceType.ETHERNET } } private suspend fun determineNetworkSetupType(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.device.networkSetupTypeLD.value != null) { return } ctxs.device.networkSetupTypeLD.nonNull(scopes).runBlockOnUiThreadAndAwaitUpdate(scopes) { flowUi.getNetworkSetupType() } flowUi.showGlobalProgressSpinner(true) } }
apache-2.0
e6e25f9b4176f8adfb5daedc64ea89a6
37.223022
101
0.682041
4.517007
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/binding/type/BaseTypeReference.kt
1
6234
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.binding.type import compiler.ast.type.TypeModifier import compiler.ast.type.TypeReference import compiler.binding.context.CTContext import compiler.lexer.SourceLocation import compiler.reportings.Reporting import kotlinext.allEqual /** * A [TypeReference] with resolved [BaseType] */ open class BaseTypeReference( val original: TypeReference, open val context: CTContext, val baseType: BaseType ) : TypeReference( original.declaredName, original.isNullable, original.modifier, original.isInferred, original.declaringNameToken ) { override val modifier: TypeModifier? = original.modifier ?: baseType.impliedModifier override fun modifiedWith(modifier: TypeModifier): BaseTypeReference { // TODO: implement type modifiers return BaseTypeReference(original.modifiedWith(modifier), context, baseType) } override fun nonNull(): BaseTypeReference = BaseTypeReference(original.nonNull(), context, baseType) override fun nullable(): BaseTypeReference = BaseTypeReference(original.nullable(), context, baseType) override fun asInferred(): BaseTypeReference = BaseTypeReference(original.asInferred(), context, baseType) /** * Validates the type reference. * * @return Any reportings on the validated code */ fun validate(): Collection<Reporting> { val reportings = mutableSetOf<Reporting>() // verify whether the modifier on the reference is compatible with the modifier on the type if (original.modifier != null && baseType.impliedModifier != null) { if (!(original.modifier!! isAssignableTo baseType.impliedModifier!!)) { val origMod = original.modifier?.toString()?.toLowerCase() val baseMod = baseType.impliedModifier?.toString()?.toLowerCase() reportings.add(Reporting.modifierError( "Cannot reference ${baseType.fullyQualifiedName} as $origMod; " + "modifier $origMod is not assignable to the implied modifier $baseMod of ${baseType.simpleName}", original.declaringNameToken?.sourceLocation ?: SourceLocation.UNKNOWN )) } } return reportings } /** @return Whether a value of this type can safely be referenced from a refence of the given type. */ infix fun isAssignableTo(other: BaseTypeReference): Boolean { // this must be a subtype of other if (!(this.baseType isSubtypeOf other.baseType)) { return false } // the modifiers must be compatible val thisModifier = modifier ?: TypeModifier.MUTABLE val otherModifier = other.modifier ?: TypeModifier.MUTABLE if (!(thisModifier isAssignableTo otherModifier)) { return false } // void-safety: // other this isCompatible // T T true // T? T true // T T? false // T? T? true if (this.isNullable != other.isNullable && (this.isNullable && !other.isNullable)) { return false } // seems all fine return true } /** * Compares the two types when a value of this type should be referenced by the given type. * @return The hierarchic distance (see [BaseType.hierarchicalDistanceTo]) if the assignment is possible, * null otherwise. */ fun assignMatchQuality(other: BaseTypeReference): Int? = if (this isAssignableTo other) this.baseType.hierarchicalDistanceTo(other.baseType) else null override fun toString(): String { var str = "" if (modifier != null) { str += modifier!!.name.toLowerCase() + " " } str += baseType.fullyQualifiedName if (isNullable) { str += "?" } return str } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BaseTypeReference if (baseType != other.baseType) return false if (modifier != other.modifier) return false return true } override fun hashCode(): Int { var result = baseType.hashCode() result = 31 * result + (modifier?.hashCode() ?: 0) return result } companion object { fun closestCommonAncestorOf(types: List<BaseTypeReference>): BaseTypeReference { if (types.size == 0) throw IllegalArgumentException("At least one type must be provided") if (types.size == 1) return types[0] val typeModifiers = types.map { it.modifier ?: TypeModifier.MUTABLE } val modifier: TypeModifier when { typeModifiers.allEqual -> modifier = typeModifiers[0] types.any { it.modifier == TypeModifier.READONLY || it.modifier == TypeModifier.IMMUTABLE} -> modifier = TypeModifier.READONLY else -> modifier = TypeModifier.MUTABLE } return BaseType.closestCommonAncestorOf(types.map(BaseTypeReference::baseType)) .baseReference(types[0].context) .modifiedWith(modifier) } fun closestCommonAncestorOf(vararg types: BaseTypeReference): BaseTypeReference { return closestCommonAncestorOf(types.asList()) } } }
lgpl-3.0
49f5a4dc3b39e6cd5e1960109d849e94
34.420455
142
0.646776
4.924171
false
false
false
false
SUPERCILEX/Robot-Scouter
feature/templates/src/main/java/com/supercilex/robotscouter/feature/templates/viewholder/CounterTemplateViewHolder.kt
1
2132
package com.supercilex.robotscouter.feature.templates.viewholder import android.os.Build import android.view.View import android.widget.EditText import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.core.view.updatePadding import androidx.core.view.updatePaddingRelative import com.supercilex.robotscouter.core.data.model.updateName import com.supercilex.robotscouter.core.data.model.updateUnit import com.supercilex.robotscouter.core.data.nullOrFull import com.supercilex.robotscouter.core.model.Metric import com.supercilex.robotscouter.core.unsafeLazy import com.supercilex.robotscouter.shared.scouting.viewholder.CounterViewHolder import kotlinx.android.synthetic.main.scout_template_base_reorder.* import kotlinx.android.synthetic.main.scout_template_counter.* import com.supercilex.robotscouter.R as RC internal class CounterTemplateViewHolder(itemView: View) : CounterViewHolder(itemView), MetricTemplateViewHolder<Metric.Number, Long> { override val reorderView: ImageView by unsafeLazy { reorder } override val nameEditor = name as EditText init { init() itemView as LinearLayout itemView.removeView(unit) itemView.addView(unit, itemView.childCount - 1) itemView.findViewById<View>(RC.id.countContainer).apply { if (Build.VERSION.SDK_INT >= 17) { updatePaddingRelative(end = 0) } else { updatePadding(right = 0) } } unit.onFocusChangeListener = this } override fun bind() { super.bind() unit.setText(metric.unit) } override fun onClick(v: View) { super.onClick(v) if (name.hasFocus()) metric.updateName(name.text.toString()) } override fun bindValue(count: TextView) { count.text = countFormat.format(metric.value) } override fun onFocusChange(v: View, hasFocus: Boolean) { super.onFocusChange(v, hasFocus) if (!hasFocus && v === unit) { metric.updateUnit(unit.text.nullOrFull()?.toString()) } } }
gpl-3.0
413c38571472065150b80387ecdc3d20
32.84127
87
0.711538
4.333333
false
false
false
false
KawakawaRitsuki/JapaneCraft
src/main/kotlin/com/wcaokaze/japanecraft/VariableExpander.kt
1
2674
package com.wcaokaze.japanecraft import kotlin.coroutines.experimental.buildSequence class VariableExpander(strWithVars: String) { private val tokenExpanderList = parse(strWithVars) fun expand(variableMap: Map<String, String>): String { return tokenExpanderList .map { it.expand(variableMap) } .fold(StringBuffer()) { buffer, token -> buffer.append(token) } .toString() } private fun parse(str: String): List<TokenExpander> { val identifierStartCharList = ('a'..'z') + ('A'..'Z') + '_' val identifierPartCharList = identifierStartCharList + ('0'..'9') fun Char.isIdentifierStart() = this in identifierStartCharList fun Char.isIdentifierPart() = this in identifierPartCharList return buildSequence { val buffer = StringBuffer(str) yieldToken@ while (buffer.isNotEmpty()) { searchDollar@ for (i in 0 until buffer.lastIndex) { if (buffer[i] != '$') continue@searchDollar if (buffer[i + 1] == '{') { val closeBraceIdx = buffer.indexOf("}") if (closeBraceIdx == -1) continue@searchDollar val constantStr = buffer.substring(0, i) val variableName = buffer.substring(i + 2, closeBraceIdx) .dropWhile { it == ' ' } .dropLastWhile { it == ' ' } yield(TokenExpander.ConstantString(constantStr)) yield(TokenExpander.VariableExpander(variableName)) buffer.delete(0, closeBraceIdx + 1) continue@yieldToken } else if (buffer[i + 1].isIdentifierStart()) { yield(TokenExpander.ConstantString(buffer.substring(0, i))) buffer.delete(0, i + 1) val variableName = buffer.takeWhile { it.isIdentifierPart() } .toString() yield(TokenExpander.VariableExpander(variableName)) buffer.delete(0, variableName.length) continue@yieldToken } } yield(TokenExpander.ConstantString(buffer.toString())) buffer.delete(0, buffer.length) } } .toList() } private sealed class TokenExpander { abstract fun expand(variableMap: Map<String, String>): String class ConstantString(private val str: String) : TokenExpander() { override fun expand(variableMap: Map<String, String>): String { return str } } class VariableExpander(private val variableName: String) : TokenExpander() { override fun expand(variableMap: Map<String, String>): String { return variableMap.getOrDefault(variableName, "\${$variableName}") } } } }
lgpl-2.1
101451065484ccb146c91d3b1f487e85
33.282051
80
0.616679
4.494118
false
false
false
false
jtransc/jtransc
benchmark_kotlin_mpp/src/commonMain/kotlin/CRC32.kt
1
833
@file:Suppress("unused") class CRC32 { /* * The following logic has come from RFC1952. */ private var v = 0 companion object { private val crc_table: IntArray = IntArray(256).also { crc_table -> for (n in 0..255) { var c = n var k = 8 while (--k >= 0) { c = if (c and 1 != 0) { -0x12477ce0 xor (c ushr 1) } else { c ushr 1 } } crc_table[n] = c } } } fun update(buf: ByteArray, index: Int, len: Int) { //int[] crc_table = CRC32.crc_table; var idx = index var l = len var c = v.inv() while (--l >= 0) { c = crc_table[c xor buf[idx++].toInt() and 0xff] xor (c ushr 8) } v = c.inv() } fun reset() { v = 0 } fun reset(vv: Int) { v = vv } val value: Int get() = v fun copy(): CRC32 { val foo = CRC32() foo.v = v return foo } }
apache-2.0
c021c6b917197b8aac87f56d6371901f
15.019231
69
0.515006
2.464497
false
false
false
false
outadoc/Twistoast-android
keolisprovider/src/main/kotlin/fr/outadev/android/transport/timeo/TimeoStop.kt
1
1510
/* * Twistoast - TimeoStop.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast 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. * * Twistoast 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 fr.outadev.android.transport.timeo import org.joda.time.DateTime /** * A bus stop. * * @author outadoc */ data class TimeoStop(val id: Int, val name: String, var line: TimeoLine, var reference: String? = null) { /** * Checks if this stop is outdated and its reference needs to be updated. * @return true if it needs to be updated, otherwise false */ var isOutdated: Boolean = false /** * Checks if notifications are currently active for this bus stop. */ var isWatched: Boolean = false /** * Gets the last estimated time of arrival for this bus stop. * @return a timestamp of an approximation of the arrival of the next bus */ var lastETA: DateTime? = null override fun toString(): String = name }
gpl-3.0
54116896834568266d46a718eca6e32f
30.458333
105
0.699338
4.037433
false
false
false
false
Raniz85/ffbe-grinder
src/main/kotlin/se/raneland/ffbe/service/ScreenshotCollector.kt
1
3759
/* * Copyright (c) 2017, Daniel Raniz Raneland */ package se.raneland.ffbe.service import mu.KLogging import se.vidstige.jadb.JadbDevice import java.awt.image.BufferedImage import java.io.DataInputStream import java.io.EOFException import java.io.FilterInputStream import java.io.InputStream import java.nio.IntBuffer import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.isAccessible class ScreenshotCollector(val device: JadbDevice, val adbLocation: String, val ffmpegLocation: String, val callback: (BufferedImage) -> Unit) : Thread("screenshot-collector") { companion object: KLogging() { const val width = 720 const val height = 1280 } var ffmpeg : Process var imageStream : InputStream val streamLock = Any() @Volatile var run: Boolean = true init { ffmpeg = startFfmpeg() imageStream = ffmpeg.inputStream start() } private fun startFfmpeg() : Process { logger.info("Starting ffmpeg") val adbCommand = "${adbLocation} -s ${device.serial} shell screenrecord --output-format=h264 --time-limit=180 --size=${width}x${height} - | ${ffmpegLocation} -r 60 -i - -f image2pipe -c:v rawvideo -pix_fmt argb -r 5 -" //val adbCommand = "${adbLocation} -s ${device.serial} shell screenrecord --output-format=h264 --time-limit=180 --size=${width}x${height} - " //val adbCommand = "ffmpeg -f rawvideo -pix_fmt rgb24 -video_size ${width}x${height} -r 5 -i /dev/urandom -f image2pipe -c:v rawvideo -pix_fmt rgb24 -r 5 -" logger.debug(adbCommand) return ProcessBuilder() .redirectError(ProcessBuilder.Redirect.INHERIT) .command("sh", "-c", adbCommand) .start() } fun stopAndWait() { run = false ffmpeg.destroyForcibly() imageStream.close() interrupt() logger.info("Waiting for collector to finish") join() } fun restartCapturing() { synchronized(streamLock) { ffmpeg.destroyForcibly() imageStream.close() ffmpeg = startFfmpeg() imageStream = ffmpeg.inputStream } } override fun run() { logger.info("Starting screenshot collection") while (run) { val currentImage = IntBuffer.allocate(width * height) val dataStream = DataInputStream(imageStream) while (run) { // Read images try { currentImage.put(dataStream.readInt()) } catch (e: EOFException) { logger.debug("Ffmpeg has died") break } if (currentImage.remaining() == 0) { // Extract pixels from buffer val pixels = currentImage.array() val image = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) image.raster.setDataElements(0, 0, width, height, pixels) callback(image) currentImage.clear() } } if (run) { logger.info("Starting screenshot collection from fresh ffmpeg") restartCapturing() } } logger.info("Ending screenshot collection") } private fun unfilter(stream: InputStream): InputStream { if (stream is FilterInputStream) { val inField = FilterInputStream::class.memberProperties .find { it.name == "in" } ?: throw Error("FilterInputStream has no 'in' field") inField.isAccessible = true return inField.get(stream) as InputStream } return stream } }
mit
965550c25fc9c9175e426970ae23d527
33.181818
226
0.588454
4.518029
false
false
false
false
enchf/kotlin-koans
src/iii_conventions/n30DestructuringDeclarations.kt
4
556
package iii_conventions.multiAssignemnt import util.TODO import util.doc30 fun todoTask30(): Nothing = TODO( """ Task 30. Read about destructuring declarations and make the following code compile by adding one 'data' modifier. """, documentation = doc30() ) class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) fun isLeapDay(date: MyDate): Boolean { todoTask30() // val (year, month, dayOfMonth) = date // // // 29 February of a leap year // return year % 4 == 0 && month == 2 && dayOfMonth == 29 }
mit
d6472d2c7f354b36963b4aba6ff17e8c
24.272727
112
0.654676
3.731544
false
false
false
false
laurencegw/jenjin
jenjin-demo/src/com/binarymonks/jj/demo/demos/D14_spine_bounding_boxes.kt
1
1164
package com.binarymonks.jj.demo.demos import com.badlogic.gdx.graphics.Color import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.JJConfig import com.binarymonks.jj.core.JJGame import com.binarymonks.jj.core.specs.SceneSpec import com.binarymonks.jj.core.specs.SceneSpecRef import com.binarymonks.jj.spine.specs.SpineSpec class D14_spine_bounding_boxes : JJGame(JJConfig { b2d.debugRender = true val width = 6f gameView.worldBoxWidth = width gameView.cameraPosX = 0f gameView.cameraPosY = 2f gameView.clearColor = Color(0.5f, 0.7f, 1f, 1f) }) { override fun gameOn() { JJ.scenes.addSceneSpec("spineDummy", spine_with_bounding_boxes()) JJ.scenes.loadAssetsNow() JJ.scenes.instantiate(SceneSpec { node( "spineDummy" ) }) } fun spine_with_bounding_boxes(): SceneSpecRef { return SpineSpec { spineRender { atlasPath = "spine/male_base.atlas" dataPath = "spine/male_base.json" scale = 1.5f / 103f } skeleton { boundingBoxes = true } } } }
apache-2.0
75ba515ba250952e79bf4ea230a38926
26.093023
73
0.630584
3.592593
false
false
false
false
mfietz/fyydlin
src/main/kotlin/FyydResponse.kt
1
1676
package de.mfietz.fyydlin import com.squareup.moshi.Json import java.util.* data class FyydResponse( val status: Int, val msg: String, val meta: MetaData, val data: List<SearchHit> ) data class SearchHit( val title: String, val id: Int, @field:Json(name = "xmlURL") val xmlUrl: String, @field:Json(name = "htmlURL")val htmlUrl: String, @field:Json(name = "imgURL") val imageUrl: String, val status: Int, val slug: String, val layoutImageUrl: String, val thumbImageURL: String, val smallImageURL: String, val microImageURL: String, val language: String, val lastpoll: String, val generator: String, val categories: IntArray, @field:Json(name = "lastpub") val lastPubDate: Date, val rank: Int, @field:Json(name = "url_fyyd") val urlFyyd: String, val description: String, val subtitle: String, val author: String, @field:Json(name = "count_episodes") val countEpisodes: Int ) data class MetaData( val paging: Paging, @field:Json(name = "API_INFO") val apiInfo: ApiInfo, @field:Json(name = "SERVER") val server: String, val duration: Int ) data class Paging( val count: Int, val page: Int, @field:Json(name = "first_page") val firstPage: Int, @field:Json(name = "last_page") val lastPage: Int, @field:Json(name = "next_page") val nextPage: Int?, @field:Json(name = "prev_page") val prevPage: Int? ) data class ApiInfo( @field:Json(name = "API_VERSION") val apiVersion: Double )
apache-2.0
30e5e47238d5ce26e5099f5b93063bb3
28.928571
67
0.602029
3.596567
false
false
false
false
Yubyf/QuoteLock
app/src/main/java/com/crossbowffs/quotelock/components/MaterialPreferenceDialogFragmentCompat.kt
1
4852
package com.crossbowffs.quotelock.components import android.app.Dialog import android.content.DialogInterface import android.graphics.drawable.BitmapDrawable import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.preference.ListPreferenceDialogFragmentCompat import androidx.preference.MultiSelectListPreferenceDialogFragmentCompat import androidx.preference.PreferenceDialogFragmentCompat import com.crossbowffs.quotelock.utils.getReflectionField import com.crossbowffs.quotelock.utils.invokeReflectionMethod import com.crossbowffs.quotelock.utils.setReflectionField import com.google.android.material.dialog.MaterialAlertDialogBuilder private fun PreferenceDialogFragmentCompat.createMaterialDialog( savedInstanceState: Bundle?, builderBlock: ((AlertDialog.Builder, String?) -> Unit), ): Dialog { var title: String? = null var icon: BitmapDrawable? = null var positiveButtonText: String? = null var negativeButtonText: String? = null var message: String? = null runCatching { setReflectionField("mWhichButtonClicked", DialogInterface.BUTTON_NEGATIVE) title = getReflectionField<String>("mDialogTitle") icon = getReflectionField<BitmapDrawable>("mDialogIcon") positiveButtonText = getReflectionField<String>("mPositiveButtonText") negativeButtonText = getReflectionField<String>("mNegativeButtonText") message = getReflectionField<String>("mDialogMessage") }.onFailure { return onCreateDialog(savedInstanceState) } val builder = MaterialAlertDialogBuilder(requireContext()) .setTitle(title) .setIcon(icon) .setPositiveButton(positiveButtonText, this) .setNegativeButton(negativeButtonText, this) .setMessage(message) .setBackgroundInsetTop(0) .setBackgroundInsetBottom(0) builderBlock.invoke(builder, message) // Create the dialog val dialog = builder.create() if (invokeReflectionMethod<Boolean>("needInputMethod") == true) { invokeReflectionMethod<Boolean>("requestInputMethod", linkedMapOf(Dialog::class.java to dialog)) } return builder.create() } /** * A [androidx.preference.PreferenceDialogFragmentCompat] that uses a [MaterialAlertDialogBuilder]. * * @author Yubyf */ abstract class MaterialPreferenceDialogFragmentCompat : PreferenceDialogFragmentCompat() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = createMaterialDialog(savedInstanceState) { builder, message -> val contentView = onCreateDialogView(requireContext()) if (contentView != null) { onBindDialogView(contentView) builder.setView(contentView) } else { builder.setMessage(message) } onPrepareDialogBuilder(builder) } } /** * A [androidx.preference.ListPreferenceDialogFragmentCompat] that uses a [MaterialAlertDialogBuilder]. * * @author Yubyf */ class MaterialListPreferenceDialogFragmentCompat : ListPreferenceDialogFragmentCompat() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = createMaterialDialog(savedInstanceState) { builder, message -> val contentView = onCreateDialogView(requireContext()) if (contentView != null) { onBindDialogView(contentView) builder.setView(contentView) } else { builder.setMessage(message) } onPrepareDialogBuilder(builder) } companion object { fun newInstance(key: String?): ListPreferenceDialogFragmentCompat = MaterialListPreferenceDialogFragmentCompat().apply { arguments = Bundle(1).apply { putString(ARG_KEY, key) } } } } /** * A [androidx.preference.MultiSelectListPreferenceDialogFragmentCompat] that uses a [MaterialAlertDialogBuilder]. * * @author Yubyf */ class MaterialMultiSelectListPreferenceDialogFragmentCompat : MultiSelectListPreferenceDialogFragmentCompat() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = createMaterialDialog(savedInstanceState) { builder, message -> val contentView = onCreateDialogView(requireContext()) if (contentView != null) { onBindDialogView(contentView) builder.setView(contentView) } else { builder.setMessage(message) } onPrepareDialogBuilder(builder) } companion object { fun newInstance(key: String?): MultiSelectListPreferenceDialogFragmentCompat = MaterialMultiSelectListPreferenceDialogFragmentCompat().apply { arguments = Bundle(1).apply { putString(ARG_KEY, key) } } } }
mit
8c17ce2578cb5e7fe70327d67294fb41
35.765152
114
0.703627
5.681499
false
false
false
false
MichaelRocks/paranoid
sample/src/main/java/io/michaelrocks/paranoid/sample/MainActivity.kt
1
2033
/* * Copyright 2020 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.paranoid.sample import android.app.AlertDialog import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import io.michaelrocks.paranoid.Obfuscate @Obfuscate class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) val questionTextView = findViewById<TextView>(R.id.questionTextView) questionTextView.text = String.format(QUESTION, "How does it work?") val answerTextView = findViewById<TextView>(R.id.answerTextView) answerTextView.text = String.format(ANSWER, "It's magic! ¯\\_(ツ)_/¯") val showDialogButton = findViewById<Button>(R.id.showDialogButton) showDialogButton.text = "Show dialog" showDialogButton.setOnClickListener { Toast.makeText(this@MainActivity, "Button clicked", Toast.LENGTH_SHORT).show() AlertDialog.Builder(this@MainActivity) .setTitle("Title") .setMessage("Message 2") .setPositiveButton("Close") { dialog, _ -> Toast.makeText(this@MainActivity, "Dialog dismissed", Toast.LENGTH_SHORT).show() dialog.dismiss() } .show() } } companion object { private const val QUESTION = "Q:\r\n%s" private const val ANSWER = "A:\r\n%s" } }
apache-2.0
ec4d6fcaab2b97dba58beeabfaff1a03
33.389831
90
0.724495
4.183505
false
false
false
false
google/kiosk-app-reference-implementation
app/src/main/java/com/ape/apps/sample/baypilot/ui/welcome/WelcomeActivity.kt
1
3752
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ape.apps.sample.baypilot.ui.welcome import android.content.Intent import android.os.Bundle import android.provider.Settings import android.util.Log import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.ape.apps.sample.baypilot.R import com.ape.apps.sample.baypilot.databinding.ActivityWelcomeBinding import com.ape.apps.sample.baypilot.ui.home.HomeActivity import com.ape.apps.sample.baypilot.util.network.InternetConnectivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class WelcomeActivity : AppCompatActivity() { companion object { private const val TAG = "BayPilotWelcomeActivity" } private lateinit var binding: ActivityWelcomeBinding private lateinit var auth: FirebaseAuth private val viewModel: WelcomeViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { Log.d(TAG, "onCreate() called with: savedInstanceState") super.onCreate(savedInstanceState) auth = Firebase.auth binding = ActivityWelcomeBinding.inflate(layoutInflater) val view = binding.root setContentView(view) binding.buttonInternet.setOnClickListener { startActivity(Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)) } } override fun onStart() { super.onStart() val currentUser = auth.currentUser if (currentUser == null) { Log.d(TAG, "Creating new Anonymous user") signIn() } else { Log.d(TAG, "Current firebase auth is not null. Checking if its still first run...") viewModel.checkFirstRun(applicationContext) Log.d(TAG, "Not first run. Starting Main Activity") val intent = Intent(this, HomeActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } startActivity(intent) } } private fun signIn() { // Try signing in Anonymously. auth.signInAnonymously() .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success Log.d(TAG, "signInAnonymously:success. Starting initial Setup after sign in success") viewModel.initialSetup(applicationContext) Log.d(TAG, "Starting Main Activity after sign in Success") val intent = Intent(this, HomeActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } startActivity(intent) } else { // TODO: Add checks for specific errors. // If sign in failed, display a message to the user. Log.e(TAG, "signInAnonymously:failure", task.exception) Toast.makeText( baseContext, "Authentication failed." + task.exception, Toast.LENGTH_SHORT ).show() binding.textViewErrorMsg.setText(R.string.connect_to_internet_welcome) // Trying SignIn Again when internet connection is available. InternetConnectivity(this).observe(this) { signIn() } } } } }
apache-2.0
221bb04429d4d08978ee924ed780e9c4
32.508929
95
0.703625
4.383178
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/util/SuggestedCommandsFactory.kt
1
8055
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.util import android.content.Context import android.text.InputType import androidx.annotation.StringRes import org.openhab.habdroid.R import org.openhab.habdroid.model.Item import org.openhab.habdroid.model.Widget import org.openhab.habdroid.model.withValue class SuggestedCommandsFactory(private val context: Context, private val showUndef: Boolean) { fun fill(widget: Widget?, forItemUpdate: Boolean = false): SuggestedCommands { val suggestedCommands = SuggestedCommands() if (widget?.item == null || widget.type == Widget.Type.Chart) { return suggestedCommands } for ((value, label) in widget.mappingsOrItemOptions) { add(suggestedCommands, value, label) } if (widget.type === Widget.Type.Setpoint || widget.type === Widget.Type.Slider) { val state = widget.state?.asNumber if (state != null) { add(suggestedCommands, state.toString()) add(suggestedCommands, state.withValue(widget.minValue).toString()) add(suggestedCommands, state.withValue(widget.maxValue).toString()) if (widget.switchSupport) { addOnOffCommands(suggestedCommands) } } } fill(widget.item, suggestedCommands, forItemUpdate) return suggestedCommands } fun fill(item: Item?, forItemUpdate: Boolean = false): SuggestedCommands { val suggestedCommands = SuggestedCommands() if (item != null) { fill(item, suggestedCommands, forItemUpdate) } return suggestedCommands } private fun fill(item: Item, suggestedCommands: SuggestedCommands, forItemUpdate: Boolean) = when { item.isOfTypeOrGroupType(Item.Type.Color) -> { addOnOffCommands(suggestedCommands) addIncreaseDecreaseCommands(suggestedCommands) if (item.state != null) { add(suggestedCommands, item.state.asString, R.string.nfc_action_current_color) } addCommonPercentCommands(suggestedCommands) suggestedCommands.shouldShowCustom = true } item.isOfTypeOrGroupType(Item.Type.Contact) -> { @Suppress("ControlFlowWithEmptyBody") if (forItemUpdate) { add(suggestedCommands, "OPEN", R.string.nfc_action_open) add(suggestedCommands, "CLOSED", R.string.nfc_action_closed) add(suggestedCommands, "TOGGLE", R.string.nfc_action_toggled) } else { // Contact Items cannot receive commands } } item.isOfTypeOrGroupType(Item.Type.Dimmer) -> { addOnOffCommands(suggestedCommands) addIncreaseDecreaseCommands(suggestedCommands) addCommonPercentCommands(suggestedCommands) suggestedCommands.inputTypeFlags = INPUT_TYPE_SINGED_DECIMAL_NUMBER suggestedCommands.shouldShowCustom = true } item.isOfTypeOrGroupType(Item.Type.Number) -> { // Don't suggest numbers that might be totally out of context if there's already // at least one command if (suggestedCommands.entries.isEmpty()) { addCommonNumberCommands(suggestedCommands) } item.state?.asString?.let { value -> add(suggestedCommands, value) } suggestedCommands.inputTypeFlags = INPUT_TYPE_SINGED_DECIMAL_NUMBER suggestedCommands.shouldShowCustom = true } item.isOfTypeOrGroupType(Item.Type.NumberWithDimension) -> { val numberState = item.state?.asNumber if (numberState != null) { add(suggestedCommands, numberState.toString()) } suggestedCommands.shouldShowCustom = true } item.isOfTypeOrGroupType(Item.Type.Player) -> { add(suggestedCommands, "PLAY", R.string.nfc_action_play) add(suggestedCommands, "PAUSE", R.string.nfc_action_pause) add(suggestedCommands, "TOGGLE", R.string.nfc_action_toggle) add(suggestedCommands, "NEXT", R.string.nfc_action_next) add(suggestedCommands, "PREVIOUS", R.string.nfc_action_previous) add(suggestedCommands, "REWIND", R.string.nfc_action_rewind) add(suggestedCommands, "FASTFORWARD", R.string.nfc_action_fastforward) } item.isOfTypeOrGroupType(Item.Type.Rollershutter) -> { add(suggestedCommands, "UP", R.string.nfc_action_up) add(suggestedCommands, "DOWN", R.string.nfc_action_down) add(suggestedCommands, "TOGGLE", R.string.nfc_action_toggle) add(suggestedCommands, "MOVE", R.string.nfc_action_move) add(suggestedCommands, "STOP", R.string.nfc_action_stop) addCommonPercentCommands(suggestedCommands) suggestedCommands.inputTypeFlags = INPUT_TYPE_DECIMAL_NUMBER } item.isOfTypeOrGroupType(Item.Type.StringItem) -> { if (showUndef) { add(suggestedCommands, "", R.string.nfc_action_empty_string) add(suggestedCommands, "UNDEF", R.string.nfc_action_undefined) } item.state?.asString?.let { value -> add(suggestedCommands, value) } suggestedCommands.shouldShowCustom = true } item.isOfTypeOrGroupType(Item.Type.Switch) -> { addOnOffCommands(suggestedCommands) } showUndef -> { add(suggestedCommands, "UNDEF", R.string.nfc_action_undefined) suggestedCommands.shouldShowCustom = true } else -> {} } private fun add(suggestedCommands: SuggestedCommands, command: String, @StringRes label: Int) { add(suggestedCommands, command, context.getString(label)) } private fun add(suggestedCommands: SuggestedCommands, command: String, label: String = command) { if (command !in suggestedCommands.entries.map { entry -> entry.command }) { suggestedCommands.entries.add(SuggestedCommand(command, label)) } } private fun addCommonNumberCommands(suggestedCommands: SuggestedCommands) { for (command in arrayOf("0", "33", "50", "66", "100")) { add(suggestedCommands, command) } } private fun addCommonPercentCommands(suggestedCommands: SuggestedCommands) { for (command in arrayOf("0", "33", "50", "66", "100")) { add(suggestedCommands, command, "$command\u00A0%") } } private fun addOnOffCommands(suggestedCommands: SuggestedCommands) { add(suggestedCommands, "ON", R.string.nfc_action_on) add(suggestedCommands, "OFF", R.string.nfc_action_off) add(suggestedCommands, "TOGGLE", R.string.nfc_action_toggle) } private fun addIncreaseDecreaseCommands(suggestedCommands: SuggestedCommands) { add(suggestedCommands, "INCREASE", R.string.nfc_action_increase) add(suggestedCommands, "DECREASE", R.string.nfc_action_decrease) } data class SuggestedCommand(val command: String, val label: String) inner class SuggestedCommands { var entries: MutableList<SuggestedCommand> = mutableListOf() var shouldShowCustom = false var inputTypeFlags = InputType.TYPE_CLASS_TEXT } companion object { private const val INPUT_TYPE_DECIMAL_NUMBER = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL private const val INPUT_TYPE_SINGED_DECIMAL_NUMBER = INPUT_TYPE_DECIMAL_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED } }
epl-1.0
ef21ddae1005969031c109e3b4426bd4
42.074866
103
0.6473
4.408867
false
false
false
false
rock3r/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/KtCompiler.kt
1
2300
package io.gitlab.arturbosch.detekt.core import io.gitlab.arturbosch.detekt.api.internal.ABSOLUTE_PATH import io.gitlab.arturbosch.detekt.api.internal.RELATIVE_PATH import io.gitlab.arturbosch.detekt.api.internal.createKotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt import org.jetbrains.kotlin.com.intellij.psi.PsiFileFactory import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtFile import java.nio.file.Path open class KtCompiler( protected val environment: KotlinCoreEnvironment = createKotlinCoreEnvironment() ) { protected val psiFileFactory: PsiFileFactory = PsiFileFactory.getInstance(environment.project) fun compile(root: Path, subPath: Path): KtFile { require(subPath.isFile()) { "Given sub path ($subPath) should be a regular file!" } val relativePath = (if (root == subPath) subPath.fileName else root.fileName.resolve(root.relativize(subPath))).normalize() val absolutePath = subPath.toAbsolutePath().normalize() val content = subPath.toFile().readText() val lineSeparator = content.determineLineSeparator() val ktFile = createKtFile(content, absolutePath) return ktFile.apply { putUserData(LINE_SEPARATOR, lineSeparator) putUserData(RELATIVE_PATH, relativePath.toString()) putUserData(ABSOLUTE_PATH, absolutePath.toString()) } } private fun createKtFile(content: String, path: Path): KtFile { val psiFile = psiFileFactory.createFileFromText( path.fileName.toString(), KotlinLanguage.INSTANCE, StringUtilRt.convertLineSeparators(content), true, true, false, LightVirtualFile(path.toString()) ) return psiFile as? KtFile ?: error("kotlin file expected") } } internal fun String.determineLineSeparator(): String { val i = this.lastIndexOf('\n') if (i == -1) { return if (this.lastIndexOf('\r') == -1) System.getProperty("line.separator") else "\r" } return if (i != 0 && this[i - 1] == '\r') "\r\n" else "\n" }
apache-2.0
e48c7e5a25b03d45c4af838c6bdab3d2
40.818182
98
0.703043
4.554455
false
false
false
false
kareez/dahgan
loader/src/main/kotlin/io/dahgan/loader/Loader.kt
1
6149
package io.dahgan.loader import io.dahgan.loader.EndOfLineVisitor.LineFeedVisitor import io.dahgan.loader.EndOfLineVisitor.LineFoldVisitor import io.dahgan.parser.Code import io.dahgan.parser.Token import io.dahgan.yaml import java.io.File import java.util.* /** * Loads the first yaml document in the given text and returns the loaded object. * Depending on the content, the result can be a simple text, a map or a list. */ fun load(text: String): Any = load(text.toByteArray(Charsets.UTF_8)) /** * Loads the first yaml document in the given file and returns the loaded object. * Depending on the content, the result can be a simple text, a map or a list. */ fun load(file: File): Any = load(file.readBytes()) /** * Loads the first yaml document in the given byte array and returns the loaded object. * Depending on the content, the result can be a simple text, a map or a list. */ fun load(bytes: ByteArray): Any = load(yaml().tokenize("load", bytes, false))[0] /** * Loads all yaml documents in the given text and returns the loaded objects. * The result is a list of loaded objects. */ fun loadAll(text: String): List<Any> = loadAll(text.toByteArray(Charsets.UTF_8)) /** * Loads all yaml documents in the given file and returns the loaded objects. * The result is a list of loaded objects. */ fun loadAll(file: File): List<Any> = loadAll(file.readBytes()) /** * Loads all yaml documents in the given byte array and returns the loaded objects. * The result is a list of loaded objects. */ fun loadAll(bytes: ByteArray): List<Any> = load(yaml().tokenize("load-all", bytes, false)) private fun load(tokens: List<Token>): List<Any> { val contexts = LoaderStack() tokens.forEach { visitor(it.code).visit(contexts, it) } val result = contexts.pop().take() if (result is List<*>) { return result as List<Any> } throw IllegalStateException("unexpected result: $result") } private fun visitor(code: Code): Visitor = when (code) { Code.Text -> TextVisitor Code.Meta -> TextVisitor Code.LineFeed -> LineFeedVisitor Code.LineFold -> LineFoldVisitor Code.BeginComment -> BeginIgnoreVisitor Code.EndComment -> EndIgnoreVisitor Code.BeginAnchor -> Begin(SingleContext()) Code.EndAnchor -> EndVisitor Code.BeginAlias -> Begin(SingleContext()) Code.EndAlias -> EndAliasVisitor Code.BeginScalar -> Begin(ScalarContext()) Code.EndScalar -> EndVisitor Code.BeginSequence -> Begin(ListContext()) Code.EndSequence -> EndVisitor Code.BeginMapping -> Begin(MapContext()) Code.EndMapping -> EndVisitor Code.BeginPair -> Begin(PairContext()) Code.EndPair -> EndVisitor Code.BeginNode -> Begin(NodeContext()) Code.EndNode -> EndNodeVisitor Code.BeginDocument -> Begin(SingleContext()) Code.EndDocument -> EndVisitor Code.Error -> ErrorVisitor else -> SkipVisitor } private abstract class Context { protected val data: MutableList<Any> = ArrayList() fun add(any: Any) = data.add(any) abstract fun take(): Any } private class SingleContext : Context() { override fun take(): Any = data.first() } private class ScalarContext : Context() { override fun take(): Any = data.joinToString("") } private class NodeContext : Context() { override fun take(): Any = if (data.size > 1) Pair(data.first(), data[1]) else Pair("", data.first()) } private class ListContext : Context() { override fun take(): Any = data } private class MapContext : Context() { override fun take(): Any = (data as List<Pair<*, *>>).toMap() } private class PairContext : Context() { override fun take(): Any = Pair(data[0], data[1]) } private interface Visitor { fun visit(stack: LoaderStack, token: Token) } private class Begin(val context: Context) : Visitor { override fun visit(stack: LoaderStack, token: Token) { stack.push(context) } } private object BeginIgnoreVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { stack.push(object : Context() { override fun take(): Any = throw UnsupportedOperationException() }) } } private object EndIgnoreVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { stack.pop() } } private object EndVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { val top = stack.pop() stack.peek().add(top.take()) } } private object EndNodeVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { val top = stack.pop().take() as Pair<Any, Any> if (top.first.toString().isNotEmpty()) { stack.anchor(top.first.toString(), top.second) } stack.peek().add(top.second) } } private object EndAliasVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { val top = stack.pop() stack.peek().add(stack.anchor(top.take().toString())) } } private object TextVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { stack.peek().add(token.text.toString()) } } private abstract class EndOfLineVisitor(val join: String) : Visitor { override fun visit(stack: LoaderStack, token: Token) { stack.peek().add(join) } object LineFoldVisitor : EndOfLineVisitor(" ") object LineFeedVisitor : EndOfLineVisitor("\n") } private object ErrorVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) { throw IllegalStateException("${token.text} - Line #${token.line} , Character #${token.lineChar + 1}") } } private object SkipVisitor : Visitor { override fun visit(stack: LoaderStack, token: Token) = Unit } private class LoaderStack { private val contexts = mutableListOf<Context>(ListContext()) private val anchors = HashMap<String, Any>() fun push(context: Context) = contexts.add(context) fun peek() = contexts.last() fun pop() = contexts.removeAt(contexts.lastIndex) fun anchor(key: String, value: Any) = anchors.set(key, value) fun anchor(key: String) = anchors[key]!! }
apache-2.0
dc942f89f82487f09ecc3cf25153398a
28.280952
109
0.679623
3.850344
false
false
false
false
tipsy/javalin
javalin/src/main/java/io/javalin/http/JavalinResponseWrapper.kt
1
3624
package io.javalin.http import io.javalin.core.JavalinConfig import io.javalin.core.compression.CompressedStream import io.javalin.core.util.Header.CONTENT_ENCODING import io.javalin.core.util.Header.ETAG import io.javalin.core.util.Header.IF_NONE_MATCH import io.javalin.core.util.Util import io.javalin.http.HandlerType.GET import io.javalin.http.HttpCode.NOT_MODIFIED import java.io.InputStream import javax.servlet.ServletOutputStream import javax.servlet.WriteListener import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponseWrapper class JavalinResponseWrapper(private val ctx: Context, private val config: JavalinConfig, private val requestType: HandlerType) : HttpServletResponseWrapper(ctx.res) { private val outputStreamWrapper by lazy { OutputStreamWrapper(config, ctx) } override fun getOutputStream() = outputStreamWrapper private val serverEtag by lazy { getHeader(ETAG) } private val clientEtag by lazy { ctx.req.getHeader(IF_NONE_MATCH) } fun write(resultStream: InputStream?) = when { resultStream == null -> {} // nothing to write (and nothing to close) serverEtag != null && serverEtag == clientEtag -> closeWith304(resultStream) // client etag matches, nothing to write serverEtag == null && requestType == GET && config.autogenerateEtags -> generateEtagWriteAndClose(resultStream) else -> writeToWrapperAndClose(resultStream) } private fun generateEtagWriteAndClose(resultStream: InputStream) { val inputStream = resultStream.use { it.readBytes().inputStream() } // TODO: https://github.com/tipsy/javalin/issues/1505 val generatedEtag = Util.getChecksumAndReset(inputStream) setHeader(ETAG, generatedEtag) when (generatedEtag) { clientEtag -> closeWith304(inputStream) else -> writeToWrapperAndClose(inputStream) } } private fun writeToWrapperAndClose(inputStream: InputStream) { inputStream.use { input -> outputStreamWrapper.use { output -> input.copyTo(output) } } } private fun closeWith304(inputStream: InputStream) { inputStream.use { ctx.status(NOT_MODIFIED) } } } class OutputStreamWrapper(val config: JavalinConfig, val ctx: Context, val response: HttpServletResponse = ctx.res) : ServletOutputStream() { private val compression = config.inner.compressionStrategy private var compressedStream: CompressedStream? = null override fun write(bytes: ByteArray, offset: Int, length: Int) { if (compressedStream == null && length >= compression.minSizeForCompression && response.contentType.allowsForCompression()) { compressedStream = CompressedStream.tryBrotli(compression, ctx) ?: CompressedStream.tryGzip(compression, ctx) compressedStream?.let { response.setHeader(CONTENT_ENCODING, it.type.typeName) } } (compressedStream?.outputStream ?: response.outputStream).write(bytes, offset, length) // fall back to default stream if no compression } private fun String?.allowsForCompression(): Boolean = this == null || compression.excludedMimeTypesFromCompression.none { excluded -> this.contains(excluded, ignoreCase = true) } override fun write(byte: Int) = response.outputStream.write(byte) override fun setWriteListener(writeListener: WriteListener?) = response.outputStream.setWriteListener(writeListener) override fun isReady(): Boolean = response.outputStream.isReady override fun close() { compressedStream?.outputStream?.close() } }
apache-2.0
6aa80e15976606eb7cb095e1575a496e
46.064935
167
0.732616
4.564232
false
true
false
false
rock3r/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyBlocks.kt
1
5317
package io.gitlab.arturbosch.detekt.rules.empty import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.MultiRule import io.gitlab.arturbosch.detekt.api.Rule import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.KtClassInitializer import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDoWhileExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFinallySection import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.psi.KtIfExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPrimaryConstructor import org.jetbrains.kotlin.psi.KtSecondaryConstructor import org.jetbrains.kotlin.psi.KtTryExpression import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.KtWhileExpression /** * * <noncompliant> * // unnecessary empty blocks should be removed * fun unnecessaryFunction() { * } * </noncompliant> * * @active since v1.0.0 */ @Suppress("TooManyFunctions") class EmptyBlocks(val config: Config = Config.empty) : MultiRule() { private val emptyCatchBlock = EmptyCatchBlock(config) private val emptyClassBlock = EmptyClassBlock(config) private val emptyDefaultConstructor = EmptyDefaultConstructor(config) private val emptyDoWhileBlock = EmptyDoWhileBlock(config) private val emptyElseBlock = EmptyElseBlock(config) private val emptyFinallyBlock = EmptyFinallyBlock(config) private val emptyForBlock = EmptyForBlock(config) private val emptyFunctionBlock = EmptyFunctionBlock(config) private val emptyIfBlock = EmptyIfBlock(config) private val emptyInitBlock = EmptyInitBlock(config) private val emptyKtFile = EmptyKtFile(config) private val emptySecondaryConstructorBlock = EmptySecondaryConstructor(config) private val emptyTryBlock = EmptyTryBlock(config) private val emptyWhenBlock = EmptyWhenBlock(config) private val emptyWhileBlock = EmptyWhileBlock(config) override val rules: List<Rule> = listOf( emptyCatchBlock, emptyClassBlock, emptyDefaultConstructor, emptyDoWhileBlock, emptyElseBlock, emptyFinallyBlock, emptyForBlock, emptyFunctionBlock, emptyIfBlock, emptyInitBlock, emptyKtFile, emptySecondaryConstructorBlock, emptyTryBlock, emptyWhenBlock, emptyWhileBlock ) override fun visitKtFile(file: KtFile) { emptyKtFile.runIfActive { visitFile(file) } emptyClassBlock.runIfActive { file.declarations.filterIsInstance<KtClassOrObject>().forEach { visitClassOrObject(it) } } super.visitKtFile(file) } override fun visitTryExpression(expression: KtTryExpression) { emptyTryBlock.runIfActive { visitTryExpression(expression) } super.visitTryExpression(expression) } override fun visitCatchSection(catchClause: KtCatchClause) { emptyCatchBlock.runIfActive { visitCatchSection(catchClause) } super.visitCatchSection(catchClause) } override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) { emptyDefaultConstructor.runIfActive { visitPrimaryConstructor(constructor) } super.visitPrimaryConstructor(constructor) } override fun visitDoWhileExpression(expression: KtDoWhileExpression) { emptyDoWhileBlock.runIfActive { visitDoWhileExpression(expression) } super.visitDoWhileExpression(expression) } override fun visitIfExpression(expression: KtIfExpression) { emptyIfBlock.runIfActive { visitIfExpression(expression) } emptyElseBlock.runIfActive { visitIfExpression(expression) } super.visitIfExpression(expression) } override fun visitFinallySection(finallySection: KtFinallySection) { emptyFinallyBlock.runIfActive { visitFinallySection(finallySection) } super.visitFinallySection(finallySection) } override fun visitForExpression(expression: KtForExpression) { emptyForBlock.runIfActive { visitForExpression(expression) } super.visitForExpression(expression) } override fun visitNamedFunction(function: KtNamedFunction) { emptyFunctionBlock.runIfActive { visitNamedFunction(function) } super.visitNamedFunction(function) } override fun visitClassInitializer(initializer: KtClassInitializer) { emptyInitBlock.runIfActive { visitClassInitializer(initializer) } super.visitClassInitializer(initializer) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { emptySecondaryConstructorBlock.runIfActive { visitSecondaryConstructor(constructor) } super.visitSecondaryConstructor(constructor) } override fun visitWhenExpression(expression: KtWhenExpression) { emptyWhenBlock.runIfActive { visitWhenExpression(expression) } super.visitWhenExpression(expression) } override fun visitWhileExpression(expression: KtWhileExpression) { emptyWhileBlock.runIfActive { visitWhileExpression(expression) } super.visitWhileExpression(expression) } }
apache-2.0
abc040398da94e0f532fa54d87e67ca2
37.528986
93
0.747038
5.233268
false
true
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/presentation/navigation/SurveyAdapter.kt
1
3305
/* * Copyright (C) 2017,2019-2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. * */ package org.akvo.flow.presentation.navigation import android.content.Context import android.graphics.Typeface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import org.akvo.flow.R import org.akvo.flow.presentation.navigation.SurveyAdapter.SurveyViewHolder import java.util.ArrayList internal class SurveyAdapter(context: Context) : RecyclerView.Adapter<SurveyViewHolder>() { private val surveyList: MutableList<ViewSurvey> = ArrayList() private val selectedTextColor: Int = ContextCompat.getColor(context, R.color.orange_main) private val textColor: Int = ContextCompat.getColor(context, R.color.black_main) private var selectedSurveyId: Long = 0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SurveyViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.navigation_item, parent, false) return SurveyViewHolder(view, selectedTextColor, textColor) } fun setSurveys(surveys: List<ViewSurvey>, selectedSurveyId: Long) { this.selectedSurveyId = selectedSurveyId surveyList.clear() if (surveys.isNotEmpty()) { surveyList.addAll(surveys) } notifyDataSetChanged() } override fun onBindViewHolder(holder: SurveyViewHolder, position: Int) { val viewSurvey = surveyList[position] holder.setViews(viewSurvey, selectedSurveyId == viewSurvey.id) } override fun getItemCount(): Int { return surveyList.size } fun getItem(position: Int): ViewSurvey { return surveyList[position] } fun updateSelected(surveyId: Long) { selectedSurveyId = surveyId notifyDataSetChanged() } internal class SurveyViewHolder( view: View, private val selectedTextColor: Int, private val textColor: Int ) : RecyclerView.ViewHolder(view) { private val surveyTv: TextView = view.findViewById(R.id.item_text_view) fun setViews(navigationItem: ViewSurvey, isSelected: Boolean) { surveyTv.text = navigationItem.name if (navigationItem.viewed || isSelected) { surveyTv.setTypeface(null, Typeface.NORMAL) } else { surveyTv.setTypeface(null, Typeface.BOLD) } surveyTv.setTextColor(if (isSelected) selectedTextColor else textColor) } } }
gpl-3.0
55df38f19db2c9acec10312f3269e041
36.134831
93
0.709531
4.47226
false
false
false
false
binaryfoo/emv-bertlv
src/main/java/io/github/binaryfoo/decoders/ICCPublicKeyDecoder.kt
1
3046
package io.github.binaryfoo.decoders import io.github.binaryfoo.* import io.github.binaryfoo.crypto.RecoveredPublicKeyCertificate import io.github.binaryfoo.decoders.annotator.SignedDataDecoder import io.github.binaryfoo.tlv.ISOUtil /** * EMV 4.3 Book2, Table 14: Format of Data Recovered from ICC Public Key Certificate */ class ICCPublicKeyDecoder : SignedDataDecoder { override fun decodeSignedData(session: DecodeSession, decoded: List<DecodedData>) { val recoveredIssuerPublicKeyCertificate = session.issuerPublicKeyCertificate val iccCertificate = decoded.findTlvForTag(EmvTags.ICC_PUBLIC_KEY_CERTIFICATE) if (iccCertificate != null && recoveredIssuerPublicKeyCertificate != null && recoveredIssuerPublicKeyCertificate.exponent != null) { for (decodedCertificate in decoded.findAllForTag(EmvTags.ICC_PUBLIC_KEY_CERTIFICATE)) { val result = recoverCertificate(iccCertificate, decodedCertificate, recoveredIssuerPublicKeyCertificate, ::decodeICCPublicKeyCertificate) if (result.certificate != null) { result.certificate.rightKeyPart = decoded.findValueForTag(EmvTags.ICC_PUBLIC_KEY_REMAINDER) result.certificate.exponent = decoded.findValueForTag(EmvTags.ICC_PUBLIC_KEY_EXPONENT) session.iccPublicKeyCertificate = result.certificate } } } } } fun decodeICCPublicKeyCertificate(recovered: ByteArray, byteLengthOfIssuerModulus: Int, startIndexInBytes: Int): RecoveredPublicKeyCertificate { val publicKeyLength = Integer.parseInt(ISOUtil.hexString(recovered, 19, 1), 16) val exponentLength = ISOUtil.hexString(recovered, 20, 1) var lengthOfLeftKeyPart = if (publicKeyLength > byteLengthOfIssuerModulus - 42) byteLengthOfIssuerModulus - 42 else publicKeyLength val leftKeyPart = ISOUtil.hexString(recovered, 21, lengthOfLeftKeyPart) val children = listOf( DecodedData.byteRange("Header", recovered, 0, 1, startIndexInBytes), DecodedData.byteRange("Format", recovered, 1, 1, startIndexInBytes), DecodedData.byteRange("PAN", recovered, 2, 10, startIndexInBytes), DecodedData.byteRange("Expiry Date (MMYY)", recovered, 12, 2, startIndexInBytes), DecodedData.byteRange("Serial number", recovered, 14, 3, startIndexInBytes), DecodedData.byteRange("Hash algorithm", recovered, 17, 1, startIndexInBytes), DecodedData.byteRange("Public key algorithm", recovered, 18, 1, startIndexInBytes), DecodedData.byteRange("Public key length", publicKeyLength.toString(), 19, 1, startIndexInBytes), DecodedData.byteRange("Public key exponent length", exponentLength, 20, 1, startIndexInBytes), DecodedData.byteRange("Public key", leftKeyPart, 21, lengthOfLeftKeyPart, startIndexInBytes), DecodedData.byteRange("Hash", recovered, 21 + byteLengthOfIssuerModulus - 42, 20, startIndexInBytes), DecodedData.byteRange("Trailer", recovered, 21 + byteLengthOfIssuerModulus - 42 + 20, 1, startIndexInBytes) ) return RecoveredPublicKeyCertificate("ICC", children, exponentLength, leftKeyPart) }
mit
3e773a1aff0f5b934d665080074b25ed
58.72549
145
0.770847
4.55988
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/inventory/InventoryView.kt
1
1266
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.inventory import org.lanternpowered.api.util.uncheckedCast fun <T : AbstractInventory> List<InventoryView<T>>.asInventories(): List<T> = this.uncheckedCast() fun <T : AbstractInventory> InventoryView<T>.asInventory(): T = this.uncheckedCast() fun <T : AbstractInventory> List<T>.createViews(parent: AbstractInventory?): List<InventoryView<T>> = this.map { inventory -> inventory.createView(parent) } fun <T : AbstractInventory> T.createView(parent: AbstractInventory?): InventoryView<T> { if (this.parent == parent) return this.uncheckedCast() val view = this.original().instantiateView() (view as AbstractInventory).parent = parent return view.uncheckedCast() } fun <T : AbstractInventory> T.original(): T = if (this is InventoryView<*>) this.backing.uncheckedCast() else this interface InventoryView<out T : AbstractInventory> { val backing: T }
mit
c6491993400fc3d864e106206f4880dc
33.216216
101
0.71485
3.895385
false
false
false
false
sephiroth74/AndroidUIGestureRecognizer
app/src/main/java/it/sephiroth/android/library/uigestures/demo/fragments/UIPanGestureRecognizerFragment.kt
1
1903
package it.sephiroth.android.library.uigestures.demo.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import it.sephiroth.android.library.uigestures.UIGestureRecognizer import it.sephiroth.android.library.uigestures.UIPanGestureRecognizer import it.sephiroth.android.library.uigestures.demo.R import kotlinx.android.synthetic.main.content_uipangesturerecognizer.* import timber.log.Timber import java.lang.ref.WeakReference class UIPanGestureRecognizerFragment(recognizer: WeakReference<UIGestureRecognizer>) : IRecognizerFragment<UIPanGestureRecognizer>(recognizer) { override fun getRecognizerStatus(): String? { getRecognizer()?.let { return "scroll: ${it.scrollX}, ${it.scrollY}, touches: ${it.numberOfTouches}" } return null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Timber.i("onCreate") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.content_uipangesturerecognizer, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) getRecognizer()?.let { numberPicker1.value = it.minimumNumberOfTouches numberPicker2.value = it.maximumNumberOfTouches } numberPicker1.setListener { getRecognizer()?.minimumNumberOfTouches = it } numberPicker2.setListener { getRecognizer()?.maximumNumberOfTouches = it } } companion object { @JvmStatic fun newInstance(recognizer: UIGestureRecognizer) = UIPanGestureRecognizerFragment(WeakReference(recognizer)) } }
mit
501a2f0fe0f05ba75ae4e44f5fae4848
33.6
116
0.71939
4.854592
false
false
false
false
bravelocation/yeltzland-android
app/src/main/java/com/bravelocation/yeltzlandnew/views/MainActivityView.kt
1
1151
package com.bravelocation.yeltzlandnew.views import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.navigation.compose.rememberNavController import com.bravelocation.yeltzlandnew.dataproviders.AnalyticsManager import com.bravelocation.yeltzlandnew.viewmodels.MainActivityViewModel import com.bravelocation.yeltzlandnew.navigation.Navigation import com.google.accompanist.permissions.ExperimentalPermissionsApi @ExperimentalAnimationApi @ExperimentalPermissionsApi @Composable fun MainActivityView(viewModel: MainActivityViewModel) { val navController = rememberNavController() navController.addOnDestinationChangedListener { _, destination, _ -> destination.route?.let { routeName -> AnalyticsManager.logScreenView(routeName) } } Scaffold( bottomBar = { BottomNavigationBar( navController = navController, viewModel = viewModel ) } ) { it Navigation( navController = navController, viewModel = viewModel ) } }
mit
d92a3cb4a0c21ea93a699e9a8a6413a1
31
72
0.754996
5.902564
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/adapters/OpponentsFromCallAdapter.kt
1
7492
package com.quickblox.sample.videochat.kotlin.adapters import android.annotation.SuppressLint import android.content.Context import android.util.Log import android.util.SparseIntArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ProgressBar import android.widget.RelativeLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.quickblox.sample.videochat.kotlin.R import com.quickblox.sample.videochat.kotlin.fragments.BaseConversationFragment import com.quickblox.users.model.QBUser import com.quickblox.videochat.webrtc.QBRTCTypes import com.quickblox.videochat.webrtc.view.QBRTCSurfaceView class OpponentsFromCallAdapter(val context: Context, private val baseConversationFragment: BaseConversationFragment, users: List<QBUser>, private val width: Int, private val height: Int) : RecyclerView.Adapter<OpponentsFromCallAdapter.ViewHolder>() { private val TAG = OpponentsFromCallAdapter::class.java.simpleName private var _opponents: MutableList<QBUser> = users as MutableList<QBUser> val opponents: List<QBUser> get() = _opponents private var inflater: LayoutInflater = LayoutInflater.from(context) private var adapterListener: OnAdapterEventListener? = null fun setAdapterListener(adapterListener: OnAdapterEventListener) { this.adapterListener = adapterListener } override fun getItemCount(): Int { return _opponents.size } fun getItem(position: Int): Int { return _opponents[position].id } fun removeItem(index: Int) { _opponents.removeAt(index) notifyItemRemoved(index) notifyItemRangeChanged(index, _opponents.size) } fun replaceUsers(position: Int, qbUser: QBUser) { _opponents[position] = qbUser notifyItemChanged(position) } @SuppressLint("InflateParams") override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = inflater.inflate(R.layout.list_item_opponent_from_call, null) v.findViewById<RelativeLayout>(R.id.inner_layout).layoutParams = FrameLayout.LayoutParams(width, height) val vh = ViewHolder(v) vh.setListener(object : ViewHolder.ViewHolderClickListener { override fun onShowOpponent(callerId: Int) { adapterListener?.onItemClick(callerId) } }) vh.showOpponentView(true) return vh } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val user = _opponents[position] val userID = user.id val name = user.fullName ?: user.login holder.opponentsName.text = name holder.getOpponentView().id = user.id holder.setUserId(userID) val state = baseConversationFragment.getConnectionState(userID) Log.d(TAG, "state ordinal= " + state?.ordinal) state?.let { holder.setStatus(context.getString(QBRTCSessionStatus().getStatusDescription(it))) } if (position == _opponents.size - 1) { adapterListener?.onBindLastViewHolder(holder, position) } } override fun getItemId(position: Int): Long { return position.toLong() } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { internal var opponentsName: TextView private var connectionStatus: TextView private var opponentView: QBRTCSurfaceView private var progressBar: ProgressBar private var userId: Int = 0 private var viewHolderClickListener: ViewHolderClickListener? = null init { itemView.setOnClickListener(this) opponentsName = itemView.findViewById(R.id.opponent_name) connectionStatus = itemView.findViewById(R.id.connection_status) opponentView = itemView.findViewById(R.id.opponent_view) progressBar = itemView.findViewById(R.id.progress_bar_adapter) } fun setListener(viewHolderClickListener: ViewHolderClickListener) { this.viewHolderClickListener = viewHolderClickListener } fun setStatus(status: String) { connectionStatus.text = status } fun setUserName(userName: String) { opponentsName.text = userName } fun setUserId(userId: Int) { this.userId = userId } fun getUserId(): Int { return userId } fun getProgressBar(): ProgressBar { return progressBar } fun getOpponentView(): QBRTCSurfaceView { return opponentView } fun showOpponentView(show: Boolean) { Log.d("OpponentsAdapter", "show? $show") opponentView.visibility = if (show) View.VISIBLE else View.GONE } override fun onClick(v: View) { viewHolderClickListener?.onShowOpponent(adapterPosition) } interface ViewHolderClickListener { fun onShowOpponent(callerId: Int) } } private class QBRTCSessionStatus { private val peerStateDescriptions = SparseIntArray() init { peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_PENDING.ordinal, R.string.opponent_pending) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_CONNECTING.ordinal, R.string.text_status_connect) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_CHECKING.ordinal, R.string.text_status_checking) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_CONNECTED.ordinal, R.string.text_status_connected) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_DISCONNECTED.ordinal, R.string.text_status_disconnected) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_CLOSED.ordinal, R.string.opponent_closed) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_DISCONNECT_TIMEOUT.ordinal, R.string.text_status_disconnected) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_NOT_ANSWER.ordinal, R.string.text_status_no_answer) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_NOT_OFFER.ordinal, R.string.text_status_no_answer) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_REJECT.ordinal, R.string.text_status_rejected) peerStateDescriptions.put( QBRTCTypes.QBRTCConnectionState.QB_RTC_CONNECTION_HANG_UP.ordinal, R.string.text_status_hang_up) } fun getStatusDescription(connectionState: QBRTCTypes.QBRTCConnectionState): Int { return peerStateDescriptions.get(connectionState.ordinal) } } interface OnAdapterEventListener { fun onBindLastViewHolder(holder: ViewHolder, position: Int) fun onItemClick(position: Int) } }
bsd-3-clause
2d7f28482afad871c8d308151c38b847
37.823834
132
0.672985
4.899935
false
false
false
false