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
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/lexer/EscapeUtils.kt
3
1979
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.lexer import com.intellij.lexer.Lexer import com.intellij.psi.StringEscapesTokenTypes.* import com.intellij.psi.tree.IElementType fun esc(test: Boolean): IElementType = if (test) VALID_STRING_ESCAPE_TOKEN else INVALID_CHARACTER_ESCAPE_TOKEN /** * Determines if the char is a whitespace character. */ fun Char.isWhitespaceChar(): Boolean = equals(' ') || equals('\r') || equals('\n') || equals('\t') /** * Mimics [com.intellij.codeInsight.CodeInsightUtilCore.parseStringCharacters] * but obeys specific escaping rules provided by [decoder]. */ inline fun parseStringCharacters( lexer: Lexer, chars: String, outChars: StringBuilder, sourceOffsets: IntArray, decoder: (String) -> String ): Boolean { val outOffset = outChars.length var index = 0 for ((type, text) in chars.tokenize(lexer)) { // Set offset for the decoded character to the beginning of the escape sequence. sourceOffsets[outChars.length - outOffset] = index sourceOffsets[outChars.length - outOffset + 1] = index + 1 when (type) { VALID_STRING_ESCAPE_TOKEN -> { outChars.append(decoder(text)) // And perform a "jump" index += text.length } INVALID_CHARACTER_ESCAPE_TOKEN, INVALID_UNICODE_ESCAPE_TOKEN -> return false else -> { val first = outChars.length - outOffset outChars.append(text) val last = outChars.length - outOffset - 1 // Set offsets for each character of given chunk for (i in first..last) { sourceOffsets[i] = index index++ } } } } sourceOffsets[outChars.length - outOffset] = index return true }
mit
c97e91cb46fc9b8d52eed1844805f66e
30.412698
110
0.606367
4.407572
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/RsCodeFragment.kt
2
6541
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.impl.PsiManagerEx import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.psi.impl.source.tree.FileElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.tree.IElementType import com.intellij.testFramework.LightVirtualFile import org.rust.lang.RsFileType import org.rust.lang.RsLanguage import org.rust.lang.core.macros.RsExpandedElement import org.rust.lang.core.parser.RustParserUtil.PathParsingMode import org.rust.lang.core.parser.RustParserUtil.PathParsingMode.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.Namespace abstract class RsCodeFragment( fileViewProvider: FileViewProvider, contentElementType: IElementType, open val context: RsElement, forceCachedPsi: Boolean = true, val importTarget: RsItemsOwner? = null, ) : RsFileBase(fileViewProvider), PsiCodeFragment, RsItemsOwner { constructor( project: Project, text: CharSequence, contentElementType: IElementType, context: RsElement, importTarget: RsItemsOwner? = null, ) : this( PsiManagerEx.getInstanceEx(project).fileManager.createFileViewProvider( LightVirtualFile("fragment.rs", RsLanguage, text), true ), contentElementType, context, importTarget = importTarget ) override val containingMod: RsMod get() = context.containingMod override val crateRoot: RsMod? get() = context.crateRoot override fun accept(visitor: PsiElementVisitor) { visitor.visitFile(this) } override fun getFileType(): FileType = RsFileType private var viewProvider = super.getViewProvider() as SingleRootFileViewProvider private var forcedResolveScope: GlobalSearchScope? = null private var isPhysical = true init { if (forceCachedPsi) { @Suppress("LeakingThis") getViewProvider().forceCachedPsi(this) } init(TokenType.CODE_FRAGMENT, contentElementType) } final override fun init(elementType: IElementType, contentElementType: IElementType?) { super.init(elementType, contentElementType) } override fun isPhysical() = isPhysical override fun forceResolveScope(scope: GlobalSearchScope?) { forcedResolveScope = scope } override fun getForcedResolveScope(): GlobalSearchScope? = forcedResolveScope override fun getContext(): PsiElement = context final override fun getViewProvider(): SingleRootFileViewProvider = viewProvider override fun isValid() = true override fun clone(): PsiFileImpl { val clone = cloneImpl(calcTreeElement().clone() as FileElement) as RsCodeFragment clone.isPhysical = false clone.myOriginalFile = this clone.viewProvider = SingleRootFileViewProvider(PsiManager.getInstance(project), LightVirtualFile(name, RsLanguage, text), false) clone.viewProvider.forceCachedPsi(clone) return clone } companion object { @JvmStatic protected fun createFileViewProvider( project: Project, text: CharSequence, eventSystemEnabled: Boolean ): FileViewProvider { return PsiManagerEx.getInstanceEx(project).fileManager.createFileViewProvider( LightVirtualFile("fragment.rs", RsLanguage, text), eventSystemEnabled ) } } } open class RsExpressionCodeFragment : RsCodeFragment, RsInferenceContextOwner { protected constructor(fileViewProvider: FileViewProvider, context: RsElement) : super(fileViewProvider, RsCodeFragmentElementType.EXPR, context) constructor(project: Project, text: CharSequence, context: RsElement, importTarget: RsItemsOwner? = null) : super(project, text, RsCodeFragmentElementType.EXPR, context, importTarget = importTarget) val expr: RsExpr? get() = childOfType() } class RsDebuggerExpressionCodeFragment : RsExpressionCodeFragment { constructor(fileViewProvider: FileViewProvider, context: RsElement) : super(fileViewProvider, context) constructor(project: Project, text: CharSequence, context: RsElement) : super(project, text, context) } class RsStatementCodeFragment(project: Project, text: CharSequence, context: RsElement) : RsCodeFragment(project, text, RsCodeFragmentElementType.STMT, context) { val stmt: RsStmt? get() = childOfType() } class RsTypeReferenceCodeFragment( project: Project, text: CharSequence, context: RsElement, importTarget: RsItemsOwner? = null, ) : RsCodeFragment(project, text, RsCodeFragmentElementType.TYPE_REF, context, importTarget = importTarget), RsNamedElement { val typeReference: RsTypeReference? get() = childOfType() } class RsPathCodeFragment( fileViewProvider: FileViewProvider, context: RsElement, mode: PathParsingMode, val ns: Set<Namespace> ) : RsCodeFragment(fileViewProvider, mode.elementType(), context), RsInferenceContextOwner { constructor( project: Project, text: CharSequence, eventSystemEnabled: Boolean, context: RsElement, mode: PathParsingMode, ns: Set<Namespace> ) : this(createFileViewProvider(project, text, eventSystemEnabled), context, mode, ns) val path: RsPath? get() = childOfType() companion object { @JvmStatic private fun PathParsingMode.elementType() = when (this) { TYPE -> RsCodeFragmentElementType.TYPE_PATH VALUE -> RsCodeFragmentElementType.VALUE_PATH NO_TYPE_ARGS -> error("$NO_TYPE_ARGS mode is not supported; use $TYPE") } } } class RsReplCodeFragment(fileViewProvider: FileViewProvider, override var context: RsElement) : RsCodeFragment(fileViewProvider, RsCodeFragmentElementType.REPL, context, false), RsInferenceContextOwner, RsItemsOwner { val stmtList: List<RsExpandedElement> get() = childrenOfType() // if multiple elements have same name, then we keep only last among them val namedElementsUnique: Map<String, RsNamedElement> get() = stmtList .filterIsInstance<RsNamedElement>() .filter { it.name != null } .associateBy { it.name!! } }
mit
f01d1afb1340ebffb34de066388a736f
34.166667
120
0.712276
4.816642
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/commands/lang/CommandParserDefinition.kt
1
3032
package com.github.jk1.ytplugin.commands.lang import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiParser import com.intellij.lexer.Lexer import com.intellij.lexer.LexerBase import com.intellij.openapi.project.Project import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet class CommandParserDefinition : ParserDefinition { companion object { val ANY_TEXT = IElementType("ANY_TEXT", CommandLanguage) val QUERY = IElementType("QUERY", CommandLanguage) private val FILE = IFileElementType(CommandLanguage) } override fun getFileNodeType(): IFileElementType = FILE override fun getCommentTokens(): TokenSet = TokenSet.EMPTY override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY override fun getWhitespaceTokens(): TokenSet = TokenSet.EMPTY override fun createLexer(project: Project): Lexer = CommandLexer() override fun createParser(project: Project): PsiParser = CommandPsiParser() override fun createElement(node: ASTNode): PsiElement = CommandQueryElement(node) override fun createFile(provider: FileViewProvider): PsiFile = CommandFile(provider) /** * Sole element that represents YouTrack command in PSI tree */ class CommandQueryElement(node: ASTNode) : ASTWrapperPsiElement(node) /** * Tokenize whole command as single {@code ANY_TEXT} token */ inner class CommandLexer : LexerBase() { private var start: Int = 0 private var end: Int = 0 private lateinit var buffer: CharSequence override fun start(buffer: CharSequence , startOffset: Int, endOffset: Int, initialState: Int) { this.buffer = buffer this.start = startOffset this.end = endOffset } override fun getState(): Int = 0 override fun getTokenType(): IElementType? = if (start >= end) null else ANY_TEXT override fun getTokenStart() = start override fun getTokenEnd() = end override fun getBufferSequence() = buffer override fun getBufferEnd() = end override fun advance() { start = end } } /** * Parse whole YouTrack command as single {@code QUERY} element */ inner class CommandPsiParser : PsiParser { override fun parse(root: IElementType, builder: PsiBuilder): ASTNode { val rootMarker = builder.mark() val queryMarker = builder.mark() assert(builder.tokenType == null || builder.tokenType == ANY_TEXT) builder.advanceLexer() queryMarker.done(QUERY) assert(builder.eof()) rootMarker.done(root) return builder.treeBuilt } } }
apache-2.0
2aa52d03e762c05ac59c35d34f7f2452
31.265957
104
0.688984
4.922078
false
false
false
false
forusoul70/playTorrent
app/src/main/java/playtorrent/com/playtorrent/SingleFileStorage.kt
1
1063
package playtorrent.com.playtorrent import java.io.File import java.io.IOException import java.io.RandomAccessFile /** * Single File Storage */ class SingleFileStorage(size:Long, path:String): AbsFileStorage(size) { private val file:RandomAccessFile private val lock: Any = Object() init { val targetFile = File(path) file = RandomAccessFile(targetFile, "rw") if (size != targetFile.length()) { file.setLength(size) } } @Throws(IOException::class) override fun write(bytes: ByteArray, offset: Long) { synchronized(lock) { file.seek(offset) file.write(bytes, 0, bytes.size) } } @Throws(IOException::class) override fun get(offset: Long, length: Int): ByteArray { val buffer = ByteArray(length) synchronized(lock) { file.seek(offset) if (kotlin.run { file.read(buffer) != length}) { throw IOException("Failed to read $length") } } return buffer } }
apache-2.0
699e024bfc0172ac814631878e3e1e57
24.309524
71
0.596425
4.218254
false
false
false
false
goldmansachs/obevo
obevo-core/src/main/java/com/gs/obevo/impl/reader/DbDirectoryChangesetReader.kt
1
15567
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.impl.reader import com.gs.obevo.api.appdata.ChangeInput import com.gs.obevo.api.appdata.doc.TextMarkupDocumentSection import com.gs.obevo.api.platform.ChangeType import com.gs.obevo.api.platform.DeployMetrics import com.gs.obevo.api.platform.FileSourceContext import com.gs.obevo.api.platform.FileSourceParams import com.gs.obevo.impl.DeployMetricsCollector import com.gs.obevo.impl.DeployMetricsCollectorImpl import com.gs.obevo.impl.OnboardingStrategy import com.gs.obevo.util.VisibleForTesting import com.gs.obevo.util.hash.OldWhitespaceAgnosticDbChangeHashStrategy import com.gs.obevo.util.vfs.* import com.gs.obevo.util.vfs.FileFilterUtils.* import org.apache.commons.lang3.Validate import org.apache.commons.vfs2.FileFilter import org.eclipse.collections.api.block.function.Function import org.eclipse.collections.api.block.function.Function0 import org.eclipse.collections.api.list.ImmutableList import org.eclipse.collections.api.set.ImmutableSet import org.eclipse.collections.impl.factory.Lists import org.eclipse.collections.impl.factory.Sets import org.eclipse.collections.impl.map.mutable.ConcurrentHashMap import org.slf4j.LoggerFactory class DbDirectoryChangesetReader : FileSourceContext { private val convertDbObjectName: Function<String, String> private val packageMetadataReader: PackageMetadataReader private val packageMetadataCache = ConcurrentHashMap<FileObject, PackageMetadata>() private val tableChangeParser: DbChangeFileParser private val baselineTableChangeParser: DbChangeFileParser? private val rerunnableChangeParser: DbChangeFileParser private val deployMetricsCollector: DeployMetricsCollector constructor(convertDbObjectName: Function<String, String>, deployMetricsCollector: DeployMetricsCollector, backwardsCompatibleMode: Boolean, textMarkupDocumentReader: TextMarkupDocumentReader, baselineTableChangeParser: DbChangeFileParser?, getChangeType: GetChangeType) { this.packageMetadataReader = PackageMetadataReader(textMarkupDocumentReader) this.convertDbObjectName = convertDbObjectName this.tableChangeParser = TableChangeParser(OldWhitespaceAgnosticDbChangeHashStrategy(), backwardsCompatibleMode, deployMetricsCollector, textMarkupDocumentReader, getChangeType) this.baselineTableChangeParser = baselineTableChangeParser this.rerunnableChangeParser = RerunnableChangeParser(backwardsCompatibleMode, deployMetricsCollector, textMarkupDocumentReader) this.deployMetricsCollector = deployMetricsCollector } @VisibleForTesting constructor(convertDbObjectName: Function<String, String>, tableChangeParser: DbChangeFileParser, baselineTableChangeParser: DbChangeFileParser?, rerunnableChangeParser: DbChangeFileParser) { this.packageMetadataReader = PackageMetadataReader(TextMarkupDocumentReader(false)) this.convertDbObjectName = convertDbObjectName this.tableChangeParser = tableChangeParser this.baselineTableChangeParser = baselineTableChangeParser this.rerunnableChangeParser = rerunnableChangeParser this.deployMetricsCollector = DeployMetricsCollectorImpl() } /* * (non-Javadoc) * * @see com.gs.obevo.db.newdb.DbChangeReader#readChanges(java.io.File) */ override fun readChanges(fileSourceParams: FileSourceParams): ImmutableList<ChangeInput> { val allChanges = mutableListOf<ChangeInput>() val envSchemas = fileSourceParams.schemaNames.collect(this.convertDbObjectName) Validate.notEmpty(envSchemas.castToSet(), "Environment must have schemas populated") for (sourceDir in fileSourceParams.files) { LOG.info("Reading files from {}", sourceDir) for (schemaDir in sourceDir.findFiles(BasicFileSelector(and(vcsAware(), directory()), false))) { val schema = schemaDir.name.baseName if (envSchemas.contains(this.convertDbObjectName.valueOf(schema))) { val schemaChanges = fileSourceParams.changeTypes.flatMap { changeType -> val changeTypeDir = this.findDirectoryForChangeType(schemaDir, changeType, fileSourceParams.isLegacyDirectoryStructureEnabled) if (changeTypeDir != null) { if (changeType.isRerunnable) { findChanges(changeType, changeTypeDir, this.rerunnableChangeParser, TrueFileFilter.INSTANCE, schema, fileSourceParams.acceptedExtensions, fileSourceParams.defaultSourceEncoding) } else { findTableChanges(changeType, changeTypeDir, schema, fileSourceParams.isBaseline, fileSourceParams.acceptedExtensions, fileSourceParams.defaultSourceEncoding) } } else { emptyList<ChangeInput>() } } val tableChangeMap = schemaChanges .filter { Sets.immutable.of(ChangeType.TABLE_STR, ChangeType.FOREIGN_KEY_STR).contains(it.changeTypeName) } .groupBy(ChangeInput::getDbObjectKey) val staticDataChanges = schemaChanges.filter { it.changeTypeName.equals(ChangeType.STATICDATA_STR)} // now enrich the staticData objects w/ the information from the tables to facilitate the // deployment order calculation. staticDataChanges.forEach { staticDataChange -> val relatedTableChanges = tableChangeMap.get(staticDataChange.getDbObjectKey()) ?: emptyList() val foreignKeys = relatedTableChanges.filter { it.changeTypeName == ChangeType.FOREIGN_KEY_STR } val fkContent = foreignKeys.map { it.content }.joinToString("\n\n") staticDataChange.setContentForDependencyCalculation(fkContent) } allChanges.addAll(schemaChanges) } else { LOG.info("Skipping schema directory [{}] as it was not defined among the schemas in your system-config.xml file: {}", schema, envSchemas) continue } } } return Lists.immutable.ofAll(allChanges); } /** * We have this here to look for directories in the various places we had specified it in the code before (i.e. * for backwards-compatibility). */ private fun findDirectoryForChangeType(schemaDir: FileObject, changeType: ChangeType, legacyDirectoryStructureEnabled: Boolean): FileObject? { var dir = schemaDir.getChild(changeType.directoryName) if (dir != null && dir.exists()) { return dir } dir = schemaDir.getChild(changeType.directoryName.toUpperCase()) if (dir != null && dir.exists()) { return dir } if (legacyDirectoryStructureEnabled && changeType.directoryNameOld != null) { // for backwards-compatibility dir = schemaDir.getChild(changeType.directoryNameOld) if (dir != null && dir.exists()) { deployMetricsCollector.addMetric("oldDirectoryNameUsed", true) return dir } } return null } private fun findTableChanges(changeType: ChangeType, tableDir: FileObject, schema: String, useBaseline: Boolean, acceptedExtensions: ImmutableSet<String>, sourceEncoding: String): List<ChangeInput> { val baselineFilter = WildcardFileFilter("*.baseline.*") val nonBaselineFiles = findFiles(tableDir, if (this.isUsingChangesConvention(tableDir)) CHANGES_WILDCARD_FILTER else NotFileFilter(baselineFilter), acceptedExtensions) var nonBaselineChanges = parseChanges(changeType, nonBaselineFiles, this.tableChangeParser, schema, sourceEncoding) val nonBaselineChangeMap = nonBaselineChanges.groupBy { it.dbObjectKey } if (useBaseline) { LOG.info("Using the 'useBaseline' mode to read in the db changes") val baselineFiles = findFiles(tableDir, if (this.isUsingChangesConvention(tableDir)) CHANGES_WILDCARD_FILTER else baselineFilter, acceptedExtensions) if (baselineTableChangeParser == null) { throw IllegalArgumentException("Cannot invoke readChanges with useBaseline == true if baselineTableChangeParser hasn't been set; baseline reading may not be enabled in your Platform type") } val baselineChanges = parseChanges(changeType, baselineFiles, this.baselineTableChangeParser, schema, sourceEncoding) for (baselineChange in baselineChanges) { val regularChanges = nonBaselineChangeMap.get(baselineChange.dbObjectKey)!! if (regularChanges.isEmpty()) { throw IllegalArgumentException("Invalid state - expecting a change here for this object key: " + baselineChange.dbObjectKey) } val regularChange = regularChanges.get(0) this.copyDbObjectMetadataOverToBaseline(regularChange, baselineChange) } val baselineDbObjectKeys = baselineChanges.map { it.dbObjectKey }.toSet() LOG.info("Found the following baseline changes: will try to deploy via baseline for these db objects: " + baselineDbObjectKeys.joinToString(",")) nonBaselineChanges = nonBaselineChanges .filterNot { baselineDbObjectKeys.contains(it.dbObjectKey) } .plus(baselineChanges) } return nonBaselineChanges } /** * This is for stuff in the METADATA tag that would be in the changes file but not the baseline file */ private fun copyDbObjectMetadataOverToBaseline(regularChange: ChangeInput, baselineChange: ChangeInput) { baselineChange.setRestrictions(regularChange.getRestrictions()) baselineChange.permissionScheme = regularChange.permissionScheme } private fun findFiles(dir: FileObject, fileFilter: FileFilter, acceptedExtensions: ImmutableSet<String>): List<FileObject> { val positiveSelector = BasicFileSelector( and( fileFilter, not(directory()), not( or( WildcardFileFilter("package-info*"), WildcardFileFilter("*." + OnboardingStrategy.exceptionExtension) ) ) ), vcsAware() ) val candidateFiles = listOf(*dir.findFiles(positiveSelector)) val extensionPartition = candidateFiles.partition { acceptedExtensions.contains(it.name.extension.toLowerCase()) } if (extensionPartition.second.isNotEmpty()) { val message = "Found unexpected file extensions (these will not be deployed!) in directory " + dir + "; expects extensions [" + acceptedExtensions + "], found: " + extensionPartition.second LOG.warn(message) deployMetricsCollector.addListMetric(DeployMetrics.UNEXPECTED_FILE_EXTENSIONS, message) } return extensionPartition.first } private fun parseChanges(changeType: ChangeType, files: List<FileObject>, changeParser: DbChangeFileParser, schema: String, sourceEncoding: String): List<ChangeInput> { return files.flatMap { file -> val packageMetadata = getPackageMetadata(file, sourceEncoding) var encoding: String? = null var metadataSection: TextMarkupDocumentSection? = null if (packageMetadata != null) { encoding = packageMetadata.fileToEncodingMap.get(file.name.baseName) metadataSection = packageMetadata.metadataSection } val charsetStrategy = CharsetStrategyFactory.getCharsetStrategy(encoding ?: sourceEncoding) val objectName = file.name.baseName.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] try { LOG.debug("Attempting to read file {}", file) changeParser.value(changeType, file, file.getStringContent(charsetStrategy), objectName, schema, metadataSection).castToList() } catch (e: RuntimeException) { throw IllegalArgumentException("Error while parsing file " + file + " of change type " + changeType.name + "; please see the cause in the stack trace below: " + e.message, e) } } } private fun getPackageMetadata(file: FileObject, sourceEncoding: String): PackageMetadata? { return packageMetadataCache.getIfAbsentPut(file.parent, Function0<PackageMetadata> { val packageMetadataFile = file.parent!!.getChild("package-info.txt") // we check for containsKey, as we may end up persisting null as the value in the map if (packageMetadataFile == null || !packageMetadataFile.isReadable) { null } else { packageMetadataReader.getPackageMetadata(packageMetadataFile.getStringContent(CharsetStrategyFactory.getCharsetStrategy(sourceEncoding))) } }) } private fun findChanges(changeType: ChangeType, dir: FileObject, changeParser: DbChangeFileParser, fileFilter: FileFilter, schema: String, acceptedExtensions: ImmutableSet<String>, sourceEncoding: String): List<ChangeInput> { return parseChanges(changeType, findFiles(dir, fileFilter, acceptedExtensions), changeParser, schema, sourceEncoding) } /** * We have this check here for backwards-compatibility * Originally, we required the db files to end in .changes.*, but we now want to have the convention of the stard * file name being the * file that you edit, much like the other ones * * Originally, we wanted to regular name to be for the baseline, but given this is not yet implemented and won't * drive the changes, this was a wrong idea from the start. Eventually, we will have the baseline files in * .baseline.* */ private fun isUsingChangesConvention(dir: FileObject): Boolean { val files = dir.findFiles(BasicFileSelector(CHANGES_WILDCARD_FILTER, false)) val changesConventionUsed = files.size > 0 if (changesConventionUsed) { deployMetricsCollector.addMetric("changesConventionUsed", true) } return changesConventionUsed } companion object { private val LOG = LoggerFactory.getLogger(DbDirectoryChangesetReader::class.java) @VisibleForTesting @JvmStatic val CHANGES_WILDCARD_FILTER: FileFilter = WildcardFileFilter("*.changes.*") } }
apache-2.0
2a1704801d53ca3bb1b66b9ca7064791
51.063545
276
0.681634
5.481338
false
false
false
false
klassm/BezahlScanner
app/src/main/java/li/klass/bezahl/scanner/MainActivity.kt
1
5839
package li.klass.bezahl.scanner import android.app.AlertDialog import android.content.Intent import android.content.IntentSender import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Log import android.view.View import android.widget.ListView import com.google.android.gms.auth.api.Auth import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.drive.Drive import com.google.zxing.integration.android.IntentIntegrator import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.tasks.Task import com.google.android.gms.common.api.ApiException class MainActivity : AppCompatActivity(), GoogleApiClient.OnConnectionFailedListener { private var googleApiClient: GoogleApiClient? = null private var driveFileAccessor: DriveFileAccessor? = null private val qrCodeTextParser = QrCodeTextParser() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val scanButton = findViewById<FloatingActionButton>(R.id.scanAction) scanButton.setOnClickListener { IntentIntegrator(this@MainActivity).initiateScan() } (findViewById<View>(R.id.payments) as ListView).adapter = PaymentAdapter(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { val scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent) val msg: String if (scanResult != null && driveFileAccessor != null) { val payment = qrCodeTextParser.parse(scanResult.contents) msg = if (payment != null) { driveFileAccessor!!.addPayment(payment) updatePaymentsView() String.format(getString(R.string.payment_added_message), payment.name) } else { getString(R.string.could_not_find_payment_in_qr_code) } Snackbar.make(findViewById(android.R.id.content), msg, Snackbar.LENGTH_LONG) .setAction("Action", null).show() } else if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(intent) handleSignInResult(task) } } private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) { try { val account = completedTask.getResult(ApiException::class.java) Log.e(TAG, "sign in success with account " + account?.displayName) if (googleApiClient != null) { connect() } } catch (e: ApiException) { AlertDialog.Builder(this) .setTitle(R.string.google_login_failed_title) .setMessage(R.string.google_login_failed_text) .setCancelable(false) .setOnDismissListener { finish() } .show() Log.e(TAG, e.message, e) } } private fun connect() { Log.e(TAG, "sign in success") driveFileAccessor = DriveFileAccessor(googleApiClient!!) driveFileAccessor!!.start(object : DriveFileAccessor.InitDone { override fun onInitDone() = updatePaymentsView() }) } override fun onStart() { super.onStart() if (googleApiClient == null) { val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(Drive.SCOPE_FILE, Drive.SCOPE_APPFOLDER) .build() googleApiClient = GoogleApiClient.Builder(this) .enableAutoManage(this, 0, this) .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions) .addApi(Drive.API) .build() val signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient) startActivityForResult(signInIntent, RC_SIGN_IN) } else { googleApiClient!!.connect() } } override fun onStop() { if (googleApiClient != null && googleApiClient!!.isConnected) { googleApiClient!!.stopAutoManage(this) googleApiClient!!.disconnect() } super.onStop() } private fun updatePaymentsView() { ((findViewById<View>(R.id.payments) as ListView).adapter as PaymentAdapter).setData(driveFileAccessor!!.payments) } override fun onConnectionFailed(result: ConnectionResult) { Log.e(TAG, result.toString()) if (result.hasResolution()) { try { result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION) } catch (e: IntentSender.SendIntentException) { showError() } } else { GoogleApiAvailability.getInstance().getErrorDialog(this, result.errorCode, 0).show() } } private fun showError() { Snackbar.make(findViewById(android.R.id.content), R.string.google_drive_connection_failed, Snackbar.LENGTH_LONG) .setAction("Action", null).show() } companion object { private val REQUEST_CODE_RESOLUTION = 1 private val RC_SIGN_IN = 9001 private val TAG = MainActivity::class.java.name } }
gpl-2.0
9e8c944434cfd3db549f6937313e2497
37.414474
121
0.654222
4.69373
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/bungeecord/util/BungeeCordConstants.kt
1
614
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bungeecord.util object BungeeCordConstants { const val HANDLER_ANNOTATION = "net.md_5.bungee.event.EventHandler" const val EVENT_PRIORITY_CLASS = "net.md_5.bungee.event.EventPriority" const val LISTENER_CLASS = "net.md_5.bungee.api.plugin.Listener" const val CHAT_COLOR_CLASS = "net.md_5.bungee.api.ChatColor" const val EVENT_CLASS = "net.md_5.bungee.api.plugin.Event" const val PLUGIN = "net.md_5.bungee.api.plugin.Plugin" }
mit
348e78ece60c595927c90afaf3a6ee4a
28.238095
74
0.716612
3.283422
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/ty/Declarations.kt
2
11021
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.ty import com.intellij.extapi.psi.StubBasedPsiElementBase import com.intellij.openapi.util.Computable import com.intellij.psi.util.PsiTreeUtil import com.tang.intellij.lua.Constants import com.tang.intellij.lua.comment.LuaCommentUtil import com.tang.intellij.lua.comment.psi.LuaDocTagField import com.tang.intellij.lua.comment.psi.LuaDocTagReturn import com.tang.intellij.lua.ext.recursionGuard import com.tang.intellij.lua.psi.* import com.tang.intellij.lua.search.GuardType import com.tang.intellij.lua.search.SearchContext import com.tang.intellij.lua.stubs.LuaFuncBodyOwnerStub fun infer(element: LuaTypeGuessable?, context: SearchContext): ITy { if (element == null) return Ty.UNKNOWN return SearchContext.infer(element, context) } internal fun inferInner(element: LuaTypeGuessable, context: SearchContext): ITy { return when (element) { is LuaFuncBodyOwner -> element.infer(context) is LuaExpr -> inferExpr(element, context) is LuaParamNameDef -> element.infer(context) is LuaNameDef -> element.infer(context) is LuaDocTagField -> element.infer() is LuaTableField -> element.infer(context) is LuaPsiFile -> inferFile(element, context) else -> Ty.UNKNOWN } } fun inferReturnTy(owner: LuaFuncBodyOwner, searchContext: SearchContext): ITy { if (owner is StubBasedPsiElementBase<*>) { val stub = owner.stub if (stub is LuaFuncBodyOwnerStub<*>) { return stub.guessReturnTy(searchContext) } } return inferReturnTyInner(owner, searchContext) } private fun inferReturnTyInner(owner: LuaFuncBodyOwner, searchContext: SearchContext): ITy { if (owner is LuaCommentOwner) { val comment = LuaCommentUtil.findComment(owner) if (comment != null) { val returnDef = PsiTreeUtil.findChildOfType(comment, LuaDocTagReturn::class.java) if (returnDef != null) { //return returnDef.resolveTypeAt(searchContext.index) return returnDef.type } } } //infer from return stat return searchContext.withRecursionGuard(owner, GuardType.RecursionCall) { var type: ITy = Ty.VOID owner.acceptChildren(object : LuaRecursiveVisitor() { override fun visitReturnStat(o: LuaReturnStat) { val guessReturnType = guessReturnType(o, searchContext.index, searchContext) TyUnion.each(guessReturnType) { /** * 注意,不能排除anonymous * local function test() * local v = xxx() * v.yyy = zzz * return v * end * * local r = test() * * type of r is an anonymous ty */ type = type.union(it) } } override fun visitExprStat(o: LuaExprStat) {} override fun visitLabelStat(o: LuaLabelStat) {} override fun visitAssignStat(o: LuaAssignStat) {} override fun visitGotoStat(o: LuaGotoStat) {} override fun visitClassMethodDef(o: LuaClassMethodDef) {} override fun visitFuncDef(o: LuaFuncDef) {} override fun visitLocalDef(o: LuaLocalDef) {} override fun visitLocalFuncDef(o: LuaLocalFuncDef) {} }) type } } private fun LuaParamNameDef.infer(context: SearchContext): ITy { var type = resolveParamType(this, context) //anonymous if (Ty.isInvalid(type)) type = TyClass.createAnonymousType(this) return type } private fun LuaNameDef.infer(context: SearchContext): ITy { var type: ITy = Ty.UNKNOWN val parent = this.parent if (parent is LuaTableField) { val expr = PsiTreeUtil.findChildOfType(parent, LuaExpr::class.java) if (expr != null) type = infer(expr, context) } else { val docTy = this.docTy if (docTy != null) return docTy val localDef = PsiTreeUtil.getParentOfType(this, LuaLocalDef::class.java) if (localDef != null) { //计算 expr 返回类型 if (Ty.isInvalid(type) /*&& !context.forStub*/) { val nameList = localDef.nameList val exprList = localDef.exprList if (nameList != null && exprList != null) { type = context.withIndex(localDef.getIndexFor(this)) { exprList.guessTypeAt(context) } } } //anonymous if (type !is ITyPrimitive) type = type.union(TyClass.createAnonymousType(this)) else if (type == Ty.TABLE) type = type.union(TyClass.createAnonymousType(this)) } } return type } private fun LuaDocTagField.infer(): ITy { val stub = stub if (stub != null) return stub.type return ty?.getType() ?: Ty.UNKNOWN } private fun LuaFuncBodyOwner.infer(context: SearchContext): ITy { if (this is LuaFuncDef) return TyPsiFunction(false, this, TyFlags.GLOBAL) return if (this is LuaClassMethodDef) { TyPsiFunction(!this.isStatic, this, 0) } else TyPsiFunction(false, this, 0) } private fun LuaTableField.infer(context: SearchContext): ITy { val stub = stub //from comment val docTy = if (stub != null) stub.docTy else comment?.docTy if (docTy != null) return docTy //guess from value val valueExpr = valueExpr return if (valueExpr != null) infer(valueExpr, context) else Ty.UNKNOWN } private fun inferFile(file: LuaPsiFile, context: SearchContext): ITy { return recursionGuard(file, Computable { val moduleName = file.moduleName if (moduleName != null) TyLazyClass(moduleName) else { val stub = file.stub if (stub != null) { val statStub = stub.childrenStubs.lastOrNull { it.psi is LuaReturnStat } val stat = statStub?.psi if (stat is LuaReturnStat) guessReturnType(stat, 0, context) else null } else { val lastChild = file.lastChild var stat: LuaReturnStat? = null LuaPsiTreeUtil.walkTopLevelInFile(lastChild, LuaReturnStat::class.java) { stat = it false } if (stat != null) guessReturnType(stat, 0, context) else null } } }) ?: Ty.UNKNOWN } /** * 找参数的类型 * @param paramNameDef param name * * * @param context SearchContext * * * @return LuaType */ private fun resolveParamType(paramNameDef: LuaParamNameDef, context: SearchContext): ITy { val paramName = paramNameDef.name val paramOwner = PsiTreeUtil.getParentOfType(paramNameDef, LuaParametersOwner::class.java) val stub = paramNameDef.stub val docTy:ITy? = if (stub != null) { stub.docTy } else { // from comment val commentOwner = PsiTreeUtil.getParentOfType(paramNameDef, LuaCommentOwner::class.java) if (commentOwner != null) { val docTy = commentOwner.comment?.getParamDef(paramName)?.type if (docTy != null) return docTy } null } if (docTy != null) return docTy // 如果是个类方法,则有可能在父类里 if (paramOwner is LuaClassMethodDef) { val classType = paramOwner.guessClassType(context) val methodName = paramOwner.name var set: ITy = Ty.UNKNOWN if (classType != null && methodName != null) { TyClass.processSuperClass(classType, context) { superType -> val superMethod = superType.findMember(methodName, context) if (superMethod is LuaClassMethod) { val params = superMethod.params//todo : 优化 for (param in params) { if (paramName == param.name) { set = param.ty if (set != Ty.UNKNOWN) return@processSuperClass false } } } true } } if (set !is TyUnknown) return set } // module fun // function method(self) end if (paramOwner is LuaFuncDef && paramName == Constants.WORD_SELF) { val moduleName = paramNameDef.moduleName if (moduleName != null) { return TyLazyClass(moduleName) } } //for if (paramOwner is LuaForBStat) { val exprList = paramOwner.exprList val callExpr = PsiTreeUtil.findChildOfType(exprList, LuaCallExpr::class.java) val paramIndex = paramOwner.getIndexFor(paramNameDef) // iterator support val type = callExpr?.guessType(context) if (type != null) { var result: ITy = Ty.UNKNOWN TyUnion.each(type) { if (it is ITyFunction) { val returnTy = it.mainSignature.returnTy if (returnTy is TyTuple) { result = result.union(returnTy.list.getOrElse(paramIndex) { Ty.UNKNOWN }) } else if (paramIndex == 0) { result = result.union(returnTy) } } } if (result != Ty.UNKNOWN) return result } } // for param = 1, 2 do end if (paramOwner is LuaForAStat) return Ty.NUMBER /** * ---@param processor fun(p1:TYPE):void * local function test(processor) * end * * test(function(p1) end) * * guess type for p1 */ if (paramOwner is LuaClosureExpr) { var ret: ITy = Ty.UNKNOWN val shouldBe = paramOwner.shouldBe(context) shouldBe.each { if (it is ITyFunction) { val paramIndex = paramOwner.getIndexFor(paramNameDef) ret = ret.union(it.mainSignature.getParamTy(paramIndex)) } } return ret } return Ty.UNKNOWN }
apache-2.0
6f294790e6eef8689793b9343f210c9c
33.642405
97
0.584452
4.469988
false
false
false
false
daniloqueiroz/nsync
src/main/kotlin/commons/AsyncBus.kt
1
3816
package commons import kotlinx.coroutines.experimental.* import kotlinx.coroutines.experimental.channels.Channel import kotlinx.coroutines.experimental.channels.consumeEach import mu.KLogging import nsync.* import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import kotlin.reflect.KClass class AsyncConnection<F, G : Signal<F>>( private val bus: SignalBus, outK: KClass<G> ) : Connection<F, G> { private val id: UUID private val chn = Channel<Signal<*>>() init { id = bus.register(this, listOf(outK)) } suspend override fun handle(msg: Signal<*>) { this.chn.send(msg) } suspend override fun send(msg: Signal<*>) = bus.publish(msg) suspend override fun receive(timeout: Long): G = runBlocking { try { withTimeout(timeout, TimeUnit.MILLISECONDS, { chn.receive() as G }) } catch (err: Exception) { throw NoResponseException(err) } } override fun close() { this.bus.deregister(this.id) this.chn.close() } } class AsyncBus : SignalBus { private companion object : KLogging() private lateinit var loop: Job private val subscribers: MutableMap<KClass<*>, MutableList<UUID>> = mutableMapOf() private val keys: MutableMap<UUID, Consumer> = mutableMapOf() private val chn = Channel<Signal<*>>(Channel.UNLIMITED) private val size = AtomicInteger(0) init { this.loop = launch(CommonPool) { logger.info { "Starting SignalBus service" } chn.consumeEach { val event = it val evtType = event::class subscribers.getOrDefault(evtType, mutableListOf()).forEach { dispatch(evtType, it, event) } when (event) { is Stop -> { logger.info { "Stopping SignalBus service" } loop.cancel() chn.close() } } yield() } } } override suspend fun join() { this.loop?.join() } override fun <E, T : Signal<E>> connect(eventKlass: KClass<T>): Connection<E, T> { return AsyncConnection(this, eventKlass) } override fun register(consumer: Consumer, evtTypes: List<KClass<*>>): UUID { val key = UUID.randomUUID() for (type in evtTypes) { logger.info { "Registering consumer ${consumer::class.java.simpleName} to ${type.java.simpleName}" } val existent = subscribers.getOrDefault(type, mutableListOf()) existent.add(key) subscribers[type] = existent keys[key] = consumer } return key } override fun deregister(key: UUID) { val consumer = this.keys.remove(key) consumer?.let { logger.info { "Deregistering consumer ${it::class.java.simpleName}" } subscribers.values.forEach { it.remove(key) } } } override suspend fun <E, T : Signal<E>> publish(msg: T) { logger.debug { "Publishing $msg" } size.incrementAndGet() chn.send(msg) } private suspend fun dispatch(evtType: KClass<out Signal<*>>, consumerId: UUID, msg: Signal<*>) { keys[consumerId]?.let { try { logger.debug { "Dispatching ${evtType.java.simpleName} msg to ${it::class.java.simpleName}" } logger.debug { "Bus pending message: ${size.getAndDecrement()}" } it.handle(msg) } catch (err: Exception) { logger.error(err) { "Error dispatching msg to $it" } } } } }
gpl-3.0
123d150f8e295e75f226314239ae7d8b
29.528
112
0.5663
4.452742
false
false
false
false
echsylon/atlantis
library/lib/src/main/kotlin/com/echsylon/atlantis/Server.kt
1
17082
package com.echsylon.atlantis import com.echsylon.atlantis.extension.closeSilently import com.echsylon.atlantis.request.Request import com.echsylon.atlantis.response.Response import java.io.ByteArrayInputStream import kotlin.text.split import java.io.IOException import java.io.InputStream import java.net.InetAddress import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket import javax.net.ServerSocketFactory import kotlin.IllegalArgumentException import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.buffer import okio.sink import okio.source import java.net.SocketException import java.security.KeyManagementException import java.security.KeyStore import java.security.KeyStoreException import java.security.NoSuchAlgorithmException import java.security.SecureRandom import java.security.UnrecoverableKeyException import java.security.cert.CertificateException import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import javax.net.ssl.KeyManagerFactory import javax.net.ssl.SSLContext import javax.net.ssl.SSLServerSocket import javax.net.ssl.TrustManagerFactory /** * Represents the remote server and acts as the heart of Atlantis. It listens * for client HTTP requests and serves corresponding mock responses as defined * in the current configuration. The default configuration for this server will * serve "404 Not found" on all requests that won't match a configured pattern. */ internal class Server { companion object { internal val NOT_FOUND = Response(404) } private var server: ServerSocket? = null private var config: Configuration = Configuration() private var executor: ExecutorService = Executors.newCachedThreadPool { Thread(it, "Atlantis Mock Server").apply { isDaemon = true } } /** * The current request pattern configuration. */ var configuration: Configuration get() = config set(value) { config = value } /** * Whether the mock server is currently active or not. */ val isRunning: Boolean get() = server != null && server?.isClosed == false /** * Start listening for requests and serving mock responses for them. * * The trust store is passed as-is, directly to the JVM trust store * implementation. It is expected to be provided as a single keystore * containing one X509 certificate and one PKCS12 secret key. * * @param port The port to serve mock data on. * @param trust The trust store byte array. * @param password The trust store password, or null. * @throws RuntimeException if anything goes wrong. * @return True if the server was successfully started, else false. */ fun start(port: Int, trust: ByteArray? = null, password: String? = null) { if (isRunning) return server = runCatching { createServerSocket(port, trust, password) } .onFailure { stop() } .getOrThrow() executor.execute { do { server ?.runCatching { serveConnection(accept()) } ?.onFailure { stop() } } while (isRunning) } } /** * Stops serving mock responses. * * @return True if the server was successfully stopped, else false. */ fun stop() { executor.shutdown() server?.closeSilently() server = null } /** * Tries to create a suitable server socket based on the given parameters. * * @param port The port to serve mock data on. * @param trust The trust store byte array. * @param password The trust store password, or null. * @return A default [ServerSocket] if no trust input stream is given. An * [SSLServerSocket] otherwise. */ private fun createServerSocket(port: Int, trust: ByteArray?, password: String?): ServerSocket { return when (trust) { null -> createDefaultServerSocket(port) else -> createSecureServerSocket(port, trust, password) } } /** * Creates a new server socket and tries to bind it to the given port. * * @param port The port to serve mock data on. * @throws RuntimeException if anything goes wrong. * @return The bound server socket. */ private fun createDefaultServerSocket(port: Int): ServerSocket { try { // Passing in a null pointer InetAddress will force the ServerSocket // to assume the "wildcard" address (ultimately "localhost") as host, // with the additional benefit of not attempting to resolve it on the // network. val inetAddress: InetAddress? = null val inetSocketAddress = InetSocketAddress(inetAddress, port) return ServerSocketFactory.getDefault() .createServerSocket() .apply { reuseAddress = inetSocketAddress.port != 0 } .apply { bind(inetSocketAddress) } } catch (cause: SocketException) { throw RuntimeException("Could not determine address reuse strategy", cause) } catch (cause: IOException) { throw RuntimeException("Unexpected connection error", cause) } catch (cause: SecurityException) { throw RuntimeException("Not allowed to connect to port $port", cause) } catch (cause: IllegalArgumentException) { throw RuntimeException("Could not connect to port $port", cause) } } /** * Creates a new server socket and tries to bind it to the given address * and port. * * @param port The port to serve mock data on. * @param trust The trust store byte array. * @param password The trust store password, or null. * @throws RuntimeException if anything goes wrong. * @return The bound server socket. */ private fun createSecureServerSocket(port: Int, trust: ByteArray, password: String?): SSLServerSocket { try { // Passing in a null pointer InetAddress will force the ServerSocket // to assume the "wildcard" address (ultimately "localhost") as host, // with the additional benefit of not attempting to resolve it on the // network. val inetAddress: InetAddress? = null val inetSocketAddress = InetSocketAddress(inetAddress, port) val secureContext = createSecureContext(trust, password) return secureContext.serverSocketFactory .createServerSocket() .let { it as SSLServerSocket } .apply { reuseAddress = inetSocketAddress.port != 0 } .apply { bind(inetSocketAddress) } } catch (cause: SocketException) { throw RuntimeException("Could not determine address reuse strategy", cause) } catch (cause: IOException) { throw RuntimeException("Unexpected connection error", cause) } catch (cause: SecurityException) { throw RuntimeException("Not allowed to connect to port $port", cause) } catch (cause: IllegalArgumentException) { throw RuntimeException("Could not connect to port $port", cause) } } /** * Creates an instance of SSLContext with custom key and trust managers. * * @param trust The trust store byte array. * @param password The trust store password, or null. * @throws RuntimeException if anything goes wrong. * @return The prepared SSL context. */ private fun createSecureContext(trust: ByteArray, password: String?): SSLContext { try { val trustFactory = createTrustFactory(trust, password) val keyFactory = createKeyFactory(trust, password) val context = SSLContext.getInstance("TLS") context.init(keyFactory.keyManagers, trustFactory.trustManagers, SecureRandom.getInstanceStrong()) return context } catch (cause: NoSuchAlgorithmException) { throw RuntimeException("Could not create secure context", cause) } catch (cause: KeyManagementException) { throw RuntimeException("Could not initialize secure context", cause) } } /** * Creates a custom trust factory. * * @param trust The trust store byte array. * @param password The corresponding password. * @throws RuntimeException if anything goes wrong. * @return The trust factory that will provide the given certificate data. */ private fun createTrustFactory(trust: ByteArray, password: String?): TrustManagerFactory { try { val trustFactory = TrustManagerFactory.getInstance("PKIX") val keyStore = KeyStore.getInstance("PKCS12") val input = ByteArrayInputStream(trust) val pwd = password?.toCharArray() ?: charArrayOf() keyStore.load(input, pwd) trustFactory.init(keyStore) return trustFactory } catch (cause: NoSuchAlgorithmException) { throw RuntimeException("Could not initialize trust factory", cause) } catch (cause: KeyStoreException) { throw RuntimeException("Could not initialize trust factory", cause) } catch (cause: CertificateException) { throw RuntimeException("Could not load certificate", cause) } catch (cause: IOException) { throw RuntimeException("Could not load certificate", cause) } } /** * Creates a custom key factory. * * @param key The secret key store byte array. * @param password The trust store password, or null. * @throws RuntimeException if anything goes wrong. * @return The key factory that will provide the given secret key data. */ private fun createKeyFactory(key: ByteArray, password: String?): KeyManagerFactory { try { val keyFactory = KeyManagerFactory.getInstance("PKIX") val keyStore = KeyStore.getInstance("PKCS12") val input = ByteArrayInputStream(key) val pwd = password?.toCharArray() ?: charArrayOf() keyStore.load(input, pwd) keyFactory.init(keyStore, pwd) return keyFactory } catch (cause: NoSuchAlgorithmException) { throw RuntimeException("Could not initialize trust factory", cause) } catch (cause: KeyStoreException) { throw RuntimeException("Could not initialize trust factory", cause) } catch (cause: UnrecoverableKeyException) { throw RuntimeException("Could not initialize trust factory", cause) } catch (cause: CertificateException) { throw RuntimeException("Could not load certificate", cause) } catch (cause: IOException) { throw RuntimeException("Could not load certificate", cause) } } /** * Waits for a client to request a connection to the server socket and * serves a mocked response for any read requests. * * @param socket The socket to wait for clients on. * * @throws RuntimeException if anything goes wrong. */ private fun serveConnection(socket: Socket) { executor.execute { lateinit var target: BufferedSink lateinit var source: BufferedSource runCatching { target = socket.sink().buffer() source = socket.source().buffer() val request = readRequestSignature(source) request.headers.addAll(readRequestHeaders(source)) request.content = readRequestContent(request, source) println("Atlantis Request:\n\t$request") val response = config.findResponse(request) ?: NOT_FOUND if (response.behavior.calculateLength) ensureContentLength(response) println("Atlantis Response:\n\t$response") writeResponseSignature(response, target) writeResponseHeaders(response, target) writeResponseContent(response, target) }.onFailure { it.printStackTrace() }.also { socket.closeSilently() } } } /** * Reads the signature line from the request stream. * * Example: * "GET /path/to/resource HTTP/1.1" * * @param input The data source stream to read from. * @return The request object with the bare minimum signature. * * @throws IOException if the source can't be read. * @throws IllegalArgumentException if the source is empty. */ private fun readRequestSignature(input: BufferedSource): Request { val signature = input.readUtf8LineStrict() if (signature.isEmpty()) throw IllegalArgumentException("Empty request") val (method, path, protocol) = signature.split(" ".toRegex(), 3) return Request(method, path, protocol) } /** * Reads the headers from the request stream. * * Example: * Authorization: Bearer AF79E12_34 * Content-Length: 12 * * @param input The data source stream to read from. * @return The exhausted request headers. * * @throws IOException if the source can't be read. */ private fun readRequestHeaders(input: BufferedSource): List<String> { val headers = mutableListOf<String>() var line = input.readUtf8LineStrict() while (line.isNotBlank()) { headers.add(line) line = input.readUtf8LineStrict() } return headers } /** * Reads the request body from the request stream. * * @param request The request meta data. Used to determine content length or chunk size. * @param input The data source stream to read from. * @return A byte buffer containing the exhausted request body. * * @throws IOException if the source can't be read. */ private fun readRequestContent(request: Request, input: BufferedSource): ByteArray { return when { request.headers.expectSolidContent -> input.readByteArray() request.headers.expectChunkedContent -> { val buffer = Buffer() var chunkSize = input.readUtf8LineStrict().toLong(16) while (chunkSize != 0L) { buffer.writeUtf8(chunkSize.toString()).writeUtf8("\r\n") input.read(buffer, chunkSize) chunkSize = input.readUtf8LineStrict().toLong(16) } buffer.readByteArray() } else -> byteArrayOf() } } /** * Ensures that there is a Content-Length header when there should be one. * Exception is made for chunked content, where no header will be added. * Furthermore an already existing header will NOT be overwritten. * * @param response The response holding the headers to validate */ private fun ensureContentLength(response: Response) { if (!response.headers.expectSolidContent && !response.headers.expectChunkedContent) { response.headers.add("Content-Length: ${response.content.size}") } } /** * Writes the response signature line to the response stream. * * @param response The mocked response to deduct the signature from. * @param output The target stream to write data to. * * @throws IOException if the target can't be written. */ private fun writeResponseSignature(response: Response, output: BufferedSink) { val signature = "${response.protocol} ${response.code} ${response.phrase}" .replace("\\r".toRegex(), " ") .replace("\\n".toRegex(), " ") .replace("\\s+".toRegex(), " ") .trim() output.writeUtf8("$signature\r\n") } /** * Writes the response headers to the response stream. * * @param response The mocked response containing the headers. * @param output The target stream to write to. * * @throws IOException if the target can't be written. */ private fun writeResponseHeaders(response: Response, output: BufferedSink) { response.headers .joinToString(separator = "\r\n", postfix = "\r\n") { it.trim() } .also { output.writeUtf8(it) } } /** * Writes the response body to the response stream. * * @param response The mocked response to draw the body from. * @param output The target stream to write to. * * @throws IOException if the target can't be written. */ private fun writeResponseContent(response: Response, output: BufferedSink) { var bytes = response.body if (bytes != null) output.writeUtf8("\r\n") while (bytes != null) { output.write(bytes) bytes = response.body } output.flush() } }
apache-2.0
77bc93e969b06a4d9223fc0e448e4167
38.271264
110
0.637045
5.003515
false
false
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/common/path/TrieNode.kt
1
9356
package org.mitallast.queue.common.path import io.vavr.collection.HashMap import io.vavr.collection.Map import io.vavr.control.Option import org.mitallast.queue.common.strings.QueryStringDecoder import org.mitallast.queue.common.strings.Strings import java.util.* abstract class TrieNode<T, N : TrieNode<T, N>> { companion object { fun <T> node(): RootTrieNode<T> = RootTrieNode() fun <T> wildcard(token: String): WildcardTrieNode<T> = WildcardTrieNode(token) fun <T> token(token: String): TokenTrieNode<T> = TokenTrieNode(token) fun isNamedWildcard(key: String): Boolean { return key.length > 2 && key[0] == '{' && key[key.length - 1] == '}' } } protected val value: Option<T> protected val key: String protected val wildcard: Array<WildcardTrieNode<T>> protected val children: Array<TokenTrieNode<T>> constructor(key: String) { this.key = key this.value = Option.none() this.wildcard = emptyArray() this.children = emptyArray() } constructor(key: String, value: Option<T>, wildcard: Array<WildcardTrieNode<T>>, children: Array<TokenTrieNode<T>>) { this.key = key this.value = value this.wildcard = wildcard this.children = children } abstract fun isToken(token: String): Boolean abstract fun withValue(value: T): N abstract fun withWildcard(wildcard: Array<WildcardTrieNode<T>>): N abstract fun withChildren(children: Array<TokenTrieNode<T>>): N fun insert(path: String, value: T): N { val parts = Strings.splitStringToArray(path, '/') if (parts.isEmpty()) { return withValue(value) } return insert(parts, 0, value) } protected fun insert(path: Array<String>, index: Int, value: T): N { if (index > path.size) { throw ArrayIndexOutOfBoundsException(index) } else if (index == path.size) { return withValue(value) } else { val token = path[index] if (TrieNode.isNamedWildcard(token)) { for ((i, child) in wildcard.withIndex()) { if (child.isToken(token)) { val w = Arrays.copyOf(wildcard, wildcard.size) w[i] = child.insert(path, index + 1, value) return withWildcard(w) } } val w = Arrays.copyOf(wildcard, wildcard.size + 1) w[wildcard.size] = TrieNode.wildcard<T>(token).insert(path, index + 1, value) return withWildcard(w) } else { for ((i, child) in children.withIndex()) { if (child.isToken(token)) { val c = Arrays.copyOf(children, children.size) c[i] = child.insert(path, index + 1, value) return withChildren(c) } } val c = Arrays.copyOf(children, children.size + 1) c[children.size] = TrieNode.token<T>(token).insert(path, index + 1, value) return withChildren(c) } } } fun retrieve(path: String): Pair<Option<T>, Map<String, String>> { if (path.isEmpty() || path.length == 1 && path[0] == '/') { return Pair(value, HashMap.empty()) } var index = 0 if (path[0] == '/') { index = 1 } return retrieve(path, index) } protected fun retrieve(path: String, start: Int): Pair<Option<T>, Map<String, String>> { var len = path.length if (start >= len) { return Pair(Option.none(), HashMap.empty()) } var end = path.indexOf('/', start) val isEnd = end == -1 if (end == len - 1) { // ends with len -= 1 end = len } else if (isEnd) { end = len } for (child in children) { if (isEnd && child.value.isEmpty) { continue } if (!isEnd && child.children.isEmpty() && child.wildcard.isEmpty()) { continue } if (child.keyEquals(path, start, end)) { return if (isEnd) { Pair(child.value, HashMap.empty()) } else { val res = child.retrieve(path, end + 1) if (res.first.isDefined) { res } else { break } } } } for (child in wildcard) { if (isEnd && child.value.isDefined) { val params = child.params(path, start, end) return Pair(child.value, params) } val (res, p) = child.retrieve(path, end + 1) if (res.isDefined) { val params = child.params(path, start, end).merge(p) return Pair(res, params) } } return Pair(Option.none(), HashMap.empty()) } fun prettyPrint() = prettyPrint(0, "", true) protected fun prettyPrint(level: Int, prefix: String, last: Boolean) { print(prefix) if (level > 0) { if (last) { print("└── ") } else { print("├── ") } } println("$key [$value]") val lastNode: TrieNode<*, *>? = when { wildcard.isNotEmpty() -> wildcard.last() children.isNotEmpty() -> children.last() else -> null } val childPrefix = if (level > 0) prefix + if (last) " " else "├── " else prefix for (child in children) { child.prettyPrint(level + 1, childPrefix, lastNode === child) } for (child in wildcard) { child.prettyPrint(level + 1, childPrefix, lastNode === child) } if (level == 0) { println() } } } class WildcardTrieNode<T> : TrieNode<T, WildcardTrieNode<T>> { private val token: String private val tokenWildcard: String constructor(token: String) : super(token) { this.token = token this.tokenWildcard = token.substring(1, token.length - 1) } constructor( token: String, value: Option<T>, wildcard: Array<WildcardTrieNode<T>>, children: Array<TokenTrieNode<T>>) : super(token, value, wildcard, children) { this.token = token this.tokenWildcard = token.substring(1, token.length - 1) } override fun isToken(token: String): Boolean { return this.token == token } override fun withValue(value: T): WildcardTrieNode<T> { return WildcardTrieNode(token, Option.some(value), wildcard, children) } override fun withWildcard(wildcard: Array<WildcardTrieNode<T>>): WildcardTrieNode<T> { return WildcardTrieNode(token, value, wildcard, children) } override fun withChildren(children: Array<TokenTrieNode<T>>): WildcardTrieNode<T> { return WildcardTrieNode(token, value, wildcard, children) } fun params(value: String, start: Int, end: Int): Map<String, String> { val decoded = QueryStringDecoder.decodeComponent(value.subSequence(start, end)) return HashMap.of(tokenWildcard, decoded) } } class TokenTrieNode<T> : TrieNode<T, TokenTrieNode<T>> { private val token: String constructor(token: String) : super(token) { this.token = token } constructor( token: String, value: Option<T>, wildcard: Array<WildcardTrieNode<T>>, children: Array<TokenTrieNode<T>>) : super(token, value, wildcard, children) { this.token = token } override fun isToken(token: String): Boolean { return this.token == token } override fun withValue(value: T): TokenTrieNode<T> { return TokenTrieNode(token, Option.some(value), wildcard, children) } override fun withWildcard(wildcard: Array<WildcardTrieNode<T>>): TokenTrieNode<T> { return TokenTrieNode(token, value, wildcard, children) } override fun withChildren(children: Array<TokenTrieNode<T>>): TokenTrieNode<T> { return TokenTrieNode(token, value, wildcard, children) } fun keyEquals(sequence: String, start: Int, end: Int): Boolean { return end - start == token.length && token.regionMatches(0, sequence, start, token.length) } } class RootTrieNode<T> : TrieNode<T, RootTrieNode<T>> { constructor() : super("/") constructor( value: Option<T>, wildcard: Array<WildcardTrieNode<T>>, children: Array<TokenTrieNode<T>>) : super("/", value, wildcard, children) override fun isToken(token: String): Boolean { return "/" == token } override fun withValue(value: T): RootTrieNode<T> { return RootTrieNode(Option.some(value), wildcard, children) } override fun withWildcard(wildcard: Array<WildcardTrieNode<T>>): RootTrieNode<T> { return RootTrieNode(value, wildcard, children) } override fun withChildren(children: Array<TokenTrieNode<T>>): RootTrieNode<T> { return RootTrieNode(value, wildcard, children) } }
mit
f4bdae5c217095ed0284e94053c5380d
32.714801
121
0.557186
4.165031
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/view/dialogs/ValuePickerDialog.kt
1
2139
package de.westnordost.streetcomplete.view.dialogs import android.content.Context import android.content.DialogInterface import androidx.appcompat.app.AlertDialog import android.view.LayoutInflater import android.view.ViewGroup import android.widget.EditText import android.widget.NumberPicker import androidx.annotation.LayoutRes import androidx.core.view.children import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.ktx.spToPx /** A dialog in which you can select one value from a range of values */ class ValuePickerDialog<T>( context: Context, private val values: List<T>, selectedValue: T? = null, title: CharSequence? = null, @LayoutRes layoutResId: Int = R.layout.dialog_number_picker, private val callback: (value: T) -> Unit ) : AlertDialog(context, R.style.Theme_Bubble_Dialog) { init { val view = LayoutInflater.from(context).inflate(layoutResId, null) setView(view) setTitle(title) val numberPicker = view.findViewById<NumberPicker>(R.id.numberPicker) setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok)) { _, _ -> callback(values[numberPicker.value]) dismiss() } setButton(BUTTON_NEGATIVE, context.getString(android.R.string.cancel)) { _, _ -> cancel() } numberPicker.wrapSelectorWheel = false numberPicker.displayedValues = values.map { it.toString() }.toTypedArray() numberPicker.minValue = 0 numberPicker.maxValue = values.size - 1 if (android.os.Build.VERSION.SDK_INT >= 29) { numberPicker.textSize = 32f.spToPx(context) } selectedValue?.let { numberPicker.value = values.indexOf(it) } // do not allow keyboard input numberPicker.disableEditTextsFocus() } private fun ViewGroup.disableEditTextsFocus() { for (child in children) { if (child is ViewGroup) { child.disableEditTextsFocus() } else if (child is EditText) { child.isFocusable = false } } } }
gpl-3.0
18948a0753ad4c3009acaf5defe65e33
34.065574
100
0.671342
4.446985
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/highlighter/xml/XmlTagTreeHighlightingUtil.kt
1
3359
/* * Copyright (C) 2020 Reece H. Dunn * Copyright 2000-2020 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 uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter.xml import com.intellij.application.options.editor.WebEditorOptions import com.intellij.codeInsight.daemon.impl.tagTreeHighlighting.XmlTagTreeHighlightingColors import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.ui.UIUtil.makeTransparent import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirElemConstructor import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule import java.awt.Color import kotlin.math.min // NOTE: The IntelliJ XmlTagTreeHighlightingUtil helper methods are package private. fun isTagTreeHighlightingActive(file: PsiFile?): Boolean = when { ApplicationManager.getApplication().isUnitTestMode -> false file !is XQueryModule -> false else -> WebEditorOptions.getInstance().isTagTreeHighlightingEnabled } fun getBaseColors(): Array<Color?> { val colorKeys = XmlTagTreeHighlightingColors.getColorKeys() val colorsScheme = EditorColorsManager.getInstance().globalScheme return Array(colorKeys.size) { colorsScheme.getColor(colorKeys[it]) } } fun containsTagsWithSameName(elements: Array<out PsiElement?>): Boolean { val names: MutableSet<String> = HashSet() return elements.asSequence().filterIsInstance<XQueryDirElemConstructor>().any { element -> val name = (element as XdmElementNode).nodeName?.let { qname_presentation(it) } name != null && !names.add(name) } } // NOTE: The IntelliJ XmlTagTreeHighlightingPass helper methods are package private. fun toLineMarkerColor(gray: Int, color: Color?): Color? { return if (color == null) null else Color( toLineMarkerColor(gray, color.red), toLineMarkerColor(gray, color.green), toLineMarkerColor(gray, color.blue) ) } private fun toLineMarkerColor(gray: Int, color: Int): Int { val value = (gray * 0.6 + 0.32 * color).toInt() return if (value < 0) 0 else min(value, 255) } fun toColorsForEditor(baseColors: Array<Color?>, tagBackground: Color): Array<Color?> { val transparency = WebEditorOptions.getInstance().tagTreeHighlightingOpacity * 0.01 return Array(baseColors.size) { val color = baseColors[it] if (color != null) makeTransparent(color, tagBackground, transparency) else null } } fun toColorsForLineMarkers(baseColors: Array<Color?>): Array<Color?> { return Array(baseColors.size) { toLineMarkerColor(239, baseColors[it]) } }
apache-2.0
834a7ba2bc7380424fecd616af16d0e4
40.9875
94
0.75975
4.111383
false
false
false
false
huy-vuong/streamr
app/src/main/java/com/huyvuong/streamr/ui/component/ThumbnailComponent.kt
1
1381
package com.huyvuong.streamr.ui.component import android.util.DisplayMetrics import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.huyvuong.streamr.ui.adapter.recyclerview.ThumbnailViewHolder import org.jetbrains.anko.AnkoComponent import org.jetbrains.anko.AnkoContext import org.jetbrains.anko.dip import org.jetbrains.anko.frameLayout import org.jetbrains.anko.imageView import org.jetbrains.anko.matchParent import org.jetbrains.anko.windowManager import kotlin.properties.Delegates class ThumbnailComponent : AnkoComponent<ViewGroup> { override fun createView(ui: AnkoContext<ViewGroup>): View { var thumbnailImageView: ImageView by Delegates.notNull() val thumbnailView = with(ui) { frameLayout { val displayMetrics = DisplayMetrics() context.windowManager.defaultDisplay.getMetrics(displayMetrics) val width = displayMetrics.widthPixels lparams(width = matchParent, height = (width / 3)) { marginStart = dip(2) marginEnd = dip(2) } thumbnailImageView = imageView().lparams(width = matchParent, height = matchParent) } } thumbnailView.tag = ThumbnailViewHolder(thumbnailView, thumbnailImageView) return thumbnailView } }
gpl-3.0
2f3aac8f2c43302550df9b04923400ff
37.388889
99
0.703838
5.152985
false
false
false
false
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/login/SignInActivity.kt
1
5209
package com.marknkamau.justjava.ui.login import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.EditText import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.common.api.ApiException import com.marknjunge.core.data.model.Resource import com.marknkamau.justjava.R import com.marknkamau.justjava.databinding.ActivitySignInBinding import com.marknkamau.justjava.ui.base.BaseActivity import com.marknkamau.justjava.ui.signup.SignUpActivity import com.marknkamau.justjava.utils.* import dagger.hilt.android.AndroidEntryPoint import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class SignInActivity : BaseActivity() { companion object { private const val RC_SIGN_IN = 99 } @Inject lateinit var googleSignInClient: GoogleSignInClient private val signInViewModel: SignInViewModel by viewModels() private lateinit var binding: ActivitySignInBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignInBinding.inflate(layoutInflater) setContentView(binding.root) initializeLoading() binding.tilEmail.resetErrorOnChange(binding.etEmail) binding.tilPassword.resetErrorOnChange(binding.etPassword) binding.tvForgotPassword.setOnClickListener { showForgotPasswordDialog() } binding.btnSignInGoogle.setOnClickListener { startActivityForResult(googleSignInClient.signInIntent, RC_SIGN_IN) hideKeyboard() } binding.llSignUp.setOnClickListener { startActivity(Intent(this, SignUpActivity::class.java)) finish() } binding.btnSignIn.setOnClickListener { if (isValid()) { hideKeyboard() signIn() } } } private fun initializeLoading() { signInViewModel.loading.observe(this, { loading -> binding.pbLoading.visibility = if (loading) View.VISIBLE else View.GONE }) } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { task.getResult(ApiException::class.java)?.idToken?.let { token -> signInWithGoogle(token) } } catch (e: ApiException) { Timber.e("signInResult:failed code=${e.statusCode}") toast("Sign in with Google failed. Use password instead.") } } } private fun showForgotPasswordDialog() { val dialog = AlertDialog.Builder(this) dialog.setTitle("Reset password") val view = LayoutInflater.from(this).inflate(R.layout.dialog_reset_password, findViewById(android.R.id.content), false) val input: EditText = view.findViewById(R.id.etEmailAddress) dialog.setView(view) dialog.setPositiveButton("Reset") { _, _ -> Timber.d(input.text.toString()) val email = input.text.toString().trim() if (email.isNotEmpty()) { requestPasswordReset(email) } } dialog.setNegativeButton("Cancel") { d, _ -> d.cancel() } dialog.show() } private fun requestPasswordReset(email: String) { signInViewModel.requestPasswordReset(email).observe(this, { resource -> when (resource) { is Resource.Success -> toast("A password reset email has been sent") is Resource.Failure -> handleApiError(resource) } }) } private fun signIn() { signInViewModel.signIn(binding.etEmail.trimmedText, binding.etPassword.trimmedText) .observe(this, { resource -> when (resource) { is Resource.Success -> finish() is Resource.Failure -> handleApiError(resource) } }) } private fun signInWithGoogle(idToken: String) { signInViewModel.signInWithGoogle(idToken).observe(this, { resource -> when (resource) { is Resource.Success -> finish() is Resource.Failure -> handleApiError(resource) } }) } private fun isValid(): Boolean { var valid = true if (binding.etEmail.trimmedText.isEmpty()) { binding.tilEmail.error = "Required" valid = false } else if (!binding.etEmail.trimmedText.isValidEmail()) { binding.tilEmail.error = "Incorrect email" valid = false } if (binding.etPassword.trimmedText.isEmpty()) { binding.tilPassword.error = "Required" valid = false } return valid } }
apache-2.0
7e3f979250f710d6cba2f038f69886cf
32.824675
120
0.633327
4.881912
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/ui/migration/manga/design/MigrationSourceItem.kt
1
2438
package exh.ui.migration.manga.design import android.os.Parcelable import android.support.v7.widget.RecyclerView import android.view.View import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.android.parcel.Parcelize class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean): AbstractFlexibleItem<MigrationSourceHolder>() { override fun getLayoutRes() = R.layout.eh_source_item override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): MigrationSourceHolder { return MigrationSourceHolder(view, adapter as MigrationSourceAdapter) } /** * Binds the given view holder with this item. * * @param adapter The adapter of this item. * @param holder The holder to bind. * @param position The position of this item in the adapter. * @param payloads List of partial changes. */ override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: MigrationSourceHolder, position: Int, payloads: List<Any?>?) { holder.bind(source, sourceEnabled) } /** * Returns true if this item is draggable. */ override fun isDraggable(): Boolean { return true } override fun equals(other: Any?): Boolean { if (this === other) return true if (other is MigrationSourceItem) { return source.id == other.source.id } return false } override fun hashCode(): Int { return source.id.hashCode() } @Parcelize data class ParcelableSI(val sourceId: Long, val sourceEnabled: Boolean): Parcelable fun asParcelable(): ParcelableSI { return ParcelableSI(source.id, sourceEnabled) } companion object { fun fromParcelable(sourceManager: SourceManager, si: ParcelableSI): MigrationSourceItem? { val source = sourceManager.get(si.sourceId) as? HttpSource ?: return null return MigrationSourceItem( source, si.sourceEnabled ) } } }
apache-2.0
6f2d9663c63f593e4a796f287c087112
32.875
132
0.669401
4.935223
false
false
false
false
SirLYC/Android-Gank-Share
app/src/main/java/com/lyc/gank/utils/ObservableList.kt
1
1983
package com.lyc.gank.utils import android.support.v7.util.ListUpdateCallback /** * Created by Liu Yuchuan on 2018/2/16. */ class ObservableList<E>(private val realList: MutableList<E>): AbstractMutableList<E>() { override val size: Int get() = realList.size private val callbacks = mutableListOf<ListUpdateCallback>() fun addCallback(callback: ListUpdateCallback) = callbacks.add(callback) fun removeCallback(callback: ListUpdateCallback) = callbacks.remove(callback) override fun get(index: Int) = realList[index] override fun add(index: Int, element: E) { realList.add(index, element) callbacks.forEach { it.onInserted(index, 1) } } override fun removeAt(index: Int): E { val result = realList.removeAt(index) callbacks.forEach { it.onRemoved(index, 1) } return result } override fun set(index: Int, element: E): E { val result = realList.set(index, element) callbacks.forEach { it.onChanged(index, 1, element) } return result } override fun addAll(index: Int, elements: Collection<E>): Boolean { val result = realList.addAll(index, elements) if(result){ callbacks.forEach { it.onInserted(index, elements.size) } } return result } override fun addAll(elements: Collection<E>): Boolean{ val addIndex = realList.size val result = realList.addAll(elements) if(result){ callbacks.forEach { it.onInserted(addIndex, elements.size) } } return result } override fun removeRange(fromIndex: Int, toIndex: Int) { var index = fromIndex while(index < toIndex) realList.removeAt(index++) callbacks.forEach { it.onRemoved(fromIndex, toIndex - fromIndex) } } override fun clear() { val oldSize = realList.size realList.clear() callbacks.forEach { it.onRemoved(0, oldSize) } } }
apache-2.0
72cba2c031213839cbd686682684a83a
28.61194
89
0.638931
4.148536
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/ui/WeekdayPicker.kt
1
2838
package info.nightscout.androidaps.utils.ui import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.Checkable import androidx.appcompat.widget.AppCompatCheckedTextView import androidx.constraintlayout.widget.ConstraintLayout import info.nightscout.androidaps.core.databinding.WeekdayPickerBinding import info.nightscout.androidaps.extensions.toVisibility import java.util.* class WeekdayPicker constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private var changeListener: ((Int, Boolean) -> Unit)? = null private var binding: WeekdayPickerBinding init { val inflater = LayoutInflater.from(context) binding = WeekdayPickerBinding.inflate(inflater, this, true) determineBeginOfWeek() setupClickListeners() } private fun determineBeginOfWeek() { (Calendar.getInstance().firstDayOfWeek == Calendar.SUNDAY).let { binding.weekdayPickerSundayStart.visibility = it.toVisibility() binding.weekdayPickerSundayEnd.visibility = it.not().toVisibility() } } fun setSelectedDays(list: List<Int>) = with(binding) { weekdayPickerSundayStart.isChecked = list.contains(Calendar.SUNDAY) weekdayPickerSundayEnd.isChecked = list.contains(Calendar.SUNDAY) weekdayPickerMonday.isChecked = list.contains(Calendar.MONDAY) weekdayPickerTuesday.isChecked = list.contains(Calendar.TUESDAY) weekdayPickerWednesday.isChecked = list.contains(Calendar.WEDNESDAY) weekdayPickerThursday.isChecked = list.contains(Calendar.THURSDAY) weekdayPickerFriday.isChecked = list.contains(Calendar.FRIDAY) weekdayPickerSaturday.isChecked = list.contains(Calendar.SATURDAY) } private fun setupClickListeners() = with(binding) { weekdayPickerSundayStart.setupCallbackFor(Calendar.SUNDAY) weekdayPickerSundayEnd.setupCallbackFor(Calendar.SUNDAY) weekdayPickerMonday.setupCallbackFor(Calendar.MONDAY) weekdayPickerTuesday.setupCallbackFor(Calendar.TUESDAY) weekdayPickerWednesday.setupCallbackFor(Calendar.WEDNESDAY) weekdayPickerThursday.setupCallbackFor(Calendar.THURSDAY) weekdayPickerFriday.setupCallbackFor(Calendar.FRIDAY) weekdayPickerSaturday.setupCallbackFor(Calendar.SATURDAY) } fun setOnWeekdaysChangeListener(changeListener: (Int, Boolean) -> Unit) { this.changeListener = changeListener } private fun AppCompatCheckedTextView.setupCallbackFor(day: Int) = setOnClickListener { val checkable = it as Checkable val checked = checkable.isChecked checkable.isChecked = !checked changeListener?.invoke(day, !checked) } }
agpl-3.0
7075cad8ad1bf121a05250ed953f22a8
40.75
90
0.751233
4.893103
false
false
false
false
Adventech/sabbath-school-android-2
common/design-compose/src/main/kotlin/app/ss/design/compose/widget/material/Slider.kt
1
30407
/* * Copyright (c) 2021. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.design.compose.widget.material import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.TweenSpec import androidx.compose.foundation.Canvas import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.background import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.DragScope import androidx.compose.foundation.gestures.DraggableState import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.awaitHorizontalTouchSlopOrCancellation import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.indication import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSizeIn import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.progressSemantics import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.ContentAlpha import androidx.compose.material.MaterialTheme import androidx.compose.material.contentColorFor import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.SideEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.lerp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PointMode import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerId import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.consumePositionChange import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.semantics.disabled import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.setProgress import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.util.lerp import kotlinx.coroutines.CancellationException import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlin.math.abs /** * <a href="https://material.io/components/sliders" class="external" target="_blank">Material Design slider</a>. * * Sliders allow users to make selections from a range of values. * * Sliders reflect a range of values along a bar, from which users may select a single value. * They are ideal for adjusting settings such as volume, brightness, or applying image filters. * * ![Sliders image](https://developer.android.com/images/reference/androidx/compose/material/sliders.png) * * Use continuous sliders to allow users to make meaningful selections that don’t * require a specific value: * * @sample androidx.compose.material.samples.SliderSample * * You can allow the user to choose only between predefined set of values by specifying the amount * of steps between min and max values: * * @sample androidx.compose.material.samples.StepsSliderSample * * @param value current value of the Slider. If outside of [valueRange] provided, value will be * coerced to this range. * @param onValueChange lambda in which value should be updated * @param modifier modifiers for the Slider layout * @param enabled whether or not component is enabled and can we interacted with or not * @param valueRange range of values that Slider value can take. Passed [value] will be coerced to * this range * @param steps if greater than 0, specifies the amounts of discrete values, evenly distributed * between across the whole value range. If 0, slider will behave as a continuous slider and allow * to choose any value from the range specified. Must not be negative. * @param onValueChangeFinished lambda to be invoked when value change has ended. This callback * shouldn't be used to update the slider value (use [onValueChange] for that), but rather to * know when the user has completed selecting a new value by ending a drag or a click. * @param interactionSource the [MutableInteractionSource] representing the stream of * [Interaction]s for this Slider. You can create and pass in your own remembered * [MutableInteractionSource] if you want to observe [Interaction]s and customize the * appearance / behavior of this Slider in different [Interaction]s. * @param colors [SliderColors] that will be used to determine the color of the Slider parts in * different state. See [SliderDefaults.colors] to customize. */ @Composable fun Slider( value: Float, onValueChange: (Float) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, valueRange: ClosedFloatingPointRange<Float> = 0f..1f, /*@IntRange(from = 0)*/ steps: Int = 0, onValueChangeFinished: (() -> Unit)? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, thumbRadius: Dp = SliderDefaults.ThumbRadius, colors: SliderColors = SliderDefaults.colors() ) { require(steps >= 0) { "steps should be >= 0" } val onValueChangeState = rememberUpdatedState(onValueChange) val tickFractions = remember(steps) { stepsToTickFractions(steps) } BoxWithConstraints( modifier .requiredSizeIn(minWidth = thumbRadius * 2, minHeight = thumbRadius * 2) .sliderSemantics(value, tickFractions, enabled, onValueChange, valueRange, steps) .focusable(enabled, interactionSource) ) { val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl val maxPx = constraints.maxWidth.toFloat() val minPx = 0f fun scaleToUserValue(offset: Float) = scale(minPx, maxPx, offset, valueRange.start, valueRange.endInclusive) fun scaleToOffset(userValue: Float) = scale(valueRange.start, valueRange.endInclusive, userValue, minPx, maxPx) val scope = rememberCoroutineScope() val rawOffset = remember { mutableStateOf(scaleToOffset(value)) } val draggableState = remember(minPx, maxPx, valueRange) { SliderDraggableState { rawOffset.value = (rawOffset.value + it).coerceIn(minPx, maxPx) onValueChangeState.value.invoke(scaleToUserValue(rawOffset.value)) } } CorrectValueSideEffect(::scaleToOffset, valueRange, rawOffset, value) val gestureEndAction = rememberUpdatedState<(Float) -> Unit> { velocity: Float -> val current = rawOffset.value val target = snapValueToTick(current, tickFractions, minPx, maxPx) if (current != target) { scope.launch { animateToTarget(draggableState, current, target, velocity) onValueChangeFinished?.invoke() } } else if (!draggableState.isDragging) { // check ifDragging in case the change is still in progress (touch -> drag case) onValueChangeFinished?.invoke() } } val press = Modifier.sliderPressModifier( draggableState, interactionSource, maxPx, isRtl, rawOffset, gestureEndAction, enabled ) val drag = Modifier.draggable( orientation = Orientation.Horizontal, reverseDirection = isRtl, enabled = enabled, interactionSource = interactionSource, onDragStopped = { velocity -> gestureEndAction.value.invoke(velocity) }, startDragImmediately = draggableState.isDragging, state = draggableState ) val coerced = value.coerceIn(valueRange.start, valueRange.endInclusive) val fraction = calcFraction(valueRange.start, valueRange.endInclusive, coerced) SliderImpl( enabled, fraction, tickFractions, thumbRadius, colors, maxPx, interactionSource, modifier = press.then(drag) ) } } /** * Object to hold defaults used by [Slider] */ object SliderDefaults { /** * Creates a [SliderColors] that represents the different colors used in parts of the * [Slider] in different states. * * For the name references below the words "active" and "inactive" are used. Active part of * the slider is filled with progress, so if slider's progress is 30% out of 100%, left (or * right in RTL) 30% of the track will be active, the rest is not active. * * @param thumbColor thumb color when enabled * @param disabledThumbColor thumb colors when disabled * @param activeTrackColor color of the track in the part that is "active", meaning that the * thumb is ahead of it * @param inactiveTrackColor color of the track in the part that is "inactive", meaning that the * thumb is before it * @param disabledActiveTrackColor color of the track in the "active" part when the Slider is * disabled * @param disabledInactiveTrackColor color of the track in the "inactive" part when the * Slider is disabled * @param activeTickColor colors to be used to draw tick marks on the active track, if `steps` * is specified * @param inactiveTickColor colors to be used to draw tick marks on the inactive track, if * `steps` are specified on the Slider is specified * @param disabledActiveTickColor colors to be used to draw tick marks on the active track * when Slider is disabled and when `steps` are specified on it * @param disabledInactiveTickColor colors to be used to draw tick marks on the inactive part * of the track when Slider is disabled and when `steps` are specified on it */ @Composable fun colors( thumbColor: Color = MaterialTheme.colors.primary, disabledThumbColor: Color = MaterialTheme.colors.onSurface .copy(alpha = ContentAlpha.disabled) .compositeOver(MaterialTheme.colors.surface), activeTrackColor: Color = MaterialTheme.colors.primary, inactiveTrackColor: Color = activeTrackColor.copy(alpha = InactiveTrackAlpha), disabledActiveTrackColor: Color = MaterialTheme.colors.onSurface.copy(alpha = DisabledActiveTrackAlpha), disabledInactiveTrackColor: Color = disabledActiveTrackColor.copy(alpha = DisabledInactiveTrackAlpha), activeTickColor: Color = contentColorFor(activeTrackColor).copy(alpha = TickAlpha), inactiveTickColor: Color = activeTrackColor.copy(alpha = TickAlpha), disabledActiveTickColor: Color = activeTickColor.copy(alpha = DisabledTickAlpha), disabledInactiveTickColor: Color = disabledInactiveTrackColor .copy(alpha = DisabledTickAlpha) ): SliderColors = DefaultSliderColors( thumbColor = thumbColor, disabledThumbColor = disabledThumbColor, activeTrackColor = activeTrackColor, inactiveTrackColor = inactiveTrackColor, disabledActiveTrackColor = disabledActiveTrackColor, disabledInactiveTrackColor = disabledInactiveTrackColor, activeTickColor = activeTickColor, inactiveTickColor = inactiveTickColor, disabledActiveTickColor = disabledActiveTickColor, disabledInactiveTickColor = disabledInactiveTickColor ) val ThumbRadius = 10.dp /** * Default alpha of the inactive part of the track */ const val InactiveTrackAlpha = 0.24f /** * Default alpha for the track when it is disabled but active */ const val DisabledInactiveTrackAlpha = 0.12f /** * Default alpha for the track when it is disabled and inactive */ const val DisabledActiveTrackAlpha = 0.32f /** * Default alpha of the ticks that are drawn on top of the track */ const val TickAlpha = 0.54f /** * Default alpha for tick marks when they are disabled */ const val DisabledTickAlpha = 0.12f } /** * Represents the colors used by a [Slider] and its parts in different states * * See [SliderDefaults.colors] for the default implementation that follows Material * specifications. */ @Stable interface SliderColors { /** * Represents the color used for the sliders's thumb, depending on [enabled]. * * @param enabled whether the [Slider] is enabled or not */ @Composable fun thumbColor(enabled: Boolean): State<Color> /** * Represents the color used for the sliders's track, depending on [enabled] and [active]. * * Active part is filled with progress, so if sliders progress is 30% out of 100%, left (or * right in RTL) 30% of the track will be active, the rest is not active. * * @param enabled whether the [Slider] is enabled or not * @param active whether the part of the track is active of not */ @Composable fun trackColor(enabled: Boolean, active: Boolean): State<Color> /** * Represents the color used for the sliders's tick which is the dot separating steps, if * they are set on the slider, depending on [enabled] and [active]. * * Active tick is the tick that is in the part of the track filled with progress, so if * sliders progress is 30% out of 100%, left (or right in RTL) 30% of the track and the ticks * in this 30% will be active, the rest is not active. * * @param enabled whether the [Slider] is enabled or not * @param active whether the part of the track this tick is in is active of not */ @Composable fun tickColor(enabled: Boolean, active: Boolean): State<Color> } @Composable private fun SliderImpl( enabled: Boolean, positionFraction: Float, tickFractions: List<Float>, thumbRadius: Dp, colors: SliderColors, width: Float, interactionSource: MutableInteractionSource, modifier: Modifier ) { Box(modifier.then(DefaultSliderConstraints)) { val trackStrokeWidth: Float val thumbPx: Float val widthDp: Dp with(LocalDensity.current) { trackStrokeWidth = TrackHeight.toPx() thumbPx = thumbRadius.toPx() widthDp = width.toDp() } val thumbSize = thumbRadius * 2 val offset = (widthDp - thumbSize) * positionFraction val center = Modifier.align(Alignment.CenterStart) Track( center.fillMaxSize(), colors, enabled, 0f, positionFraction, tickFractions, thumbPx, trackStrokeWidth ) SliderThumb(center, offset, interactionSource, colors, enabled, thumbSize) } } @Composable private fun SliderThumb( modifier: Modifier, offset: Dp, interactionSource: MutableInteractionSource, colors: SliderColors, enabled: Boolean, thumbSize: Dp ) { Box(modifier.padding(start = offset)) { val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> interactions.add(interaction) is PressInteraction.Release -> interactions.remove(interaction.press) is PressInteraction.Cancel -> interactions.remove(interaction.press) is DragInteraction.Start -> interactions.add(interaction) is DragInteraction.Stop -> interactions.remove(interaction.start) is DragInteraction.Cancel -> interactions.remove(interaction.start) } } } val elevation = if (interactions.isNotEmpty()) { ThumbPressedElevation } else { ThumbDefaultElevation } Spacer( Modifier .size(thumbSize, thumbSize) .indication( interactionSource = interactionSource, indication = rememberRipple(bounded = false, radius = thumbSize * 1.2f) ) .shadow(if (enabled) elevation else 0.dp, CircleShape, clip = false) .background(colors.thumbColor(enabled).value, CircleShape) ) } } @Composable private fun Track( modifier: Modifier, colors: SliderColors, enabled: Boolean, positionFractionStart: Float, positionFractionEnd: Float, tickFractions: List<Float>, thumbPx: Float, trackStrokeWidth: Float ) { val inactiveTrackColor = colors.trackColor(enabled, active = false) val activeTrackColor = colors.trackColor(enabled, active = true) val inactiveTickColor = colors.tickColor(enabled, active = false) val activeTickColor = colors.tickColor(enabled, active = true) Canvas(modifier) { val isRtl = layoutDirection == LayoutDirection.Rtl val sliderLeft = Offset(thumbPx, center.y) val sliderRight = Offset(size.width - thumbPx, center.y) val sliderStart = if (isRtl) sliderRight else sliderLeft val sliderEnd = if (isRtl) sliderLeft else sliderRight drawLine( inactiveTrackColor.value, sliderStart, sliderEnd, trackStrokeWidth, StrokeCap.Round ) val sliderValueEnd = Offset( sliderStart.x + (sliderEnd.x - sliderStart.x) * positionFractionEnd, center.y ) val sliderValueStart = Offset( sliderStart.x + (sliderEnd.x - sliderStart.x) * positionFractionStart, center.y ) drawLine( activeTrackColor.value, sliderValueStart, sliderValueEnd, trackStrokeWidth, StrokeCap.Round ) tickFractions.groupBy { it > positionFractionEnd }.forEach { (afterFraction, list) -> drawPoints( list.map { Offset(lerp(sliderStart, sliderEnd, it).x, center.y) }, PointMode.Points, (if (afterFraction) inactiveTickColor else activeTickColor).value, trackStrokeWidth, StrokeCap.Round ) } } } private fun snapValueToTick( current: Float, tickFractions: List<Float>, minPx: Float, maxPx: Float ): Float { // target is a closest anchor to the `current`, if exists return tickFractions .minByOrNull { abs(lerp(minPx, maxPx, it) - current) } ?.run { lerp(minPx, maxPx, this) } ?: current } private suspend fun AwaitPointerEventScope.awaitSlop( id: PointerId ): Pair<PointerInputChange, Float>? { var initialDelta = 0f val postTouchSlop = { pointerInput: PointerInputChange, offset: Float -> pointerInput.consumePositionChange() initialDelta = offset } val afterSlopResult = awaitHorizontalTouchSlopOrCancellation(id, postTouchSlop) return if (afterSlopResult != null) afterSlopResult to initialDelta else null } private fun stepsToTickFractions(steps: Int): List<Float> { return if (steps == 0) emptyList() else List(steps + 2) { it.toFloat() / (steps + 1) } } // Scale x1 from a1..b1 range to a2..b2 range private fun scale(a1: Float, b1: Float, x1: Float, a2: Float, b2: Float) = lerp(a2, b2, calcFraction(a1, b1, x1)) // Scale x.start, x.endInclusive from a1..b1 range to a2..b2 range private fun scale(a1: Float, b1: Float, x: ClosedFloatingPointRange<Float>, a2: Float, b2: Float) = scale(a1, b1, x.start, a2, b2)..scale(a1, b1, x.endInclusive, a2, b2) // Calculate the 0..1 fraction that `pos` value represents between `a` and `b` private fun calcFraction(a: Float, b: Float, pos: Float) = (if (b - a == 0f) 0f else (pos - a) / (b - a)).coerceIn(0f, 1f) @Composable private fun CorrectValueSideEffect( scaleToOffset: (Float) -> Float, valueRange: ClosedFloatingPointRange<Float>, valueState: MutableState<Float>, value: Float ) { SideEffect { val error = (valueRange.endInclusive - valueRange.start) / 1000 val newOffset = scaleToOffset(value) if (abs(newOffset - valueState.value) > error) { valueState.value = newOffset } } } private fun Modifier.sliderSemantics( value: Float, tickFractions: List<Float>, enabled: Boolean, onValueChange: (Float) -> Unit, valueRange: ClosedFloatingPointRange<Float> = 0f..1f, steps: Int = 0 ): Modifier { val coerced = value.coerceIn(valueRange.start, valueRange.endInclusive) return semantics(mergeDescendants = true) { if (!enabled) disabled() setProgress( action = { targetValue -> val newValue = targetValue.coerceIn(valueRange.start, valueRange.endInclusive) val resolvedValue = if (steps > 0) { tickFractions .map { lerp(valueRange.start, valueRange.endInclusive, it) } .minByOrNull { abs(it - newValue) } ?: newValue } else { newValue } // This is to keep it consistent with AbsSeekbar.java: return false if no // change from current. if (resolvedValue == coerced) { false } else { onValueChange(resolvedValue) true } } ) }.progressSemantics(value, valueRange, steps) } private fun Modifier.sliderPressModifier( draggableState: DraggableState, interactionSource: MutableInteractionSource, maxPx: Float, isRtl: Boolean, rawOffset: State<Float>, gestureEndAction: State<(Float) -> Unit>, enabled: Boolean ): Modifier = if (enabled) { pointerInput(draggableState, interactionSource, maxPx, isRtl) { detectTapGestures( onPress = { pos -> draggableState.drag(MutatePriority.UserInput) { val to = if (isRtl) maxPx - pos.x else pos.x dragBy(to - rawOffset.value) } val interaction = PressInteraction.Press(pos) interactionSource.emit(interaction) val finishInteraction = try { val success = tryAwaitRelease() gestureEndAction.value.invoke(0f) if (success) { PressInteraction.Release(interaction) } else { PressInteraction.Cancel(interaction) } } catch (c: CancellationException) { PressInteraction.Cancel(interaction) } interactionSource.emit(finishInteraction) } ) } } else { this } private suspend fun animateToTarget( draggableState: DraggableState, current: Float, target: Float, velocity: Float ) { draggableState.drag { var latestValue = current Animatable(initialValue = current).animateTo(target, SliderToTickAnimation, velocity) { dragBy(this.value - latestValue) latestValue = this.value } } } @Immutable private class DefaultSliderColors( private val thumbColor: Color, private val disabledThumbColor: Color, private val activeTrackColor: Color, private val inactiveTrackColor: Color, private val disabledActiveTrackColor: Color, private val disabledInactiveTrackColor: Color, private val activeTickColor: Color, private val inactiveTickColor: Color, private val disabledActiveTickColor: Color, private val disabledInactiveTickColor: Color ) : SliderColors { @Composable override fun thumbColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) thumbColor else disabledThumbColor) } @Composable override fun trackColor(enabled: Boolean, active: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (active) activeTrackColor else inactiveTrackColor } else { if (active) disabledActiveTrackColor else disabledInactiveTrackColor } ) } @Composable override fun tickColor(enabled: Boolean, active: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (active) activeTickColor else inactiveTickColor } else { if (active) disabledActiveTickColor else disabledInactiveTickColor } ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as DefaultSliderColors if (thumbColor != other.thumbColor) return false if (disabledThumbColor != other.disabledThumbColor) return false if (activeTrackColor != other.activeTrackColor) return false if (inactiveTrackColor != other.inactiveTrackColor) return false if (disabledActiveTrackColor != other.disabledActiveTrackColor) return false if (disabledInactiveTrackColor != other.disabledInactiveTrackColor) return false if (activeTickColor != other.activeTickColor) return false if (inactiveTickColor != other.inactiveTickColor) return false if (disabledActiveTickColor != other.disabledActiveTickColor) return false if (disabledInactiveTickColor != other.disabledInactiveTickColor) return false return true } override fun hashCode(): Int { var result = thumbColor.hashCode() result = 31 * result + disabledThumbColor.hashCode() result = 31 * result + activeTrackColor.hashCode() result = 31 * result + inactiveTrackColor.hashCode() result = 31 * result + disabledActiveTrackColor.hashCode() result = 31 * result + disabledInactiveTrackColor.hashCode() result = 31 * result + activeTickColor.hashCode() result = 31 * result + inactiveTickColor.hashCode() result = 31 * result + disabledActiveTickColor.hashCode() result = 31 * result + disabledInactiveTickColor.hashCode() return result } } // Internal to be referred to in tests // private val ThumbRippleRadius = 24.dp private val ThumbDefaultElevation = 1.dp private val ThumbPressedElevation = 6.dp // Internal to be referred to in tests internal val TrackHeight = 4.dp private val SliderHeight = 48.dp private val SliderMinWidth = 144.dp // TODO: clarify min width private val DefaultSliderConstraints = Modifier .widthIn(min = SliderMinWidth) .heightIn(max = SliderHeight) private val SliderToTickAnimation = TweenSpec<Float>(durationMillis = 100) private class SliderDraggableState( val onDelta: (Float) -> Unit ) : DraggableState { var isDragging by mutableStateOf(false) private set private val dragScope: DragScope = object : DragScope { override fun dragBy(pixels: Float): Unit = onDelta(pixels) } private val scrollMutex = MutatorMutex() override suspend fun drag( dragPriority: MutatePriority, block: suspend DragScope.() -> Unit ): Unit = coroutineScope { isDragging = true scrollMutex.mutateWith(dragScope, dragPriority, block) isDragging = false } override fun dispatchRawDelta(delta: Float) { return onDelta(delta) } }
mit
c460599d56b1279d8b676c28a3d8dc82
38.435798
112
0.678079
4.755239
false
false
false
false
shihochan/KotlinDIExample
useDagger/src/main/kotlin/com/shihochan/kotlindiexample/ui/top/TopActivity.kt
1
1760
package com.shihochan.kotlindiexample.ui.top import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.View import com.shihochan.kotlindiexample.R import com.shihochan.kotlindiexample.data.GitHubRepository import com.shihochan.kotlindiexample.databinding.ActivityTopBinding import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration import dagger.android.support.DaggerAppCompatActivity import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.subscribeBy import timber.log.Timber import javax.inject.Inject class TopActivity : DaggerAppCompatActivity() { @Inject lateinit var gitHubRepository: GitHubRepository private lateinit var binding: ActivityTopBinding private val adapter = TopAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_top) val layoutManager = LinearLayoutManager(this) layoutManager.isItemPrefetchEnabled = true binding.recyclerView.adapter = adapter binding.recyclerView.layoutManager = layoutManager binding.recyclerView.addItemDecoration( HorizontalDividerItemDecoration.Builder(this).build()) binding.progressBar.visibility = View.VISIBLE getFollower() } fun getFollower() = gitHubRepository.getFollowers("shihochan") .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onNext = { binding.progressBar.visibility = View.GONE adapter.set(it) }, onError = { binding.progressBar.visibility = View.GONE Timber.e(it.message) }) }
apache-2.0
cdcb6c8949528021598a1e20cefac121
33.509804
77
0.771591
4.808743
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/jetpack/restore/usecases/GetRestoreStatusUseCaseTest.kt
1
17040
package org.wordpress.android.ui.jetpack.restore.usecases import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.flow.toList import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.whenever import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.fluxc.action.ActivityLogAction.FETCH_REWIND_STATE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.activity.ActivityLogModel import org.wordpress.android.fluxc.model.activity.RewindStatusModel import org.wordpress.android.fluxc.model.activity.RewindStatusModel.Reason import org.wordpress.android.fluxc.model.activity.RewindStatusModel.Rewind import org.wordpress.android.fluxc.model.activity.RewindStatusModel.State import org.wordpress.android.fluxc.store.ActivityLogStore import org.wordpress.android.fluxc.store.ActivityLogStore.OnRewindStatusFetched import org.wordpress.android.fluxc.store.ActivityLogStore.RewindStatusError import org.wordpress.android.fluxc.store.ActivityLogStore.RewindStatusErrorType.GENERIC_ERROR import org.wordpress.android.test import org.wordpress.android.ui.jetpack.restore.RestoreRequestState import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.AwaitingCredentials import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Complete import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Failure import org.wordpress.android.ui.jetpack.restore.RestoreRequestState.Progress import org.wordpress.android.util.NetworkUtilsWrapper import java.util.Date private const val REWIND_ID = "rewindId" private const val RESTORE_ID = 123456789L private const val PROGRESS = 50 private const val MESSAGE = "message" private const val CURRENT_ENTRY = "current entry" private val PUBLISHED = Date() @InternalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class GetRestoreStatusUseCaseTest { private lateinit var useCase: GetRestoreStatusUseCase @Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock lateinit var activityLogStore: ActivityLogStore @Mock private lateinit var site: SiteModel @Before fun setup() = test { useCase = GetRestoreStatusUseCase(networkUtilsWrapper, activityLogStore, TEST_DISPATCHER) whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true) whenever(activityLogStore.fetchActivitiesRewind(any())).thenReturn(OnRewindStatusFetched(FETCH_REWIND_STATE)) whenever(activityLogStore.getActivityLogItemByRewindId(REWIND_ID)).thenReturn(activityLogModel()) } @Test fun `given no network without restore id, when restore status triggers, then return network unavailable`() = test { whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(Failure.NetworkUnavailable) } @Test fun `given no network with restore id, when restore status triggers, then return network unavailable`() = test { whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(Failure.NetworkUnavailable) } @Test fun `given failure without restore id, when restore status triggers, then return remote request failure`() = test { whenever(activityLogStore.fetchActivitiesRewind(any())) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(Failure.RemoteRequestFailure) } @Test fun `given failure with restore id, when restore status triggers, then return failure`() = test { whenever(activityLogStore.fetchActivitiesRewind(any())) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(Failure.RemoteRequestFailure) } @Test fun `given finished without restore id and rewind id, when restore status triggers, then return complete`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(Complete(REWIND_ID, RESTORE_ID, PUBLISHED)) } @Test fun `given finished with restore id and rewind id, when restore status triggers, then return complete`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(Complete(REWIND_ID, RESTORE_ID, PUBLISHED)) } @Test fun `given finished without restore id no rewind id, when restore status triggers, then return failure`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(null, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(Failure.RemoteRequestFailure) } @Test fun `given finished with restore id no rewind id, when restore status triggers, then return failure`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(null, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(Failure.RemoteRequestFailure) } @Test fun `given failed without restore id, when restore status triggers, then return failure`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FAILED)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(Failure.RemoteRequestFailure) } @Test fun `given failed with restore id, when restore status triggers, then return failure`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FAILED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(Failure.RemoteRequestFailure) } @Test fun `given running without restore id, when restore status triggers, then return progress`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.RUNNING)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains( Progress(REWIND_ID, PROGRESS, MESSAGE, CURRENT_ENTRY, PUBLISHED), Complete(REWIND_ID, RESTORE_ID, PUBLISHED) ) } @Test fun `given running with restore id, when restore status triggers, then return progress`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.RUNNING)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains( Progress(REWIND_ID, PROGRESS, MESSAGE, CURRENT_ENTRY, PUBLISHED), Complete(REWIND_ID, RESTORE_ID, PUBLISHED) ) } @Test fun `given queued without restore id, when restore status triggers, then return progress`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.QUEUED)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains( Progress(REWIND_ID, PROGRESS, MESSAGE, CURRENT_ENTRY, PUBLISHED), Complete(REWIND_ID, RESTORE_ID, PUBLISHED) ) } @Test fun `given queued with restore id, when restore status triggers, then return progress`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.QUEUED)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains( Progress(REWIND_ID, PROGRESS, MESSAGE, CURRENT_ENTRY, PUBLISHED), Complete(REWIND_ID, RESTORE_ID, PUBLISHED) ) } @Test fun `given unavailable multisite without restoreId, when restore status triggers, then return multisite`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(null, null, State.UNAVAILABLE, Reason.MULTISITE_NOT_SUPPORTED)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(RestoreRequestState.Multisite) } @Test fun `given unavailable multisite with restoreId, when restore status triggers, then return multisite`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(null, null, State.UNAVAILABLE, Reason.MULTISITE_NOT_SUPPORTED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(RestoreRequestState.Multisite) } @Test fun `given unavailable without restoreId, when restore status triggers, then return empty`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(null, null, State.UNAVAILABLE)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).contains(RestoreRequestState.Empty) } @Test fun `given unavailable with restoreId, when restore status triggers, then return empty`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(null, null, State.UNAVAILABLE)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains(RestoreRequestState.Empty) } @Test fun `given max fetch retries exceeded, when restore status triggers, then return remote request failure`() = test { whenever(activityLogStore.fetchActivitiesRewind(any())) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) val result = useCase.getRestoreStatus(site, null).toList() assertThat(result).size().isEqualTo(1) assertThat(result).isEqualTo(listOf(Failure.RemoteRequestFailure)) } @Test fun `given fetch error under retry count, when restore status triggers, then return progress`() = test { whenever(activityLogStore.fetchActivitiesRewind(any())) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) .thenReturn(OnRewindStatusFetched(RewindStatusError(GENERIC_ERROR), FETCH_REWIND_STATE)) .thenReturn(OnRewindStatusFetched(FETCH_REWIND_STATE)) whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.RUNNING)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains( Progress(REWIND_ID, PROGRESS, MESSAGE, CURRENT_ENTRY, PUBLISHED), Complete(REWIND_ID, RESTORE_ID, PUBLISHED) ) } @Test fun `given no network available under retry count, when restore status triggers, then return progress`() = test { whenever(networkUtilsWrapper.isNetworkAvailable()) .thenReturn(false) .thenReturn(false) .thenReturn(true) whenever(activityLogStore.fetchActivitiesRewind(any())) .thenReturn(OnRewindStatusFetched(FETCH_REWIND_STATE)) whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.RUNNING)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED)) val result = useCase.getRestoreStatus(site, RESTORE_ID).toList() assertThat(result).contains( Progress(REWIND_ID, PROGRESS, MESSAGE, CURRENT_ENTRY, PUBLISHED), Complete(REWIND_ID, RESTORE_ID, PUBLISHED) ) } @Test fun `given awaiting creds state, when awaiting creds is checked, then creds are awaited in result`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(rewindId = null, state = State.AWAITING_CREDENTIALS)) val result = useCase.getRestoreStatus(site, restoreId = null, checkIfAwaitingCredentials = true) .toList() assertThat(result).contains(AwaitingCredentials(true)) } @Test fun `given non awaiting creds state, when awaiting creds is checked, then creds are not awaited in result`() = test { whenever(activityLogStore.getRewindStatusForSite(site)) .thenReturn(rewindStatusModel(REWIND_ID, Rewind.Status.FINISHED, state = State.ACTIVE)) val result = useCase.getRestoreStatus(site, RESTORE_ID, checkIfAwaitingCredentials = true) .toList() assertThat(result).contains(AwaitingCredentials(false)) } /* PRIVATE */ private fun activityLogModel() = ActivityLogModel( activityID = "activityID", summary = "summary", content = null, name = null, type = null, gridicon = null, status = null, rewindable = null, rewindID = null, published = PUBLISHED, actor = null ) private fun rewindStatusModel( rewindId: String?, status: Rewind.Status? = null, state: State = State.ACTIVE, reason: Reason = Reason.NO_REASON ) = RewindStatusModel( state = state, reason = reason, lastUpdated = PUBLISHED, canAutoconfigure = null, credentials = null, rewind = if (state == State.AWAITING_CREDENTIALS || state == State.UNAVAILABLE) { null } else { rewind(rewindId, status as Rewind.Status) } ) private fun rewind( rewindId: String?, status: Rewind.Status ) = Rewind( rewindId = rewindId, restoreId = RESTORE_ID, status = status, progress = PROGRESS, reason = null, message = MESSAGE, currentEntry = CURRENT_ENTRY ) }
gpl-2.0
bb8fe2f98dda7035cc9f70bdbfb96179
42.692308
119
0.649061
5.211009
false
true
false
false
crashlytics/18thScale
app/src/main/java/com/firebase/hackweek/tank18thscale/service/BluetoothConnectThread.kt
1
2229
package com.firebase.hackweek.tank18thscale.service import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothSocket import android.util.Log import java.io.IOException // FIXME: This is probably dynamically retrievable device.uuids[0] // private const val DEVICE_UUID = "00001101-0000-1000-8000-00805f9b34fb" class BluetoothConnectThread(private val bluetoothAdapter: BluetoothAdapter, device: BluetoothDevice, private val connectListener: ConnectListener) : Thread() { private val connectSocket: BluetoothSocket init { name = "Bluetooth ConnectThread" var socket: BluetoothSocket? = null try { socket = createSocket(device) } catch (e: Exception) { Log.e("Tank18thScale", "Socket connection failed " + e.message) } // FIXME: This will blow up if an exception was thrown. connectSocket = socket!! } override fun run() { bluetoothAdapter.cancelDiscovery() try { connectSocket.connect() } catch (e: IOException) { Log.e("Tank18thScale", "Socket connect error " + e.message) try { connectSocket.close() } catch (closeError: IOException) { // TODO: log the failure } connectListener.onConnectionFailure() return } connectListener.onConnected(connectSocket) } fun cancel() { try { connectSocket.close() } catch (closeError: IOException) { // TODO: log the failure } } @Throws(Exception::class) private fun createSocket(device: BluetoothDevice) : BluetoothSocket { // return device.createRfcommSocketToServiceRecord(UUID.fromString(DEVICE_UUID)) // Use the internal connect method to bypass the service record lookup val m = device.javaClass.getMethod( "createRfcommSocket", Int::class.javaPrimitiveType ) return m.invoke(device, 1) as BluetoothSocket } interface ConnectListener { fun onConnected(socket: BluetoothSocket) fun onConnectionFailure() } }
apache-2.0
749c2bac404530d4e86a080ff8bc327c
30.394366
160
0.641095
4.803879
false
false
false
false
DanielGrech/anko
preview/robowrapper/src/org/jetbrains/kotlin/android/robowrapper/AttributeRenderer.kt
3
9213
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.robowrapper import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import android.widget.LinearLayout import android.view.ViewGroup.MarginLayoutParams import android.widget.TableRow import android.widget.FrameLayout import android.widget.AbsoluteLayout import android.support.v4.widget.SlidingPaneLayout import android.content.Context import android.util.TypedValue import android.widget.ImageView import android.text.TextUtils.TruncateAt import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import org.robolectric.Robolectric import android.text.SpannedString import android.text.SpannableStringBuilder import org.jetbrains.kotlin.android.attrs.Attr import org.robolectric.Shadows import org.robolectric.res.ResourceLoader import org.robolectric.shadows.ShadowResources // Render a ViewGroup.LayoutParams subclass, make a parameter list of (android:layout_...) private fun renderLayoutParams(view: View, lp: ViewGroup.LayoutParams, topLevel: Boolean): String { val props = Buffer().append(" ") val present = hashSetOf<String>() fun addProperty(key: String, value: String) { if (key in present) return props.append("android:layout_").append(key).append("=\"").append(value).append("\" ") } // Add a RelativeLayout property. // Contains RelativeLayout.TRUE=-1 if set, 0 if unset, other possible values contains view id fun addRLProp(key: String, value: Int) { if (value == 0) return val v = if (value == RelativeLayout.TRUE) "true" else ("@+id/gen" + (value.toString().replace("-", "_"))) addProperty(key, v) } // Handle some special cases for layout dimension value fun addDimension(key: String, value: Int, default: String? = null) { val dim = when(value) { ViewGroup.LayoutParams.MATCH_PARENT -> "match_parent" ViewGroup.LayoutParams.WRAP_CONTENT -> "wrap_content" else -> resolveDimension(view, "", value.toString()) } if (default != null && dim == default) return addProperty(key, dim) } // These parameters are mandatory if (topLevel) { addDimension("width", ViewGroup.LayoutParams.MATCH_PARENT) addDimension("height", ViewGroup.LayoutParams.MATCH_PARENT) } else { addDimension("width", lp.width) addDimension("height", lp.height) } if (lp is LinearLayout.LayoutParams) { val gravity = resolveGravity(lp.gravity) if (gravity != null) addProperty("gravity", gravity) if (lp.weight != 0f) { val weight = lp.weight addProperty("weight", weight.prettifyNumber()) } } if (lp is MarginLayoutParams) { addDimension("marginTop", lp.topMargin, "0dp") addDimension("marginLeft", lp.leftMargin, "0dp") addDimension("marginRight", lp.rightMargin, "0dp") addDimension("marginBottom", lp.bottomMargin, "0dp") addDimension("marginStart", lp.getMarginStart(), "0dp") addDimension("marginEnd", lp.getMarginEnd(), "0dp") } if (lp is RelativeLayout.LayoutParams) { val rules = lp.getRules() relativeLayoutProperties.forEach { addRLProp(it.getKey(), rules[it.getValue()]) } } if (lp is TableRow.LayoutParams) { if (lp.column != -1) addProperty("column", lp.column.toString()) if (lp.span != -1) addProperty("span", lp.span.toString()) } if (lp is FrameLayout.LayoutParams) { val gravity = resolveGravity(lp.gravity) if (gravity != null) addProperty("gravity", gravity) } if (lp is AbsoluteLayout.LayoutParams) { addDimension("x", lp.x) addDimension("y", lp.y) } try { if (lp is SlidingPaneLayout.LayoutParams) { addProperty("weight", lp.weight.prettifyNumber()) } } catch (e: Throwable) { /* it's ok */ } return props.toString() } // Convert px value to dp (independent to screen size) private fun Context.px2dip(value: Int): Float { val metrics = getResources().getDisplayMetrics() return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value.toFloat(), metrics) } /** RenderAttr entry point. Handle all special cases (such as id, layoutParams or etc) @returns null if attr was not parsed properly */ private fun renderAttribute(view: View, attr: Attr?, key: String, value: Any, topLevel: Boolean): String? { if (key == "gravity") { return resolveGravity(value.toString().toInt()) } if (key == "id") { val id = value.toString() if (id == "-1") return null // Generate a layout-local id return "@+id/gen" + (value.toString().replace('-', '_')) } if (key == "layoutParams" && value is ViewGroup.LayoutParams) { return renderLayoutParams(view, value, topLevel) } if (value is ImageView.ScaleType) { return convertScaleType(value) } if (value is TruncateAt) { return convertEllipsize(value) } if (value is ColorDrawable) { //just return a color if value is a ColorDrawable val hex = Integer.toHexString(value.getColor()) //omit transparency part if not transparent return "#" + if (hex.startsWith("ff")) hex.substring(2) else hex } // Not a color drawable if (value is Drawable) { val drawableAttributeValue = renderDrawableAttribute(value, view) if (drawableAttributeValue != null) return drawableAttributeValue } if (attr != null) { if ("color" in attr.format) { if (value is Int) return "#" + Integer.toHexString(value) if (value is Long) return "#" + java.lang.Long.toHexString(value) } if ("dimension" in attr.format || key in dimensionProperties) { return resolveDimension(view, key, value.toString()) } if ("enum" in attr.format && attr.enum != null) { for (nv in attr.enum) { val enumValue = nv.value.parseEnumFlagValue() if (enumValue.toString().equals(basicRenderAttr(key, value))) { return nv.name } } } if ("flags" in attr.format && attr.flags != null) { return parseFlags(value.toString().toLong(), attr) } // If our property contains nothing but enum and flags, and string representation not found, exit if (attr.format.size() == 1 && attr.format[0] == "enum") return null if (attr.format.size() == 1 && attr.format[0] == "flags") return null } // (key, value) pair is not special return basicRenderAttr(key, value) } private fun renderDrawableAttribute(value: android.graphics.drawable.Drawable, view: android.view.View): String? { // Actual resourceId is stored in a ShadowDrawable val drawable = Shadows.shadowOf(value) if (drawable != null) { val resourceId = drawable.getCreatedFromResId() if (resourceId != -1) { val resourceLoader = Shadows.shadowOf(view.getContext()).getResourceLoader() // Convert Int id to a string representation (@package:resource) val resourceName = resourceLoader?.getNameForId(resourceId) if (resourceName != null) { return "@" + resourceName } } } return null } fun String.parseEnumFlagValue(): Long { if (startsWith("0x") && length() > 2) { return java.lang.Long.parseLong(substring(2), 16) } else return toLong() } private fun parseFlags(value: Long, attr: Attr): String { val present = hashSetOf<String>() attr.flags?.forEach { nv -> val flagValue = nv.value.parseEnumFlagValue() if ((value and flagValue) == flagValue) { present.add(nv.name) } } return present.joinToString("|") } // Convert several types of values to a string representation fun basicRenderAttr(key: String, value: Any): String? { when (value) { is Int, is Long -> return value.toString() is Float -> return value.prettifyNumber() is Double -> return value.prettifyNumber() is String -> return value is SpannedString -> return value.toString() is SpannableStringBuilder -> return value.toString() is Boolean -> return if (value) "true" else "false" else -> { if (DEBUG) { System.err.println("Failed to parse property key=$key type ${value.javaClass.getName()}") } return null } } }
apache-2.0
83a414f8b4f570a0b6c15c333c32699f
37.714286
114
0.645501
4.307153
false
false
false
false
squanchy-dev/squanchy-android
app/src/main/java/net/squanchy/support/widget/ImageViewWithForeground.kt
1
6005
/* * Portions derived from https://gist.github.com/chrisbanes/9091754 * For those portions: * * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.squanchy.support.widget import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.Gravity import androidx.appcompat.widget.AppCompatImageView import net.squanchy.R open class ImageViewWithForeground @JvmOverloads constructor( context: Context, attrs: AttributeSet, defStyleAttr: Int = 0 ) : AppCompatImageView(context, attrs, defStyleAttr), ViewWithForeground { private var foregroundDrawable: Drawable? = null private var gravity = Gravity.FILL private var foregroundInPadding = true private var foregroundBoundsChanged: Boolean = false private val bounds = Rect() private val overlayBounds = Rect() init { val a = context.obtainStyledAttributes(attrs, R.styleable.ImageViewWithForeground, defStyleAttr, 0) foregroundGravity = a.getInt(R.styleable.ImageViewWithForeground_android_foregroundGravity, gravity) val d = a.getDrawable(R.styleable.ImageViewWithForeground_android_foreground) if (d != null) { foreground = d } foregroundInPadding = a.getBoolean(R.styleable.ImageViewWithForeground_foregroundInsidePadding, true) a.recycle() } override fun foregroundGravity(): Int = gravity override fun setForegroundGravity(foregroundGravity: Int) { if (this.gravity == foregroundGravity) { return } var adjustedGravity = foregroundGravity if (adjustedGravity and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK == 0) { adjustedGravity = adjustedGravity or Gravity.START } if (adjustedGravity and Gravity.VERTICAL_GRAVITY_MASK == 0) { adjustedGravity = adjustedGravity or Gravity.TOP } this.gravity = adjustedGravity if (this.gravity == Gravity.FILL && foregroundDrawable != null) { val padding = Rect() foregroundDrawable!!.getPadding(padding) } requestLayout() } override fun verifyDrawable(drawable: Drawable): Boolean { return super.verifyDrawable(drawable) || drawable === foregroundDrawable } override fun jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState() foregroundDrawable?.jumpToCurrentState() } override fun drawableStateChanged() { super.drawableStateChanged() if (foregroundDrawable != null && foregroundDrawable!!.isStateful) { foregroundDrawable!!.state = drawableState } } /** * Supply a Drawable that is to be rendered on top of all of the child * views in the frame layout. Any padding in the Drawable will be taken * into account by ensuring that the children are inset to be placed * inside of the padding area. * * @param drawable The Drawable to be drawn on top of the children. */ override fun setForeground(drawable: Drawable?) { if (foregroundDrawable === drawable || drawable === null) { return } if (foregroundDrawable != null) { foregroundDrawable!!.callback = null unscheduleDrawable(foregroundDrawable) } foregroundDrawable = drawable drawable.callback = this if (drawable.isStateful) { drawable.state = drawableState } if (gravity == Gravity.FILL) { val padding = Rect() drawable.getPadding(padding) } requestLayout() invalidate() } /** * Returns the drawable used as the foreground of this FrameLayout. The * foreground drawable, if non-null, is always drawn on top of the children. * * @return A Drawable or null if no foreground was set. */ override fun foreground(): Drawable? = foregroundDrawable override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) foregroundBoundsChanged = changed } override fun draw(canvas: Canvas) { super.draw(canvas) if (foregroundDrawable == null) { return } val foreground = foregroundDrawable if (foregroundBoundsChanged) { foregroundBoundsChanged = false applyGravityTo(foreground!!) } foreground!!.draw(canvas) } private fun applyGravityTo(foreground: Drawable) { val selfBounds = bounds val w = right - left val h = bottom - top if (foregroundInPadding) { selfBounds.set(0, 0, w, h) } else { selfBounds.set(paddingLeft, paddingTop, w - paddingRight, h - paddingBottom) } Gravity.apply(gravity, foreground.intrinsicWidth, foreground.intrinsicHeight, selfBounds, overlayBounds) foreground.bounds = overlayBounds } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { foregroundBoundsChanged = true super.onSizeChanged(w, h, oldw, oldh) } override fun drawableHotspotChanged(x: Float, y: Float) { super.drawableHotspotChanged(x, y) foregroundDrawable?.setHotspot(x, y) } }
apache-2.0
5feb9cc0ff88817783fdabfcfb6f5aa0
30.605263
112
0.662781
4.804
false
false
false
false
hzsweers/CatchUp
app/src/main/kotlin/io/sweers/catchup/ui/widget/ForegroundLinearLayout.kt
1
5716
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.ui.widget import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.Gravity import android.widget.LinearLayout import io.sweers.catchup.R /** * From AppCompat's implementation */ class ForegroundLinearLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : LinearLayout(context, attrs, defStyle) { private val mSelfBounds = Rect() private val mOverlayBounds = Rect() private var mForegroundBoundsChanged = false private var mForeground: Drawable? = null private var mForegroundGravity = Gravity.FILL init { val a = context.obtainStyledAttributes(attrs, R.styleable.ForegroundView, defStyle, 0) mForegroundGravity = a.getInt( R.styleable.ForegroundView_android_foregroundGravity, mForegroundGravity ) a.getDrawable(R.styleable.ForegroundView_android_foreground)?.run { foreground = this } a.recycle() } /** * Describes how the foreground is positioned. * * @return foreground gravity. * @see .setForegroundGravity */ override fun getForegroundGravity(): Int { return mForegroundGravity } /** * Describes how the foreground is positioned. Defaults to START and TOP. * * @param foregroundGravity See [android.view.Gravity] * @see getForegroundGravity */ override fun setForegroundGravity(foregroundGravity: Int) { var foregroundGravityMutable = foregroundGravity if (mForegroundGravity != foregroundGravityMutable) { if (foregroundGravityMutable and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK == 0) { foregroundGravityMutable = foregroundGravityMutable or Gravity.START } if (foregroundGravityMutable and Gravity.VERTICAL_GRAVITY_MASK == 0) { foregroundGravityMutable = foregroundGravityMutable or Gravity.TOP } mForegroundGravity = foregroundGravityMutable if (mForegroundGravity == Gravity.FILL && mForeground != null) { val padding = Rect() mForeground!!.getPadding(padding) } requestLayout() } } override fun verifyDrawable(who: Drawable): Boolean { return super.verifyDrawable(who) || who === mForeground } override fun jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState() mForeground?.run { jumpToCurrentState() } } override fun drawableStateChanged() { super.drawableStateChanged() mForeground?.run { if (isStateful) { state = drawableState } } } /** * Returns the drawable used as the foreground of this FrameLayout. The * foreground drawable, if non-null, is always drawn on top of the children. * * @return A Drawable or null if no foreground was set. */ override fun getForeground(): Drawable? { return mForeground } /** * Supply a Drawable that is to be rendered on top of all of the child * views in the frame layout. Any padding in the Drawable will be taken * into account by ensuring that the children are inset to be placed * inside of the padding area. * * @param drawable The Drawable to be drawn on top of the children. */ override fun setForeground(drawable: Drawable?) { if (mForeground !== drawable) { if (mForeground != null) { mForeground!!.callback = null unscheduleDrawable(mForeground) } mForeground = drawable if (drawable != null) { setWillNotDraw(false) drawable.callback = this if (drawable.isStateful) { drawable.state = drawableState } if (mForegroundGravity == Gravity.FILL) { val padding = Rect() drawable.getPadding(padding) } } else { setWillNotDraw(true) } requestLayout() invalidate() } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) mForegroundBoundsChanged = mForegroundBoundsChanged or changed } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) mForegroundBoundsChanged = true } override fun draw(canvas: Canvas) { super.draw(canvas) mForeground?.run { if (mForegroundBoundsChanged) { mForegroundBoundsChanged = false val selfBounds = mSelfBounds val overlayBounds = mOverlayBounds val w = right - left val h = bottom - top selfBounds.set( paddingLeft, paddingTop, w - paddingRight, h - paddingBottom ) Gravity.apply( mForegroundGravity, intrinsicWidth, intrinsicHeight, selfBounds, overlayBounds ) bounds = overlayBounds } draw(canvas) } } override fun drawableHotspotChanged(x: Float, y: Float) { super.drawableHotspotChanged(x, y) mForeground?.run { setHotspot(x, y) } } }
apache-2.0
8741000f055e0cfa979614e1409f3706
26.882927
90
0.675297
4.500787
false
false
false
false
GunoH/intellij-community
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereContributorFeaturesProvider.kt
7
2990
package com.intellij.ide.actions.searcheverywhere.ml.features import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.SearchEverywhereMixedListInfo import com.intellij.ide.actions.searcheverywhere.ml.features.statistician.SearchEverywhereContributorStatistician import com.intellij.internal.statistic.eventLog.events.EventField import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair internal class SearchEverywhereContributorFeaturesProvider { companion object { internal val SE_TABS = listOf( "SearchEverywhereContributor.All", "ClassSearchEverywhereContributor", "FileSearchEverywhereContributor", "RecentFilesSEContributor", "SymbolSearchEverywhereContributor", "ActionSearchEverywhereContributor", "RunConfigurationsSEContributor", "CommandsContributor", "TopHitSEContributor", "com.intellij.ide.actions.searcheverywhere.CalculatorSEContributor", "TmsSearchEverywhereContributor", "YAMLKeysSearchEverywhereContributor", "UrlSearchEverywhereContributor", "Vcs.Git", "AutocompletionContributor", "TextSearchContributor", "DbSETablesContributor", "third.party" ) private val CONTRIBUTOR_INFO_ID = EventFields.String("id", SE_TABS) private val CONTRIBUTOR_PRIORITY = EventFields.Int("priority") private val CONTRIBUTOR_WEIGHT = EventFields.Int("weight") private val CONTRIBUTOR_IS_MOST_POPULAR = EventFields.Boolean("isMostPopular") private val CONTRIBUTOR_POPULARITY_INDEX = EventFields.Int("popularityIndex") fun getFeaturesDeclarations(): List<EventField<*>> = listOf( CONTRIBUTOR_INFO_ID, CONTRIBUTOR_PRIORITY, CONTRIBUTOR_WEIGHT, CONTRIBUTOR_IS_MOST_POPULAR, CONTRIBUTOR_POPULARITY_INDEX ) } fun getFeatures(contributor: SearchEverywhereContributor<*>, mixedListInfo: SearchEverywhereMixedListInfo): List<EventPair<*>> { val info = arrayListOf<EventPair<*>>( CONTRIBUTOR_INFO_ID.with(contributor.searchProviderId), CONTRIBUTOR_WEIGHT.with(contributor.sortWeight), ) mixedListInfo.contributorPriorities[contributor.searchProviderId]?.let { priority -> info.add(CONTRIBUTOR_PRIORITY.with(priority)) } return info + getStatisticianFeatures(contributor) } private fun getStatisticianFeatures(contributor: SearchEverywhereContributor<*>): List<EventPair<*>> { val contributorId = contributor.searchProviderId val statistics = SearchEverywhereContributorStatistician.getStatistics() val isMostPopular = statistics.contributorUsage.firstOrNull()?.first?.equals(contributorId) ?: return emptyList() val popularityIndex = statistics.contributorUsage.indexOfFirst { it.first == contributorId }.takeIf { it >= 0 } ?: return emptyList() return listOf( CONTRIBUTOR_IS_MOST_POPULAR.with(isMostPopular), CONTRIBUTOR_POPULARITY_INDEX.with(popularityIndex), ) } }
apache-2.0
56c54e703d55d6f5192de2418af0dea5
48.85
137
0.784615
4.942149
false
false
false
false
TonnyL/Mango
app/src/main/java/io/github/tonnyl/mango/database/AppDatabase.kt
1
2395
/* * Copyright (c) 2017 Lizhaotailang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.tonnyl.mango.database import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context import io.github.tonnyl.mango.data.AccessToken import io.github.tonnyl.mango.data.User import io.github.tonnyl.mango.database.dao.AccessTokenDao import io.github.tonnyl.mango.database.dao.UserDao /** * Created by lizhaotailang on 2017/6/28. */ @Database(entities = [(AccessToken::class), (User::class)], version = 1, exportSchema = true) abstract class AppDatabase : RoomDatabase() { companion object { private val DATABASE_NAME = "mango-db" private var INSTANCE: AppDatabase? = null private val lock = Any() fun getInstance(context: Context): AppDatabase { synchronized(lock) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, DATABASE_NAME ).build() } return INSTANCE as AppDatabase } } } abstract fun accessTokenDao(): AccessTokenDao abstract fun userDao(): UserDao }
mit
caf157761c0585f548765aed2e02b07d
35.861538
93
0.699374
4.686888
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/CacheJvm.kt
1
7848
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.sessions import io.ktor.util.collections.* import kotlinx.coroutines.* import java.lang.ref.* import java.util.* import java.util.concurrent.* import java.util.concurrent.locks.* import kotlin.concurrent.* import kotlin.coroutines.* internal interface CacheReference<out K> { val key: K } internal open class ReferenceCache<K : Any, V : Any, out R>( val calc: suspend (K) -> V, val wrapFunction: (K, V, ReferenceQueue<V>) -> R ) : Cache<K, V> where R : Reference<V>, R : CacheReference<K> { private val queue = ReferenceQueue<V>() private val container = BaseCache { key: K -> forkThreadIfNeeded(); wrapFunction(key, calc(key), queue) } private val workerThread by lazy { Thread(ReferenceWorker(container, queue)).apply { isDaemon = true; start() } } override suspend fun getOrCompute(key: K): V { val ref = container.getOrCompute(key) val value = ref.get() if (value == null) { if (container.invalidate(key, ref)) { ref.enqueue() } return getOrCompute(key) } return value } override fun peek(key: K): V? = container.peek(key)?.get() override fun invalidate(key: K): V? = container.invalidate(key)?.get() override fun invalidate(key: K, value: V): Boolean { val ref = container.peek(key) if (ref?.get() == value) { ref.enqueue() return container.invalidate(key, ref) } return false } override fun invalidateAll() { container.invalidateAll() } private fun forkThreadIfNeeded() { if (!workerThread.isAlive) { throw IllegalStateException("Daemon thread is already dead") } } } private class ReferenceWorker<out K : Any, R : CacheReference<K>> constructor( owner: Cache<K, R>, val queue: ReferenceQueue<*> ) : Runnable { private val owner = WeakReference(owner) override fun run() { do { val ref = queue.remove(60000) if (ref is CacheReference<*>) { @Suppress("UNCHECKED_CAST") val cast = ref as R val currentOwner = owner.get() ?: break currentOwner.invalidate(cast.key, cast) } } while (!Thread.interrupted() && owner.get() != null) } } internal class CacheSoftReference<out K, V>(override val key: K, value: V, queue: ReferenceQueue<V>) : SoftReference<V>(value, queue), CacheReference<K> internal class CacheWeakReference<out K, V>(override val key: K, value: V, queue: ReferenceQueue<V>) : WeakReference<V>(value, queue), CacheReference<K> internal class SoftReferenceCache<K : Any, V : Any>(calc: suspend (K) -> V) : ReferenceCache<K, V, CacheSoftReference<K, V>>(calc, { k, v, q -> CacheSoftReference(k, v, q) }) internal class WeakReferenceCache<K : Any, V : Any>( calc: suspend (K) -> V ) : ReferenceCache<K, V, CacheWeakReference<K, V>>(calc, { k, v, q -> CacheWeakReference(k, v, q) }) internal class BaseTimeoutCache<in K : Any, V : Any> constructor( private val timeoutValue: Long, private val touchOnGet: Boolean, private val delegate: Cache<K, V> ) : Cache<K, V> { private val lock = ReentrantLock() private val cond = lock.newCondition() private val items = PullableLinkedList<KeyState<K>>() private val map = WeakHashMap<K, KeyState<K>>() private val workerThread by lazy { Thread(TimeoutWorker(this, lock, cond, items)).apply { isDaemon = true; start() } } override suspend fun getOrCompute(key: K): V { if (touchOnGet) { pull(key) } return delegate.getOrCompute(key) } override fun peek(key: K): V? { if (touchOnGet) { pull(key, create = false) } return delegate.peek(key) } override fun invalidate(key: K): V? { remove(key) return delegate.invalidate(key) } override fun invalidate(key: K, value: V): Boolean { if (delegate.invalidate(key, value)) { remove(key) return true } return false } override fun invalidateAll() { delegate.invalidateAll() lock.withLock { items.clear() cond.signalAll() } } private fun forkIfNeeded() { if (!items.isEmpty() && !workerThread.isAlive) { throw IllegalStateException("Daemon thread is already dead") } } private fun pull(key: K, create: Boolean = true) { lock.withLock { val state = if (create) map.getOrPut(key) { KeyState(key, timeoutValue) } else map[key] if (state != null) { state.touch() items.pull(state) cond.signalAll() } } forkIfNeeded() } private fun remove(key: K) { lock.withLock { map.remove(key)?.let { items.remove(it) cond.signalAll() } } } } private class KeyState<K>(key: K, val timeout: Long) : ListElement<KeyState<K>>() { val key: WeakReference<K> = WeakReference(key) var lastAccess = System.currentTimeMillis() fun touch() { lastAccess = System.currentTimeMillis() } fun timeToWait() = 0L.coerceAtLeast(lastAccess + timeout - System.currentTimeMillis()) } private class TimeoutWorker<K : Any>( owner: BaseTimeoutCache<K, *>, val lock: ReentrantLock, val cond: Condition, val items: PullableLinkedList<KeyState<K>> ) : Runnable { private val owner = WeakReference(owner) override fun run() { do { lock.withLock { val item = head() if (item != null) { val time = item.timeToWait() if (time == 0L) { items.remove(item) val k = item.key.get() if (k != null) { owner.get()?.invalidate(k) } } else { cond.await(time, TimeUnit.MILLISECONDS) } } } } while (!Thread.interrupted() && owner.get() != null) } private fun head() = lock.withLock { while (items.isEmpty() && owner.get() != null) { cond.await(60, TimeUnit.SECONDS) } if (owner.get() == null) null else items.head() } } private abstract class ListElement<E : ListElement<E>> { var next: E? = null var prev: E? = null } private class PullableLinkedList<E : ListElement<E>> { private var head: E? = null private var tail: E? = null fun isEmpty() = head == null fun take(): E = head().apply { remove(this) } fun head(): E = head ?: throw NoSuchElementException() fun add(element: E) { require(element.next == null) require(element.prev == null) val oldHead = head if (oldHead != null) { element.next = oldHead oldHead.prev = element } head = element if (tail == null) { tail = element } } fun remove(element: E) { if (element == head) { head = null } if (element == tail) { tail = null } element.prev?.next = element.next element.next = null element.prev = null } fun clear() { head = null tail = null } fun pull(element: E) { if (element !== head) { remove(element) add(element) } } }
apache-2.0
03605177d12128f5be893be0e6400216
27.028571
119
0.555683
4.121849
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/analytics/LegendEvaluator.kt
1
5379
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.analytics import javax.inject.Inject import org.hisp.dhis.android.core.dataelement.DataElementCollectionRepository import org.hisp.dhis.android.core.indicator.IndicatorCollectionRepository import org.hisp.dhis.android.core.legendset.LegendCollectionRepository import org.hisp.dhis.android.core.program.ProgramIndicatorCollectionRepository import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeCollectionRepository @Suppress("TooGenericExceptionCaught") internal class LegendEvaluator @Inject constructor( private val dataElementRepository: DataElementCollectionRepository, private val programIndicatorRepository: ProgramIndicatorCollectionRepository, private val indicatorRepository: IndicatorCollectionRepository, private val legendRepository: LegendCollectionRepository, private val trackedEntityAttributeCollectionRepository: TrackedEntityAttributeCollectionRepository, ) { fun getLegendByProgramIndicator( programIndicatorUid: String, value: String? ): String? { return if (value == null) { null } else try { val programIndicator = programIndicatorRepository .byUid().eq(programIndicatorUid) .withLegendSets() .one().blockingGet() val legendSet = programIndicator.legendSets()!![0] return getLegendByLegendSet(legendSet.uid(), value) } catch (e: Exception) { null } } fun getLegendByDataElement( dataElementUid: String, value: String? ): String? { return if (value == null) { null } else try { val dataElement = dataElementRepository .byUid().eq(dataElementUid) .withLegendSets() .one().blockingGet() val legendSet = dataElement.legendSets()!![0] return getLegendByLegendSet(legendSet.uid(), value) } catch (e: Exception) { null } } @Suppress("UnusedPrivateMember", "FunctionOnlyReturningConstant") fun getLegendByTrackedEntityAttribute( trackedEntityAttributeUid: String, value: String? ): String? { return if (value == null) { null } else try { val trackedEntityAttribute = trackedEntityAttributeCollectionRepository .byUid().eq(trackedEntityAttributeUid) .withLegendSets() .one().blockingGet() val legendSet = trackedEntityAttribute.legendSets()!![0] return getLegendByLegendSet(legendSet.uid(), value) } catch (e: Exception) { null } } fun getLegendByIndicator( indicatorUid: String, value: String? ): String? { return if (value == null) { null } else try { val indicator = indicatorRepository .byUid().eq(indicatorUid) .withLegendSets() .one().blockingGet() val legendSet = indicator.legendSets()!![0] return getLegendByLegendSet(legendSet.uid(), value) } catch (e: Exception) { null } } fun getLegendByLegendSet( legendSetUid: String, value: String? ): String? { return if (value == null || value.toDouble().isNaN()) { null } else try { return legendRepository .byStartValue().smallerThan(value.toDouble()) .byEndValue().biggerOrEqualTo(value.toDouble()) .byLegendSet().eq(legendSetUid) .one() .blockingGet().uid() } catch (e: Exception) { null } } }
bsd-3-clause
f3f03e4283c9ec67c5f042d5dec9932c
36.096552
103
0.656999
5.036517
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/utils/keyboardwatcher/KeyboardWatcher.kt
1
4647
package com.ashish.movieguide.utils.keyboardwatcher import android.app.Activity import android.graphics.Rect import android.view.MotionEvent import android.view.View import android.view.ViewTreeObserver import android.view.Window import android.widget.EditText import com.ashish.movieguide.di.scopes.ActivityScope import com.ashish.movieguide.utils.extensions.hideKeyboard import javax.inject.Inject /** * Created by Ashish on Jan 08. */ @ActivityScope class KeyboardWatcher @Inject constructor( private val activity: Activity ) : ViewTreeObserver.OnGlobalLayoutListener { companion object { private const val MIN_KEYBOARD_HEIGHT_PX = 150 } private val coordinates = IntArray(2) private val touchRect: Rect = Rect() private val visibleFrameRect: Rect = Rect() private lateinit var decorView: View private var focusedView: View? = null private var lastVisibleDecorViewHeight: Int = 0 private var touchWasInsideFocusedView: Boolean = false private var listener: KeyboardVisibilityListener? = null fun watchKeyboard(listener: KeyboardVisibilityListener) { this.listener = listener val content = activity.findViewById(Window.ID_ANDROID_CONTENT) content.isFocusable = true content.isFocusableInTouchMode = true decorView = activity.window.decorView decorView.viewTreeObserver.addOnGlobalLayoutListener(this) activity.application.registerActivityLifecycleCallbacks(object : AutoActivityLifecycleCallbacks(activity) { override fun onTargetActivityDestroyed() { removeListener() } }) } internal fun removeListener() { listener = null decorView.viewTreeObserver.removeOnGlobalLayoutListener(this) } override fun onGlobalLayout() { if (listener != null) { decorView.getWindowVisibleDisplayFrame(visibleFrameRect) val visibleDecorViewHeight = visibleFrameRect.height() // Decide whether keyboard is visible from changing decor view height. if (lastVisibleDecorViewHeight != 0) { if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) { val currentKeyboardHeight = decorView.height - visibleFrameRect.bottom listener!!.onKeyboardShown(currentKeyboardHeight) } else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) { listener!!.onKeyboardHidden() } } // Save current decor view height for the next call lastVisibleDecorViewHeight = visibleDecorViewHeight } } fun dispatchEditTextTouchEvent(event: MotionEvent, dispatchTouchEvent: Boolean): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { focusedView = activity.currentFocus if (focusedView != null) { focusedView!!.getLocationOnScreen(coordinates) touchRect.set(coordinates[0], coordinates[1], coordinates[0] + focusedView!!.width, coordinates[1] + focusedView!!.height) touchWasInsideFocusedView = touchRect.contains(event.x.toInt(), event.y.toInt()) } } MotionEvent.ACTION_UP -> if (focusedView != null) { // Dispatch to allow new view to (potentially) take focus val currentFocus = activity.currentFocus /* If the focus is still on the original view and the touch was inside that view, leave the keyboard open. Otherwise, if the focus is now on another view and that view is an EditText, also leave the keyboard open. */ if (focusedView == currentFocus) { if (touchWasInsideFocusedView) return dispatchTouchEvent } else if (currentFocus is EditText) { return dispatchTouchEvent } /* If the touch was outside the originally focused view and not inside another EditText, so close the keyboard */ activity.hideKeyboard() focusedView!!.clearFocus() return dispatchTouchEvent } } return dispatchTouchEvent } interface KeyboardVisibilityListener { fun onKeyboardShown(keyboardHeight: Int) fun onKeyboardHidden() } }
apache-2.0
1700775165ab210e8e895498c4268866
35.3125
115
0.633742
5.687882
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/utility/MinecraftPlayerMembers.kt
1
4699
/* * Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.utility import com.mcmoonlake.api.Valuable import com.mcmoonlake.api.entity.Entities import com.mcmoonlake.api.gui.Containers import com.mcmoonlake.api.reflect.accessor.AccessorField import com.mcmoonlake.api.reflect.accessor.Accessors import com.mojang.authlib.GameProfile import io.netty.channel.Channel import org.bukkit.entity.Player enum class MinecraftPlayerMembers( val clazz: Class<*> ) : Valuable<String> { /** * Minecraft Entity Player Field Member: Ping (实体玩家字段成员: 延迟) */ PING(Int::class.java) { override fun value(): String = "ping" }, /** * Minecraft Entity Player Field Member: Locale (实体玩家字段成员: 本地化) */ LOCALE(String::class.java) { override fun value(): String = "locale" }, /** * Minecraft Entity Player Field Member: Connection (实体玩家字段成员: 连接) */ CONNECTION(MinecraftReflection.playerConnectionClass) { override fun value(): String = "playerConnection" override fun get(): () -> AccessorField { return try { super.get() } catch(e: NoSuchFieldException) { { Accessors.getAccessorField(MinecraftReflection.entityPlayerClass, clazz, true) } } } }, /** * Minecraft Entity Player Field Member: Network Manager (实体玩家字段成员: 网络管理器) * - Parent: [CONNECTION] */ NETWORK_MANAGER(MinecraftReflection.networkManagerClass) { // parent = connection override fun value(): String = "networkManager" override fun get(): () -> AccessorField = { Accessors.getAccessorField(MinecraftReflection.playerConnectionClass, clazz, true) } override fun get(player: Player): Any? = field.get(CONNECTION.get(player)) override fun set(player: Player, value: Any?) = field.set(CONNECTION.get(player), value) }, /** * Minecraft Entity Player Field Member: Channel (实体玩家字段成员: 通道) * - Parent: [NETWORK_MANAGER] */ CHANNEL(Channel::class.java) { // parent = networkManager override fun value(): String = "channel" override fun get(): () -> AccessorField = { Accessors.getAccessorField(MinecraftReflection.networkManagerClass, clazz, true) } override fun get(player: Player): Any? = field.get(NETWORK_MANAGER.get(player)) override fun set(player: Player, value: Any?) = field.set(NETWORK_MANAGER.get(player), value) }, /** * Minecraft Entity Player Field Member: Profile (实体玩家字段成员: 简介) */ PROFILE(GameProfile::class.java) { override fun value(): String = "profile" override fun get(): () -> AccessorField = { Accessors.getAccessorField(MinecraftReflection.entityHumanClass, clazz, true) } }, /** * Minecraft Entity Player Field Member: Active Container (实体玩家字段成员: 交互容器) */ ACTIVE_CONTAINER(Containers.containerClass) { override fun value(): String = "activeContainer" } ; protected val field: AccessorField get() = cachedMap.getOrPut(this, get()) open fun get(player: Player): Any? = field.get(Entities.asNMSEntity(player)) open fun set(player: Player, value: Any?) = field.set(Entities.asNMSEntity(player), value) protected open fun get(): () -> AccessorField = { Accessors.getAccessorField(MinecraftReflection.entityPlayerClass, value(), true) } companion object { @JvmStatic private val cachedMap: MutableMap<MinecraftPlayerMembers, AccessorField> by lazy { HashMap<MinecraftPlayerMembers, AccessorField>() } } }
gpl-3.0
0f4d042c751339e88e6b4289df63048e
35.087302
104
0.638883
4.397485
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/settings/SettingsPreferenceLoader.kt
1
6567
package org.wikipedia.settings import android.content.DialogInterface import android.content.Intent import androidx.appcompat.app.AlertDialog import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreferenceCompat import com.microsoft.appcenter.AppCenter import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.LoginFunnel import org.wikipedia.auth.AccountUtil.isLoggedIn import org.wikipedia.auth.AccountUtil.userName import org.wikipedia.feed.configure.ConfigureActivity import org.wikipedia.login.LoginActivity import org.wikipedia.readinglist.sync.ReadingListSyncAdapter import org.wikipedia.settings.languages.WikipediaLanguagesActivity import org.wikipedia.theme.ThemeFittingRoomActivity.Companion.newIntent /** UI code for app settings used by PreferenceFragment. */ internal class SettingsPreferenceLoader(fragment: PreferenceFragmentCompat) : BasePreferenceLoader(fragment) { override fun loadPreferences() { loadPreferences(R.xml.preferences) if (ReadingListSyncAdapter.isDisabledByRemoteConfig) { findPreference(R.string.preference_category_sync).isVisible = false findPreference(R.string.preference_key_sync_reading_lists).isVisible = false } findPreference(R.string.preference_key_sync_reading_lists).onPreferenceChangeListener = SyncReadingListsListener() findPreference(R.string.preference_key_eventlogging_opt_in).onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference, newValue: Any -> if (!(newValue as Boolean)) { Prefs.setAppInstallId(null) } true } loadPreferences(R.xml.preferences_about) updateLanguagePrefSummary() findPreference(R.string.preference_key_language).onPreferenceClickListener = Preference.OnPreferenceClickListener { activity.startActivityForResult(WikipediaLanguagesActivity.newIntent(activity, Constants.InvokeSource.SETTINGS), Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE) true } findPreference(R.string.preference_key_customize_explore_feed).onPreferenceClickListener = Preference.OnPreferenceClickListener { activity.startActivityForResult(ConfigureActivity.newIntent(activity, Constants.InvokeSource.NAV_MENU.ordinal), Constants.ACTIVITY_REQUEST_FEED_CONFIGURE) true } findPreference(R.string.preference_key_color_theme).let { it.setSummary(WikipediaApp.getInstance().currentTheme.nameId) it.onPreferenceClickListener = Preference.OnPreferenceClickListener { activity.startActivity(newIntent(activity)) true } } findPreference(R.string.preference_key_about_wikipedia_app).onPreferenceClickListener = Preference.OnPreferenceClickListener { activity.startActivity(Intent(activity, AboutActivity::class.java)) true } findPreference(R.string.preference_key_auto_upload_crash_reports).onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference, newValue: Any? -> AppCenter.setEnabled((newValue as Boolean?)!!) true } } fun updateLanguagePrefSummary() { // TODO: resolve RTL vs LTR with multiple languages (e.g. list contains English and Hebrew) findPreference(R.string.preference_key_language).summary = WikipediaApp.getInstance().language().appLanguageLocalizedNames } private inner class SyncReadingListsListener : Preference.OnPreferenceChangeListener { override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean { if (isLoggedIn) { if (newValue as Boolean) { (preference as SwitchPreferenceCompat).isChecked = true ReadingListSyncAdapter.setSyncEnabledWithSetup() } else { AlertDialog.Builder(activity) .setTitle(activity.getString(R.string.preference_dialog_of_turning_off_reading_list_sync_title, userName)) .setMessage(activity.getString(R.string.preference_dialog_of_turning_off_reading_list_sync_text, userName)) .setPositiveButton(R.string.reading_lists_confirm_remote_delete_yes, DeleteRemoteListsYesListener(preference)) .setNegativeButton(R.string.reading_lists_confirm_remote_delete_no, null) .show() } } else { AlertDialog.Builder(activity) .setTitle(R.string.reading_list_preference_login_to_enable_sync_dialog_title) .setMessage(R.string.reading_list_preference_login_to_enable_sync_dialog_text) .setPositiveButton(R.string.reading_list_preference_login_to_enable_sync_dialog_login ) { _: DialogInterface, _: Int -> val loginIntent = LoginActivity.newIntent(activity, LoginFunnel.SOURCE_SETTINGS) activity.startActivity(loginIntent) } .setNegativeButton(R.string.reading_list_preference_login_to_enable_sync_dialog_cancel, null) .show() } // clicks are handled and preferences updated accordingly; don't pass the result through return false } } fun updateSyncReadingListsPrefSummary() { findPreference(R.string.preference_key_sync_reading_lists).let { if (isLoggedIn) { it.summary = activity.getString(R.string.preference_summary_sync_reading_lists_from_account, userName) } else { it.setSummary(R.string.preference_summary_sync_reading_lists) } } } private inner class DeleteRemoteListsYesListener(private val preference: Preference) : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, which: Int) { (preference as SwitchPreferenceCompat).isChecked = false Prefs.setReadingListSyncEnabled(false) Prefs.setReadingListsRemoteSetupPending(false) Prefs.setReadingListsRemoteDeletePending(true) ReadingListSyncAdapter.manualSync() } } }
apache-2.0
8151ddec6fdd15a295b0fffce480cfc7
52.827869
175
0.679306
5.278939
false
false
false
false
Pinkal7600/Todo
app/src/main/java/com/pinkal/todo/category/adapter/CategoryAdapter.kt
1
3456
package com.pinkal.todo.category.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.pinkal.todo.R import com.pinkal.todo.category.`interface`.CategoryDelete import com.pinkal.todo.category.`interface`.CategoryIsEmpty import com.pinkal.todo.category.`interface`.CategoryUpdate import com.pinkal.todo.category.model.CategoryModel import com.pinkal.todo.utils.dialogDeleteCategory import com.pinkal.todo.utils.dialogUpdateCategory import kotlinx.android.synthetic.main.row_category.view.* /** * Created by Pinkal on 25/5/17. */ class CategoryAdapter(val mContext: Context, mArrayList: ArrayList<CategoryModel>, categoryIsEmpty: CategoryIsEmpty) : RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), CategoryUpdate, CategoryDelete { val TAG = CategoryAdapter::class.java.simpleName!! var mArrayList: ArrayList<CategoryModel> = ArrayList() var inflater: LayoutInflater var isEmpty: CategoryIsEmpty = categoryIsEmpty init { this.mArrayList = mArrayList inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } /** * Binding views with Adapter * */ override fun onBindViewHolder(holder: ViewHolder?, position: Int) { holder!!.txtCategoryName.text = mArrayList[position].categoryName holder.imgEditCategory.setOnClickListener({ dialogUpdateCategory(mContext, mArrayList[position].id!!, this) }) holder.imgDeleteCategory.setOnClickListener({ dialogDeleteCategory(mContext, mArrayList[position].id!!, this) }) } override fun getItemCount(): Int { Log.e(TAG, "size : " + mArrayList.size) if (mArrayList.size == 0) { isEmpty.categoryIsEmpty(true) } else { isEmpty.categoryIsEmpty(false) } return mArrayList.size } /** * Clear list data * */ fun clearAdapter() { this.mArrayList.clear() notifyDataSetChanged() } /** * Set new data list * */ fun setList(mArrayList: ArrayList<CategoryModel>) { this.mArrayList = mArrayList notifyDataSetChanged() } /** * Inflating layout * */ override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { val mView = LayoutInflater.from(mContext).inflate(R.layout.row_category, parent, false) return ViewHolder(mView) } /** * update list when category is updated * */ override fun isCategoryUpdated(isUpdated: Boolean, mArrayList: ArrayList<CategoryModel>) { clearAdapter() setList(mArrayList) } /** * update list when category is deleted * */ override fun isCategoryDeleted(isDeleted: Boolean, mArrayList: ArrayList<CategoryModel>) { if (isDeleted) { clearAdapter() setList(mArrayList) } } /** * @ViewHolder class * initialize view * */ class ViewHolder(view: View?) : RecyclerView.ViewHolder(view) { val txtCategoryName: TextView = view!!.txtCategoryName val imgEditCategory: ImageView = view!!.imgEditCategory val imgDeleteCategory: ImageView = view!!.imgDeleteCategory } }
apache-2.0
de9b04e7aa68a61cdf48b9de910fcb20
29.866071
118
0.681424
4.547368
false
false
false
false
orauyeu/SimYukkuri
subprojects/simyukkuri/src/main/kotlin/simyukkuri/geometry/SizeXY.kt
1
632
package simyukkuri.geometry /** * xy平面上の不変な大きさ. */ data class SizeXY(override val width: Double, override val height: Double) : HasSizeXY { override val size get() = this operator fun times(k: Double): SizeXY = multiply(k, k) operator fun div(k: Double): SizeXY = multiply(1 / k, 1 / k) /** 各方向に指定された値を掛けた大きさを返す. */ fun multiply(x: Double, y: Double) = SizeXY(width * x, height * y) /** 奥行きを加えて3次元の大きさを作る. */ fun insertDepth(depth: Double) = Size3(width, height, depth) }
apache-2.0
9d7c42a85e39104b4b337b4d36761d82
22.545455
88
0.616667
2.903226
false
false
false
false
kaif-open/kaif-android
app/src/main/kotlin/io/kaif/mobile/view/HonorActivity.kt
1
2019
package io.kaif.mobile.view import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.AppBarLayout import io.kaif.mobile.R import io.kaif.mobile.app.BaseActivity import org.jetbrains.anko.* import org.jetbrains.anko.appcompat.v7.themedToolbar import org.jetbrains.anko.design.coordinatorLayout import org.jetbrains.anko.design.themedAppBarLayout class HonorActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) HonorActivityUI().setContentView(this) setSupportActionBar(find(io.kaif.mobile.R.id.tool_bar)) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.content_frame, HonorFragment.newInstance()) .commit() } } } class HonorActivityIntent(context: Context) : Intent(context, HonorActivity::class.java) class HonorActivityUI : AnkoComponent<HonorActivity> { override fun createView(ui: AnkoContext<HonorActivity>) = with(ui) { coordinatorLayout { lparams(width = matchParent, height = matchParent) themedAppBarLayout { lparams(width = matchParent, height = wrapContent) themedToolbar(R.style.ThemeOverlay_AppCompat_Dark_ActionBar) { id = io.kaif.mobile.R.id.tool_bar popupTheme = R.style.ThemeOverlay_AppCompat_Light title = resources.getString(R.string.honor) }.lparams(width = matchParent, height = wrapContent) { scrollFlags = R.id.enterAlways } } frameLayout { id = io.kaif.mobile.R.id.content_frame }.lparams(width = matchParent, height = matchParent) { behavior = AppBarLayout.ScrollingViewBehavior() } } } }
apache-2.0
4b4d7dbcda2327aedf9f16c2cce8cb50
37.826923
88
0.653789
4.695349
false
false
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestPreviewComponent.kt
1
1659
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import com.intellij.openapi.Disposable import com.intellij.ui.OnePixelSplitter import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestDataProvider internal class GithubPullRequestPreviewComponent(private val changes: GithubPullRequestChangesComponent, private val details: GithubPullRequestDetailsComponent) : OnePixelSplitter("Github.PullRequest.Preview.Component", 0.5f), Disposable { private var currentProvider: GithubPullRequestDataProvider? = null private val requestChangesListener = object : GithubPullRequestDataProvider.RequestsChangedListener { override fun detailsRequestChanged() { details.loadAndShow(currentProvider!!.detailsRequest) } override fun commitsRequestChanged() { changes.loadAndShow(currentProvider!!.logCommitsRequest) } } init { firstComponent = details secondComponent = changes } fun setPreviewDataProvider(provider: GithubPullRequestDataProvider?) { val previousNumber = currentProvider?.number currentProvider?.removeRequestsChangesListener(requestChangesListener) currentProvider = provider currentProvider?.addRequestsChangesListener(requestChangesListener) if (previousNumber != provider?.number) { details.reset() changes.reset() } details.loadAndShow(provider?.detailsRequest) changes.loadAndShow(provider?.logCommitsRequest) } override fun dispose() {} }
apache-2.0
ffb804bacf807e98987091bcd4e09b17
35.866667
140
0.764316
5.300319
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/icons/HaskellIcons.kt
1
990
package org.jetbrains.haskell.icons import com.intellij.openapi.util.IconLoader import javax.swing.* /** * @author Evgeny.Kurbatsky */ object HaskellIcons { val HASKELL_BIG: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/haskell24.png") val HASKELL: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/haskell16.png") val DEFAULT: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/haskell16.png") val APPLICATION: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/application.png") @JvmField val CABAL: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/cabal.png") val BIG: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/haskell.png") val UPDATE: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/update.png") @JvmField val REPL: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/repl.png") @JvmField val HAMLET: Icon = IconLoader.getIcon("/org/jetbrains/haskell/icons/yesod16.png") }
apache-2.0
b381eae28f6b00ecf7e9dc90a144bbf0
42.043478
94
0.740404
3.639706
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/ExternalModuleImlFileEntitiesSerializer.kt
1
8971
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.impl.ModulePath import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.ExternalSystemModuleOptionsEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleCustomImlDataEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.getOrCreateExternalSystemModuleOptions import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.util.JpsPathUtil import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity private val MODULE_OPTIONS_TO_CHECK = setOf( "externalSystemModuleVersion", "linkedProjectPath", "linkedProjectId", "rootProjectPath", "externalSystemModuleGroup", "externalSystemModuleType" ) internal class ExternalModuleImlFileEntitiesSerializer(modulePath: ModulePath, fileUrl: VirtualFileUrl, virtualFileManager: VirtualFileUrlManager, internalEntitySource: JpsFileEntitySource, internalModuleListSerializer: JpsModuleListSerializer) : ModuleImlFileEntitiesSerializer(modulePath, fileUrl, internalEntitySource, virtualFileManager, internalModuleListSerializer) { override val skipLoadingIfFileDoesNotExist: Boolean get() = true override fun loadEntities(builder: MutableEntityStorage, reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { } override fun acceptsSource(entitySource: EntitySource): Boolean { return entitySource is JpsImportedEntitySource && entitySource.storedExternally } override fun readExternalSystemOptions(reader: JpsFileContentReader, moduleOptions: Map<String?, String?>): Pair<Map<String?, String?>, String?> { val componentTag = reader.loadComponent(fileUrl.url, "ExternalSystem", getBaseDirPath()) ?: return Pair(emptyMap(), null) val options = componentTag.attributes.associateBy({ it.name }, { it.value }) return Pair(options, options["externalSystem"]) } override fun loadExternalSystemOptions(builder: MutableEntityStorage, module: ModuleEntity, reader: JpsFileContentReader, externalSystemOptions: Map<String?, String?>, externalSystemId: String?, entitySource: EntitySource) { if (!shouldCreateExternalSystemModuleOptions(externalSystemId, externalSystemOptions, MODULE_OPTIONS_TO_CHECK)) return val optionsEntity = builder.getOrCreateExternalSystemModuleOptions(module, entitySource) builder.modifyEntity(optionsEntity) { externalSystem = externalSystemId externalSystemModuleVersion = externalSystemOptions["externalSystemModuleVersion"] linkedProjectPath = externalSystemOptions["linkedProjectPath"] linkedProjectId = externalSystemOptions["linkedProjectId"] rootProjectPath = externalSystemOptions["rootProjectPath"] externalSystemModuleGroup = externalSystemOptions["externalSystemModuleGroup"] externalSystemModuleType = externalSystemOptions["externalSystemModuleType"] } } override fun saveModuleOptions(externalSystemOptions: ExternalSystemModuleOptionsEntity?, moduleType: String?, customImlData: ModuleCustomImlDataEntity?, writer: JpsFileContentWriter) { val fileUrlString = fileUrl.url if (FileUtil.extensionEquals(fileUrlString, "iml")) { logger<ExternalModuleImlFileEntitiesSerializer>().error("External serializer should not write to iml files. Path:$fileUrlString") } if (externalSystemOptions != null) { val componentTag = JDomSerializationUtil.createComponentElement("ExternalSystem") fun saveOption(name: String, value: String?) { if (value != null) { componentTag.setAttribute(name, value) } } saveOption("externalSystem", externalSystemOptions.externalSystem) saveOption("externalSystemModuleGroup", externalSystemOptions.externalSystemModuleGroup) saveOption("externalSystemModuleType", externalSystemOptions.externalSystemModuleType) saveOption("externalSystemModuleVersion", externalSystemOptions.externalSystemModuleVersion) saveOption("linkedProjectId", externalSystemOptions.linkedProjectId) saveOption("linkedProjectPath", externalSystemOptions.linkedProjectPath) saveOption("rootProjectPath", externalSystemOptions.rootProjectPath) writer.saveComponent(fileUrlString, "ExternalSystem", componentTag) } if (moduleType != null || !customImlData?.customModuleOptions.isNullOrEmpty()) { val componentTag = JDomSerializationUtil.createComponentElement(DEPRECATED_MODULE_MANAGER_COMPONENT_NAME) if (moduleType != null) { componentTag.addContent(Element("option").setAttribute("key", "type").setAttribute("value", moduleType)) } customImlData?.customModuleOptions?.forEach{ (key, value) -> componentTag.addContent(Element("option").setAttribute("key", key).setAttribute("value", value)) } writer.saveComponent(fileUrlString, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, componentTag) } } override fun createExternalEntitySource(externalSystemId: String) = JpsImportedEntitySource(internalEntitySource, externalSystemId, true) override fun createFacetSerializer(): FacetsSerializer { return FacetsSerializer(fileUrl, internalEntitySource, "ExternalFacetManager", getBaseDirPath(), true) } override fun getBaseDirPath(): String { return modulePath.path } override fun toString(): String = "ExternalModuleImlFileEntitiesSerializer($fileUrl)" } internal class ExternalModuleListSerializer(private val externalStorageRoot: VirtualFileUrl, private val virtualFileManager: VirtualFileUrlManager) : ModuleListSerializerImpl(externalStorageRoot.append("project/modules.xml").url, virtualFileManager) { override val isExternalStorage: Boolean get() = true override val componentName: String get() = "ExternalProjectModuleManager" override val entitySourceFilter: (EntitySource) -> Boolean get() = { it is JpsImportedEntitySource && it.storedExternally } override fun getSourceToSave(module: ModuleEntity): JpsFileEntitySource.FileInDirectory? { return (module.entitySource as? JpsImportedEntitySource)?.internalFile as? JpsFileEntitySource.FileInDirectory } override fun getFileName(entity: ModuleEntity): String { return "${entity.name}.xml" } override fun createSerializer(internalSource: JpsFileEntitySource, fileUrl: VirtualFileUrl, moduleGroup: String?): JpsFileEntitiesSerializer<ModuleEntity> { val fileName = PathUtil.getFileName(fileUrl.url) val actualFileUrl = if (PathUtil.getFileExtension(fileName) == "iml") { externalStorageRoot.append("modules/${fileName.substringBeforeLast('.')}.xml") } else { fileUrl } val filePath = JpsPathUtil.urlToPath(fileUrl.url) return ExternalModuleImlFileEntitiesSerializer(ModulePath(filePath, moduleGroup), actualFileUrl, virtualFileManager, internalSource, this) } // Component DeprecatedModuleOptionManager removed by ModuleStateStorageManager.beforeElementSaved from .iml files override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { super.deleteObsoleteFile(fileUrl, writer) if (FileUtil.extensionEquals(fileUrl, "xml")) { writer.saveComponent(fileUrl, "ExternalSystem", null) writer.saveComponent(fileUrl, "ExternalFacetManager", null) writer.saveComponent(fileUrl, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null) writer.saveComponent(fileUrl, TEST_MODULE_PROPERTIES_COMPONENT_NAME, null) } } override fun toString(): String = "ExternalModuleListSerializer($fileUrl)" }
apache-2.0
c7d593031fa8ce0854889ef6f63d92e2
52.39881
158
0.735592
6.221221
false
false
false
false
zdary/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/action/ImportProjectFromScriptAction.kt
4
1806
// 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 org.jetbrains.plugins.gradle.action import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.externalSystem.action.ExternalSystemAction import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.plugins.gradle.service.project.open.linkAndRefreshGradleProject import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants class ImportProjectFromScriptAction: ExternalSystemAction() { override fun isEnabled(e: AnActionEvent): Boolean = true override fun isVisible(e: AnActionEvent): Boolean { val virtualFile = e.getData<VirtualFile>(CommonDataKeys.VIRTUAL_FILE) ?: return false val project = e.getData<Project>(CommonDataKeys.PROJECT) ?: return false return GradleConstants.KNOWN_GRADLE_FILES.contains(virtualFile.name) && GradleSettings.getInstance(project).getLinkedProjectSettings(virtualFile.parent.path) == null } override fun actionPerformed(e: AnActionEvent) { val virtualFile = e.getData<VirtualFile>(CommonDataKeys.VIRTUAL_FILE) ?: return val project = e.getData<Project>(CommonDataKeys.PROJECT) ?: return val externalProjectPath = getDefaultPath(virtualFile) ExternalSystemUtil.confirmLoadingUntrustedProject(project, GradleConstants.SYSTEM_ID) linkAndRefreshGradleProject(externalProjectPath, project) } private fun getDefaultPath(file: VirtualFile): String { return if (file.isDirectory) file.path else file.parent.path } }
apache-2.0
133f85a3e9c78b71aa33684a92765d9f
47.837838
140
0.807863
4.715405
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUi.kt
1
12543
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ui.branch.dashboard import com.intellij.ide.CommonActionsManager import com.intellij.ide.DataManager import com.intellij.ide.DefaultTreeExpander import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.IdeBorderFactory.createBorder import com.intellij.ui.JBColor import com.intellij.ui.OnePixelSplitter import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.StatusText.getDefaultEmptyText import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy import com.intellij.vcs.log.VcsLogFilterCollection import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.impl.VcsLogManager.BaseVcsLogUiFactory import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties.MAIN_LOG_ID import com.intellij.vcs.log.impl.VcsLogUiProperties import com.intellij.vcs.log.ui.VcsLogColorManager import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcs.log.ui.VcsLogUiImpl import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx import com.intellij.vcs.log.ui.frame.FrameDiffPreview import com.intellij.vcs.log.ui.frame.MainFrame import com.intellij.vcs.log.ui.frame.ProgressStripe import com.intellij.vcs.log.ui.frame.VcsLogChangeProcessor import com.intellij.vcs.log.visible.VisiblePackRefresher import com.intellij.vcs.log.visible.VisiblePackRefresherImpl import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import git4idea.i18n.GitBundle.message import git4idea.ui.branch.dashboard.BranchesDashboardActions.DeleteBranchAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.FetchAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.GroupByDirectoryAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.NewBranchAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowBranchDiffAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowMyBranchesAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.ToggleFavoriteAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.UpdateSelectedBranchAction import org.jetbrains.annotations.CalledInAwt import java.awt.Component import javax.swing.JComponent import javax.swing.event.TreeSelectionListener internal class BranchesDashboardUi(project: Project, private val logUi: BranchesVcsLogUi) : Disposable { private val uiController = BranchesDashboardController(project, this) private val tree = FilteringBranchesTree(project, BranchesTreeComponent(project), uiController) private val branchViewSplitter = BranchViewSplitter() private val branchesTreePanel = BranchesTreePanel().withBorder(createBorder(JBColor.border(), SideBorder.LEFT)) private val branchesTreeWithToolbarPanel = simplePanel() private val branchesScrollPane = ScrollPaneFactory.createScrollPane(tree.component, true) private val branchesProgressStripe = ProgressStripe(branchesScrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) private val branchesTreeWithLogPanel = simplePanel() private val mainPanel = simplePanel().apply { DataManager.registerDataProvider(this, uiController) } private val branchesSearchFieldPanel = simplePanel() private val branchesSearchField = NonOpaquePanel(tree.installSearchField(JBUI.Borders.emptyLeft(5))).apply(UIUtil::setNotOpaqueRecursively) private val treeSelectionListener = TreeSelectionListener { if (!branchesTreeWithToolbarPanel.isVisible) return@TreeSelectionListener val ui = logUi val branchNames = tree.getSelectedBranchNames() ui.filterUi.setFilter(if (branchNames.isNotEmpty()) VcsLogFilterObject.fromBranches(branchNames) else null) } init { initMainUi() installLogUi() updateBranchesTree(true) } @CalledInAwt private fun installLogUi() { uiController.registerDataPackListener(logUi.logData) uiController.registerLogUiPropertiesListener(logUi.properties) branchesSearchField.setVerticalSizeReferent(logUi.toolbar) branchViewSplitter.secondComponent = logUi.mainFrame val diffPreview = logUi.createDiffPreview() mainPanel.add(DiffPreviewSplitter(diffPreview, logUi.properties, branchesTreeWithLogPanel).mainComponent) tree.component.addTreeSelectionListener(treeSelectionListener) } @CalledInAwt private fun disposeBranchesUi() { branchViewSplitter.secondComponent.removeAll() uiController.removeDataPackListener(logUi.logData) uiController.removeLogUiPropertiesListener(logUi.properties) tree.component.removeTreeSelectionListener(treeSelectionListener) } private fun initMainUi() { val diffAction = ShowBranchDiffAction() diffAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Diff.ShowDiff"), branchesTreeWithLogPanel) val deleteAction = DeleteBranchAction() val shortcuts = KeymapUtil.getActiveKeymapShortcuts("SafeDelete").shortcuts + KeymapUtil.getActiveKeymapShortcuts( "EditorDeleteToLineStart").shortcuts deleteAction.registerCustomShortcutSet(CustomShortcutSet(*shortcuts), branchesTreeWithLogPanel) createFocusFilterFieldAction(branchesSearchField) val groupByDirectoryAction = GroupByDirectoryAction(tree) val toggleFavoriteAction = ToggleFavoriteAction() val fetchAction = FetchAction(this) val showMyBranchesAction = ShowMyBranchesAction(uiController) val newBranchAction = NewBranchAction() val updateSelectedAction = UpdateSelectedBranchAction() val defaultTreeExpander = DefaultTreeExpander(tree.component) val commonActionsManager = CommonActionsManager.getInstance() val expandAllAction = commonActionsManager.createExpandAllHeaderAction(defaultTreeExpander, tree.component) val collapseAllAction = commonActionsManager.createCollapseAllHeaderAction(defaultTreeExpander, tree.component) val group = DefaultActionGroup() group.add(newBranchAction) group.add(updateSelectedAction) group.add(deleteAction) group.add(diffAction) group.add(showMyBranchesAction) group.add(fetchAction) group.add(toggleFavoriteAction) group.add(Separator()) group.add(groupByDirectoryAction) group.add(expandAllAction) group.add(collapseAllAction) val toolbar = ActionManager.getInstance().createActionToolbar("Git.Cleanup.Branches", group, false) toolbar.setTargetComponent(branchesTreePanel) branchesTreeWithToolbarPanel.addToLeft(toolbar.component) branchesSearchFieldPanel.withBackground(UIUtil.getListBackground()).withBorder(createBorder(JBColor.border(), SideBorder.BOTTOM)) branchesSearchFieldPanel.addToCenter(branchesSearchField) branchesTreePanel.addToTop(branchesSearchFieldPanel).addToCenter(branchesProgressStripe) branchesTreeWithToolbarPanel.addToCenter(branchesTreePanel) branchViewSplitter.firstComponent = branchesTreeWithToolbarPanel branchesTreeWithLogPanel.addToCenter(branchViewSplitter) mainPanel.isFocusCycleRoot = true mainPanel.focusTraversalPolicy = BRANCHES_UI_FOCUS_TRAVERSAL_POLICY startLoadingBranches() toggleBranchesPanelVisibility() } fun toggleBranchesPanelVisibility() { branchesTreeWithToolbarPanel.isVisible = logUi.properties.get(SHOW_GIT_BRANCHES_LOG_PROPERTY) } private fun createFocusFilterFieldAction(searchField: Component) { DumbAwareAction.create { e -> val project = e.getRequiredData(CommonDataKeys.PROJECT) if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(tree.component) != null) { IdeFocusManager.getInstance(project).requestFocus(searchField, true) } else { IdeFocusManager.getInstance(project).requestFocus(tree.component, true) } }.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Find"), branchesTreePanel) } inner class BranchesTreePanel : BorderLayoutPanel(), DataProvider { override fun getData(dataId: String): Any? { if (GIT_BRANCHES.`is`(dataId)) { return tree.getSelectedBranches() } return null } } private val BRANCHES_UI_FOCUS_TRAVERSAL_POLICY = object : ComponentsListFocusTraversalPolicy() { override fun getOrderedComponents(): List<Component> = listOf(tree.component, logUi.table, logUi.mainFrame.changesBrowser.preferredFocusedComponent, logUi.mainFrame.filterUi.textFilterComponent.textEditor) } fun getMainComponent(): JComponent { return mainPanel } fun updateBranchesTree(initial: Boolean) { tree.update(initial) } fun refreshTree() { tree.refreshTree() } fun startLoadingBranches() { tree.component.emptyText.text = message("action.Git.Loading.Branches.progress") branchesTreePanel.isEnabled = false branchesProgressStripe.startLoading() } fun stopLoadingBranches() { tree.component.emptyText.text = getDefaultEmptyText() branchesTreePanel.isEnabled = true branchesProgressStripe.stopLoading() } override fun dispose() { disposeBranchesUi() } } internal class BranchesVcsLogUiFactory(logManager: VcsLogManager, logId: String, filters: VcsLogFilterCollection? = null) : BaseVcsLogUiFactory<BranchesVcsLogUi>(logId, filters, logManager.uiProperties, logManager.colorManager) { override fun createVcsLogUiImpl(logId: String, logData: VcsLogData, properties: MainVcsLogUiProperties, colorManager: VcsLogColorManagerImpl, refresher: VisiblePackRefresherImpl, filters: VcsLogFilterCollection?) = BranchesVcsLogUi(logId, logData, colorManager, properties, refresher, filters) } internal class BranchesVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager, uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher, initialFilters: VcsLogFilterCollection?) : VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, initialFilters) { private val branchesUi = BranchesDashboardUi(logData.project, this) .also { branchesUi -> Disposer.register(this, branchesUi) } override fun createMainFrame(logData: VcsLogData, uiProperties: MainVcsLogUiProperties, filterUi: VcsLogFilterUiEx) = MainFrame(logData, this, uiProperties, filterUi, false) .apply { isFocusCycleRoot = false focusTraversalPolicy = null //new focus traversal policy will be configured include branches tree } override fun getMainComponent() = branchesUi.getMainComponent() fun createDiffPreview(): VcsLogChangeProcessor { return mainFrame.createDiffPreview(false, mainFrame.changesBrowser) } } internal val SHOW_GIT_BRANCHES_LOG_PROPERTY = object : VcsLogProjectTabsProperties.CustomBooleanTabProperty("Show.Git.Branches") { override fun defaultValue(logId: String) = logId == MAIN_LOG_ID } private class BranchViewSplitter(first: JComponent? = null, second: JComponent? = null) : OnePixelSplitter(false, "vcs.branch.view.splitter.proportion", 0.3f) { init { firstComponent = first secondComponent = second } } private class DiffPreviewSplitter(diffPreview: VcsLogChangeProcessor, uiProperties: VcsLogUiProperties, mainComponent: JComponent) : FrameDiffPreview<VcsLogChangeProcessor>(diffPreview, uiProperties, mainComponent, "vcs.branch.view.diff.splitter.proportion", true, 0.3f) { override fun updatePreview(state: Boolean) { previewDiff.updatePreview(state) } }
apache-2.0
5f1f87ca9528c6eb4e499191ad10b002
45.284133
141
0.784262
5.113331
false
false
false
false
vicboma1/Kotlin-Koans
src/main/java/iii_conventions/MyDate.kt
1
1363
package iii_conventions import java.util.* data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { operator fun plus(timeIntervals: RepeatedTimeInterval) = addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number) override fun compareTo(other: MyDate ): Int{ if (this.year != other.year) return (this.year - other.year) if (this.month != other.month) return (this.month - other.month) return (this.dayOfMonth - other.dayOfMonth) } } enum class TimeInterval { DAY, WEEK, YEAR } class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int) class DateRange(override val start: MyDate, override val end: MyDate) : Iterable<MyDate> , Range<MyDate> { operator fun MyDate.rangeTo(other: MyDate) = DateRange(this,other) override fun contains(item: MyDate): Boolean = start < item && item < end override fun iterator(): Iterator<MyDate> = object : Iterator<MyDate> { var current: MyDate = start override fun next(): MyDate { if (!hasNext()) { throw NoSuchElementException() } val result = current current = current.nextDay() return result } override fun hasNext(): Boolean { return current <= end } } }
mit
b83e17d7605ec818132be74041c39794
27.395833
127
0.639032
4.513245
false
false
false
false
tbaxter120/Restdroid
app/src/main/java/com/ridocula/restdroid/persistence/entities/HistoryRequestEntity.kt
1
795
package com.ridocula.restdroid.persistence.entities import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey /** * Created by tbaxter on 7/26/17. */ @Entity(tableName = "history_request") data class HistoryRequestEntity constructor( @ColumnInfo(name = "id") @PrimaryKey val id: String, @ColumnInfo(name = "url") val url: String, @ColumnInfo(name = "type") val type: String, @ColumnInfo(name = "body") val body: String?, @ColumnInfo(name = "response_id") val responseId: String?, @ColumnInfo(name = "created_date") val createdDate: Long?, @ColumnInfo(name = "headrs") val headers: String )
apache-2.0
0e038e01248e1f3d2709d49a41dacf3e
28.481481
51
0.641509
4.035533
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerEnabledRootView.kt
2
2260
package versioned.host.exp.exponent.modules.api.components.gesturehandler.react import android.content.Context import android.os.Bundle import android.util.AttributeSet import android.view.MotionEvent import com.facebook.react.ReactInstanceManager import com.facebook.react.ReactRootView @Deprecated(message = "Use <GestureHandlerRootView /> component instead. Check gesture handler installation instructions in documentation for more information.") class RNGestureHandlerEnabledRootView : ReactRootView { private lateinit var _reactInstanceManager: ReactInstanceManager private var gestureRootHelper: RNGestureHandlerRootHelper? = null constructor(context: Context?) : super(context) {} constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {} override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { gestureRootHelper?.requestDisallowInterceptTouchEvent(disallowIntercept) super.requestDisallowInterceptTouchEvent(disallowIntercept) } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { return if (gestureRootHelper?.dispatchTouchEvent(ev) == true) { true } else super.dispatchTouchEvent(ev) } /** * This method is used to enable root view to start processing touch events through the gesture * handler library logic. Unless this method is called (which happens as a result of instantiating * new gesture handler from JS) the root view component will just proxy all touch related methods * to its superclass. Thus in the "disabled" state all touch related events will fallback to * default RN behavior. */ fun initialize() { check(gestureRootHelper == null) { "GestureHandler already initialized for root view $this" } gestureRootHelper = RNGestureHandlerRootHelper( _reactInstanceManager.currentReactContext!!, this ) } fun tearDown() { gestureRootHelper?.let { it.tearDown() gestureRootHelper = null } } override fun startReactApplication( reactInstanceManager: ReactInstanceManager, moduleName: String, initialProperties: Bundle?, ) { super.startReactApplication(reactInstanceManager, moduleName, initialProperties) _reactInstanceManager = reactInstanceManager } }
bsd-3-clause
fb6d8b558a158b57dc4bcf9b59deeb66
37.965517
161
0.774779
5.124717
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/cases/MoveRefactoringCase.kt
3
2584
// 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.actions.internal.refactoringTesting.cases; import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.Project import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RandomMoveRefactoringResult import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RefactoringCase import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsHandler import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.RefactoringConflictsFoundException import org.jetbrains.kotlin.psi.KtClass internal class MoveRefactoringCase : RefactoringCase { override fun tryCreateAndRun(project: Project): RandomMoveRefactoringResult { val projectFiles = project.files() if (projectFiles.isEmpty()) RandomMoveRefactoringResult.Failed fun getRandomKotlinClassOrNull(): KtClass? { val classes = PsiTreeUtil.collectElementsOfType(projectFiles.random().toPsiFile(project), KtClass::class.java) return if (classes.isNotEmpty()) return classes.random() else null } val targetClass: KtClass? = null val sourceClass = getRandomKotlinClassOrNull() ?: return RandomMoveRefactoringResult.Failed val sourceClassAsArray = arrayOf(sourceClass) val testDataKeeper = TestDataKeeper("no data") val handler = MoveKotlinDeclarationsHandler(MoveKotlinDeclarationsHandlerTestActions(testDataKeeper)) if (!handler.canMove(sourceClassAsArray, targetClass, /*reference = */ null)) { return RandomMoveRefactoringResult.Failed } try { handler.doMove(project, sourceClassAsArray, targetClass, null) } catch (e: Throwable) { return when (e) { is NotImplementedError, is FailedToRunCaseException, is RefactoringConflictsFoundException, is ConfigurationException -> RandomMoveRefactoringResult.Failed else -> RandomMoveRefactoringResult.ExceptionCaused( testDataKeeper.caseData, "${e.javaClass.typeName}: ${e.message ?: "No message"}" ) } } return RandomMoveRefactoringResult.Success(testDataKeeper.caseData) } }
apache-2.0
cecd7bcaab5cbabca2c03823129780a5
43.551724
158
0.724458
5.168
false
true
false
false
smmribeiro/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/LineStatusTrackerModifyDocumentTest.kt
12
19739
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs import com.intellij.openapi.vcs.LineStatusTrackerTestUtil.parseInput import com.intellij.openapi.vcs.ex.Range class LineStatusTrackerModifyDocumentTest : BaseLineStatusTrackerTestCase() { fun testInitialEmpty() { test("", "") { assertRanges() compareRanges() } } fun testInitialEquals() { test("1234_2345_3456", "1234_2345_3456") { assertRanges() compareRanges() } } fun testInitialInsertion() { test("1234_2345_3456", "1234_3456") { assertRanges(Range(1, 2, 1, 1)) compareRanges() } } fun testInitialDeletion() { test("1234_3456", "1234_2345_3456") { assertRanges(Range(1, 1, 1, 2)) compareRanges() } } fun testInitialModification1() { test("1234_x_3456", "1234_2345_3456") { assertRanges(Range(1, 2, 1, 2)) compareRanges() } } fun testInitialModification2() { test("1_3_4_5_6_7", "1_2_3_5_6_12") { assertRanges(Range(1, 1, 1, 2), Range(2, 3, 3, 3), Range(5, 6, 5, 6)) compareRanges() } } fun testInitialHeuristic() { test("1234567__1234567__1234567__1234567", "1234567__XXXXXX__1234567__XXXXXX__1234567__XXXXXX__1234567") { assertRanges(Range(2, 2, 2, 4), Range(4, 4, 6, 8), Range(6, 6, 10, 12)) compareRanges() } } fun testSimpleInsert() { test("1234_2345_3456") { "12".insertAfter("a") assertRanges(Range(0, 1, 0, 1)) compareRanges() } } fun testUndo() { test("1234_2345_3456") { "1234_23".insertAfter("a") assertRanges(Range(1, 2, 1, 2)) compareRanges() "a".delete() compareRanges() } } fun testLineEndBeforeModification() { test("1234_2345_3456") { "1234_2".insertAfter("a") assertRanges(Range(1, 2, 1, 2)) compareRanges() "1234_".insertAfter("_") assertRanges(Range(1, 3, 1, 2)) compareRanges() } } fun testLineEndBeforeModification2() { test("1234_2345_3456") { "1234_2".insertAfter("a") compareRanges() "1234".insertAfter("_") compareRanges() } } fun testInsertDoubleEnterAtEnd() { test("1") { "1".insertAfter("_") compareRanges() "1_".insertAfter("_") compareRanges() } } fun testSimpleInsertAndWholeReplace() { test("1234_2345_3456") { "12".insertAfter("a") compareRanges() replaceWholeText(" ") compareRanges() } } fun testSimpleInsert2() { test("1_2_3_4_5") { "2_".insertAfter("a") compareRanges() } } fun testSimpleInsertToEmpty() { test("") { insertAtStart("a") compareRanges() } } fun testDoubleSimpleInsert() { test("1234_2345_3456") { "12".insertAfter("a") compareRanges() "12".insertAfter("a") compareRanges() } } fun testInsertEnter() { test("1234_2345_3456") { "12".insertAfter("_") compareRanges() } } fun testSimpleInsertAndEnterToEmpty() { test("") { insertAtStart("a") compareRanges() "a".insertAfter("_") compareRanges() } } fun testInsertEnterAtEnter() { test("1234_2345_3456") { "1234".insertAfter("_") compareRanges() } } fun testInsertEnterAtEnterAndSimpleInsert() { test("1234_2345_3456") { "1234".insertAfter("_") compareRanges() "1234_".insertAfter("a") compareRanges() } } fun testInsertDoubleEnterAtEnters() { test("1234_2345_3456") { "1234".insertAfter("_") compareRanges() "2345".insertAfter("_") compareRanges() } } fun testInsertEnterAndSpaceAfterEnter() { test("12345_12345_12345") { (1 th "12345").insertAfter("_ ") compareRanges() } } fun testInsertEnterAndDeleteEnter1() { test("12345_12345_12345") { (1 th "12345").insertAfter("_") compareRanges() (1 th "_").delete() compareRanges() } } fun testInsertEnterAndDeleteEnter2() { test("12345_12345_12345") { (1 th "12345").insertAfter("_") compareRanges() (2 th "_").delete() compareRanges() } } fun testSimpleDelete() { test("1234_2345_3456") { (1 th "3").delete() compareRanges() } } fun testDeleteLine() { test("1234_2345_3456") { "1234_".delete() compareRanges() } } fun testDoubleDelete() { test("1234_2345_3456") { (1 th "3").delete() compareRanges() (1 th "4").delete() compareRanges() } } fun testDeleteEnter() { test("12345_23456_34567") { (1 th "_").delete() compareRanges() } } fun testDeleteDoubleEnter() { test("12345__23456_34567") { (1 th "_").delete() compareRanges() } } fun testDoubleInsertToClass() { test("class A{__}") { "class A{_".insertAfter("a") compareRanges() "class A{_a".insertAfter("a") compareRanges() } } fun testInsertSymbolAndEnterToClass() { test("class A{__}") { "class A{_".insertAfter("a") compareRanges() "class A{_a".insertAfter("_") compareRanges() } } fun testMultiLineReplace2() { test("012a_012b_012c") { "_012b".replace("_x_y_z") compareRanges() } } fun testChangedLines1() { test("class A{_x_a_b_c_}", "class A{_1_x_2_}") { compareRanges() } } fun testMultiLineReplace1() { test("012a_012b_012c_012d_012e") { ("0" `in` "012b").replace("a") compareRanges() "_a12b_012c".replace("_x") compareRanges() } } fun testInsertAndModify() { test("a_b_c_d") { "a_b".insertAfter("_") compareRanges() "a_b_".insertAfter("_") compareRanges() "a_b___".insertAfter(" ") compareRanges() } } fun testRangesShouldMerge() { test("1_2_3_4") { "1".insertAfter("1") compareRanges() "3".insertAfter("3") compareRanges() "11_".insertAfter("2") compareRanges() } } fun testShiftRangesAfterChange() { test("1_2_3_4") { "4".insertAfter("4") compareRanges() insertAtStart("_") compareRanges() insertAtStart("_") compareRanges() insertAtStart("_") compareRanges() } } fun testInsertBeforeChange() { test(" 11_ 3 _ 44_ 55_ 6_ 7_ 88_ ", " 1_ 2_ 3 _ 4_ 5_ 6_ 7_ 8_ ") { "11_ ".insertAfter("3") assertTextContentIs(" 11_ 33 _ 44_ 55_ 6_ 7_ 88_ ") compareRanges() "11_ ".insertAfter("aaa_bbbbbbbb_cccc_dddd") compareRanges() } } fun testUndoDeletion() { test("1_2_3_4_5_6_7_") { "3_".delete() assertTextContentIs("1_2_4_5_6_7_") compareRanges() "2_".insertAfter("3_") compareRanges() } } fun testUndoDeletion2() { test("1_2_3_4_5_6_7_") { "_3".delete() assertTextContentIs("1_2_4_5_6_7_") compareRanges() "2_".insertAfter("_3") compareRanges() } } fun testSRC17123() { test( "package package;_" + "_" + "public class Class3 {_" + " public int i1;_" + " public int i2;_" + " public int i3;_" + " public int i4;_" + "_" + " public static void main(String[] args) {_" + "_" + " }_" + "}" ) { "_ public int i1;".delete() compareRanges() assertTextContentIs( "package package;_" + "_" + "public class Class3 {_" + " public int i2;_" + " public int i3;_" + " public int i4;_" + "_" + " public static void main(String[] args) {_" + "_" + " }_" + "}") ("_" + " public int i2;_" + " public int i3;_" + " public int i4;_" + "_" + " public static void main(String[] args) {_" + "_" + " }_" + "}").delete() compareRanges() "{".delete() compareRanges() } } fun testUnexpetedDeletedRange() { test(" public class_ bbb_") { " public class_".insertAfter(" _") assertTextContentIs(" public class_ _ bbb_") compareRanges() (" " after "public class_").delete() assertTextContentIs(" public class__ bbb_") compareRanges() " public class__".insertAfter(" _") assertTextContentIs(" public class__ _ bbb_") compareRanges() (" " after "public class__").delete() assertTextContentIs(" public class___ bbb_") compareRanges() "public".delete() assertTextContentIs(" class___ bbb_") compareRanges() " class___".insertBefore("p") assertTextContentIs(" p class___ bbb_") compareRanges() " p".insertAfter("r") assertTextContentIs(" pr class___ bbb_") compareRanges() " pr".insertAfter("i") assertTextContentIs(" pri class___ bbb_") compareRanges() } } fun testSrc29814() { test("111_222_333_") { "111_222_333_".delete() assertTextContentIs("") compareRanges() insertAtStart("222_") compareRanges() "222_".delete() compareRanges() insertAtStart("111_222_333_") compareRanges() } } fun testDeletingTwoMethods() { val part1 = "class Foo {_ public void method1() {_ // something_ }__" val part2 = " public void method2() {_ // something_ }__ public void method3() {_ // something_ }_" val part3 = "_ public void method4() {_ // something_ }_}" test(part1 + part2 + part3) { (part2).delete() assertTextContentIs(part1 + part3) assertRanges(Range(5, 5, 5, 12)) ("_" at !part1.length - (part1.length + 1)).delete() compareRanges() } } fun testBug1() { test("1_2_3_4_") { "3_".delete() compareRanges() "1_2".insertAfter("X") compareRanges() } } fun testBug2() { test("1_2_3_4_5_6_") { "3_".delete() compareRanges() "6_".delete() compareRanges() "1_2_".insertAfter("3_8_") compareRanges() } } fun testBug3() { test("__00_556_") { "0_5".delete() "_05".delete() "_6".delete() insertAtStart("__32_") "_32".delete() } } fun testBug4() { test("_5_30_5240_32_46____51530__") { "_5_".insertAfter("40_1_2") "0_5240_32_46___".delete() "5_40".delete() "__1_23_51".insertAfter("30__23") "1_23_5130".delete() } } fun testBug5() { test("_") { insertAtStart("__6406") ("_" at !1 - 2).delete() ("_" at !0 - 1).insertAfter("_11_5") "__1".insertAfter("130") "__11301_".insertAfter("3") "56406".replace("4__56_21_") "1301_34__56_21".replace(" 60246") "__1 602".insertAfter("01511") "__1 60201".insertAfter("2633_33") "5".delete() "3114".delete() "602012633_3".delete() ("1" at !2 - 3).replace("_34__310_") ("_" at !2 - 3).delete() "0_".delete() ("_" at !0 - 1).insertAfter("051") assertTextContentIs("_051_34__31 6__") } } fun testTrimSpaces1() { test("a _b _c ") { insertAtStart("x") stripTrailingSpaces() rollbackLine(0) stripTrailingSpaces() assertTextContentIs("a _b _c ") } } fun testTrimSpaces2() { test("a _b _c ") { insertAtStart("x") stripTrailingSpaces() assertTextContentIs("xa_b _c ") } } fun testTrimSpaces3() { test("a _b _c ") { "a _b _".insertAfter("x") insertAtStart("x") stripTrailingSpaces() rollbackLine(2) stripTrailingSpaces() assertTextContentIs("xa_b _c ") } } fun testInsertion1() { test("X_X_X_") { insertAtStart("X_") assertRanges(Range(0, 1, 0, 0)) } } fun testInsertion2() { test("X_X_X_") { (1 th "X_").insertAfter("X_") assertRanges(Range(1, 2, 1, 1)) } } fun testInsertion3() { test("X_X_X_") { (2 th "X_").insertAfter("X_") assertRanges(Range(2, 3, 2, 2)) } } fun testInsertion4() { test("X_X_X_") { (3 th "X_").insertAfter("X_") assertRanges(Range(3, 4, 3, 3)) } } fun testInsertion5() { test("Z_X_X_") { "Z".replace("Y") "Y_".insertAfter("X_") assertRanges(Range(0, 2, 0, 1)) } } fun testInsertion6() { test("X_X_X_") { (1 th "X").replace("Y") "Y_X_".insertAfter("X_") assertRanges(Range(0, 1, 0, 1), Range(2, 3, 2, 2)) } } fun testInsertion7() { test("X_X_X_") { (1 th "X").replace("Y") "Y_X_X_".insertAfter("X_") assertRanges(Range(0, 1, 0, 1), Range(3, 4, 3, 3)) } } fun testInsertion8() { test("X_X_X_") { (3 th "X").replace("Y") assertRanges(Range(2, 3, 2, 3)) } } fun testInsertion9() { test("X_X_X") { (3 th "X").replace("Y") assertRanges(Range(2, 3, 2, 3)) } } fun testWhitespaceChanges() { test("AAAAA_ _BBBBB_CCCCC_DDDDD_EEEEE_") { " _BBBBB_CCCCC_DDDDD_EEEEE".replace(" BBBBB_ CCCCC_ DDDDD_ EEEEE_ ") assertRanges(Range(1, 6, 1, 6)) } } fun testWhitespaceBlockMerging1() { test("A_B_C_D_E_") { "A".replace("C_D_E") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_B_") assertRanges(Range(0, 3, 0, 1), Range(4, 4, 2, 5)) } } fun testWhitespaceBlockMerging2() { test("A_ _C_D_E_") { "A".replace("C_D_E") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_ _") assertRanges(Range(0, 0, 0, 2), Range(3, 4, 5, 5)) } } fun testWhitespaceBlockMerging3() { test("A_ _ _ _ _ _CCCCC_DDDDD_EEEEE_") { "A".replace("CCCCC_DDDDD_EEEEE") (2 th "CCCCC_DDDDD_EEEEE_").delete() assertTextContentIs("CCCCC_DDDDD_EEEEE_ _ _ _ _ _") assertRanges(Range(0, 0, 0, 6), Range(3, 8, 9, 9)) } } fun testWhitespaceBlockMerging4() { test("A_ _ _ _ _ _C_D_E_") { "A".replace("C_D_E") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_ _ _ _ _ _") assertRanges(Range(0, 3, 0, 1), Range(8, 8, 6, 9)) } } fun testNonEmptyLinesPriority1() { test("A_B__C_D") { "C_".delete() "B_".insertAfter("C_") assertRanges(Range(2, 2, 2, 3), Range(3, 4, 4, 4)) } } fun testNonEmptyLinesPriority2() { test("A_B____C_D") { "C_".delete() "B_".insertAfter("C_") assertRanges(Range(2, 3, 2, 2), Range(6, 6, 5, 6)) } } fun testFreezeNonEmptyLinesPriority() { test("A_B_C__C_D") { (2 th "C_").delete() tracker.doFrozen { simpleTracker.setBaseRevision(parseInput("A_B__C_D")) } assertRanges(Range(2, 2, 2, 3), Range(3, 4, 4, 4)) } } fun testFreeze1() { test("X_X_X") { (2 th "X_").insertAfter("X_") tracker.doFrozen(Runnable { assertNull(tracker.getRanges()) runCommandVerify { document.setText("") document.setText("Y") } runCommandVerify { document.setText("X\nX\nX\nX") } assertNull(tracker.getRanges()) }) assertRanges(Range(2, 3, 2, 2)) } } fun testFreeze2() { test("X_X_X") { (2 th "X_").insertAfter("X_") tracker.doFrozen(Runnable { assertNull(tracker.getRanges()) runCommandVerify { document.setText("") document.setText("Y") } runCommandVerify { document.setText(parseInput("Y_X_X_X_X")) } assertNull(tracker.getRanges()) }) assertRanges(Range(0, 1, 0, 0), Range(3, 4, 2, 2)) } } fun testFreeze3() { test("X_X_X") { (2 th "X_").insertAfter("X_") tracker.doFrozen(Runnable { assertNull(tracker.getRanges()) tracker.doFrozen(Runnable { runCommandVerify { document.setText("") document.setText("Y") } assertNull(tracker.getRanges()) }) assertNull(tracker.getRanges()) runCommandVerify { document.setText("X\nX\nX\nX") } assertNull(tracker.getRanges()) }) assertRanges(Range(2, 3, 2, 2)) } } fun testFreeze4() { test("X_X_X") { (2 th "X_").insertAfter("X_") tracker.doFrozen(Runnable { assertNull(tracker.getRanges()) simpleTracker.setBaseRevision(parseInput("X_X_X_Z_Z")) runCommandVerify { document.setText(parseInput("Y_X_X_X_X_Z_Z")) } assertNull(tracker.getRanges()) }) assertRanges(Range(0, 1, 0, 0), Range(3, 4, 2, 2)) } } fun testFreeze5() { test("__", "") { tracker.doFrozen(Runnable { simpleTracker.setBaseRevision(parseInput(" 23")) }) assertRanges(Range(0, 3, 0, 1)) } } fun testCompensatedModifications() { test("X_X_X_X_X_X_X_X") { (1 th "X_").insertBefore("X_") (7 th "X_").delete() assertTextContentIs("X_X_X_X_X_X_X_X") assertRangesEmpty() } } fun testSuboptimalBaseRevisionUpdate() { val javadoc = """ /** * Javadoc */_ """.trimIndent() val methodBody = """ public static void main(String[] args) { System.out.println("Hello"); System.out.println("World"); }_ """.trimIndent() val suffix = """ tracker.doFrozen(Runnable { simpleTracker.setBaseRevision(parseInput(" 23")) })_ """.trimIndent() test(javadoc + methodBody + "_" + suffix) { (1 th "}_").insertAfter("_" + methodBody) ("Javadoc").insertAfter(" with modification") tracker.doFrozen(Runnable { simpleTracker.setBaseRevision(parseInput(javadoc + methodBody + "_" + methodBody + "_" + suffix)) }) assertRanges(Range(1, 2, 1, 2)) } testPartial(javadoc + methodBody + "_" + suffix) { (1 th "}_").insertAfter("_" + methodBody) ("Javadoc").insertAfter(" with modification") createChangelist("Test") range(1).moveTo("Test") tracker.doFrozen(Runnable { partialTracker.setBaseRevision(parseInput(javadoc + methodBody + "_" + methodBody + "_" + suffix)) }) // we could not merge misaligned compensating addition and deletion because they belong to different changelists assertRanges(Range(1, 2, 1, 2), Range(3, 3, 3, 8), Range(7, 12, 12, 12)) } } fun testSuboptimalBaseRevisionUpdateWithEmptyLines() { val prefix = """ /** * Javadoc */_ public static void main(String[] args) { System.out.println("Hello"); System.out.println("World"); }_ """.trimIndent() val suffix = """ tracker.doFrozen(Runnable { simpleTracker.setBaseRevision(parseInput(" 23")) })_ """.trimIndent() test(prefix + "_" + suffix) { (1 th "}_").insertAfter("__") ("Javadoc").insertAfter(" with modification") tracker.doFrozen(Runnable { simpleTracker.setBaseRevision(parseInput(prefix + "___" + suffix)) }) assertRanges(Range(1, 2, 1, 2)) } } }
apache-2.0
19dbfd830821ee92827ab7f9badff6ee
20.316415
140
0.513906
3.542534
false
true
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslExpressionCastUints.kt
1
978
package de.fabmax.kool.modules.ksl.lang // Uint to * cast extension functions - defined in a separate file to avoid JVM signature clashes fun KslScalarExpression<KslTypeUint1>.toFloat1() = KslExpressionCastScalar(this, KslTypeFloat1) fun KslScalarExpression<KslTypeUint1>.toInt1() = KslExpressionCastScalar(this, KslTypeInt1) fun KslVectorExpression<KslTypeUint2, KslTypeUint1>.toFloat2() = KslExpressionCastVector(this, KslTypeFloat2) fun KslVectorExpression<KslTypeUint2, KslTypeUint1>.toInt2() = KslExpressionCastVector(this, KslTypeInt2) fun KslVectorExpression<KslTypeUint3, KslTypeUint1>.toFloat3() = KslExpressionCastVector(this, KslTypeFloat3) fun KslVectorExpression<KslTypeUint3, KslTypeUint1>.toInt3() = KslExpressionCastVector(this, KslTypeInt3) fun KslVectorExpression<KslTypeUint4, KslTypeUint1>.toFloat4() = KslExpressionCastVector(this, KslTypeFloat4) fun KslVectorExpression<KslTypeUint4, KslTypeUint1>.toInt4() = KslExpressionCastVector(this, KslTypeInt4)
apache-2.0
4ac5ff6ee132286083bbc334cfa48494
64.266667
109
0.839468
4.38565
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/rcomponents/Top.kt
1
8956
package com.cout970.modeler.gui.rcomponents import com.cout970.modeler.api.model.selection.SelectionType import com.cout970.modeler.controller.Dispatch import com.cout970.modeler.gui.Gui import com.cout970.modeler.gui.canvas.tool.Cursor3D import com.cout970.modeler.gui.canvas.tool.CursorMode import com.cout970.modeler.gui.canvas.tool.CursorOrientation import com.cout970.modeler.gui.leguicomp.* import com.cout970.modeler.gui.rcomponents.left.ModelAccessorProps import com.cout970.modeler.util.IPropertyBind import com.cout970.modeler.util.PropertyManager import com.cout970.reactive.core.* import com.cout970.reactive.dsl.* import com.cout970.reactive.nodes.child import com.cout970.reactive.nodes.div import com.cout970.reactive.nodes.style import org.liquidengine.legui.component.optional.align.HorizontalAlign data class TopBarProps(val gui: Gui) : RProps class TopBar : RStatelessComponent<TopBarProps>() { override fun RBuilder.render() = div("TopBar") { style { style.border = PixelBorder().also { it.enableBottom = true } classes("top_bar") height = 48f } postMount { fillX() } div("ProjectControls") { style { transparent() borderless() width = 240f height = 48f } +IconButton("project.new", "newProjectIcon", 0f, 0f, 48f, 48f).also { it.setTooltip("New Project") } +IconButton("project.load", "loadProjectCubeIcon", 48f, 0f, 48f, 48f).also { it.setTooltip("Load Project") } +IconButton("project.save", "saveProjectIcon", 96f, 0f, 48f, 48f).also { it.setTooltip("Save Project") } +IconButton("project.save.as", "saveAsProjectIcon", 144f, 0f, 48f, 48f).also { it.setTooltip("Save Project As") } +IconButton("project.edit", "editProjectIcon", 192f, 0f, 48f, 48f).also { it.setTooltip("Edit Project") } } div("ExportControls") { style { transparent() borderless() width = 192f height = 48f posX = 240f } +IconButton("model.import", "importModelIcon", 0f, 0f, 48f, 48f).also { it.setTooltip("Import Model") } +IconButton("model.export", "exportModelIcon", 48f, 0f, 48f, 48f).also { it.setTooltip("Export Model") } +IconButton("texture.export", "exportTextureIcon", 96f, 0f, 48f, 48f).also { it.setTooltip("Export Texture Template") } +IconButton("model.export.hitboxes", "exportHitboxIcon", 144f, 0f, 48f, 48f).also { it.setTooltip("Export Hitbox Map") } } child(SelectionTypeBar::class) child(CursorOrientationBar::class, CursorProps(props.gui.state.cursor)) child(CursorModeBar::class, CursorProps(props.gui.state.cursor)) // child(ModelStatistics::class, ModelAccessorProps(props.gui.programState)) } } data class SelectionTypeState(val type: SelectionType) : RState class SelectionTypeBar : RComponent<EmptyProps, SelectionTypeState>() { override fun getInitialState() = SelectionTypeState(SelectionType.OBJECT) override fun RBuilder.render() = div("SelectionTypeBar") { style { classes("selection_type_bar") posX = 432f + 10f posY = 5f width = 143f + 8f height = 40f } val firstButton = state.type == SelectionType.OBJECT val secondButton = state.type == SelectionType.FACE val thirdButton = state.type == SelectionType.EDGE val fourthButton = state.type == SelectionType.VERTEX +ToggleButton("selection_mode_object", firstButton, 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Selection mode: OBJECT") borderless() onClick { set(SelectionType.OBJECT) } } +ToggleButton("selection_mode_face", secondButton, 32f + 5f + 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Selection mode: FACE") borderless() onClick { set(SelectionType.FACE) } } +ToggleButton("selection_mode_edge", thirdButton, 64f + 10f + 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Selection mode: EDGE") borderless() onClick { set(SelectionType.EDGE) } } +ToggleButton("selection_mode_vertex", fourthButton, 96f + 15f + 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Selection mode: VERTEX") borderless() onClick { set(SelectionType.VERTEX) } } onCmd("updateSelectionType") { args -> setState { SelectionTypeState(args.getValue("value") as SelectionType) } } } @Suppress("UNCHECKED_CAST") private fun set(newType: SelectionType) { PropertyManager.findProperty("SelectionType") ?.let { it as IPropertyBind<SelectionType> } ?.set(newType) } } data class CursorProps(val cursor: Cursor3D) : RProps class CursorOrientationBar : RStatelessComponent<CursorProps>() { override fun RBuilder.render() = div("CursorOrientationBar") { style { classes("cursor_orientation_bar") posX = 600f posY = 5f width = 64f + 14f height = 40f } val secondButton = props.cursor.orientation == CursorOrientation.GLOBAL val firstButton = props.cursor.orientation == CursorOrientation.LOCAL +ToggleButton("selection_orientation_global", secondButton, 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Cursor orientation: Global") borderless() onClick { Dispatch.run("cursor.set.orientation.global") } } +ToggleButton("selection_orientation_local", firstButton, 32f + 5f + 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Cursor orientation: Local") borderless() onClick { Dispatch.run("cursor.set.orientation.local") } } onCmd("updateCursorOrientation") { rerender() } } } class CursorModeBar : RStatelessComponent<CursorProps>() { override fun RBuilder.render() = div("CursorModeBar") { style { classes("cursor_mode_bar") posX = 600f + 64f + 14f + 8f posY = 5f width = 72f + 32f + 5f + 8f height = 40f } val firstButton = props.cursor.mode == CursorMode.TRANSLATION val secondButton = props.cursor.mode == CursorMode.ROTATION val thirdButton = props.cursor.mode == CursorMode.SCALE +ToggleButton("selection_mode_translation", firstButton, 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Cursor mode: Translation") borderless() onClick { Dispatch.run("cursor.set.mode.translate") } } +ToggleButton("selection_mode_rotation", secondButton, 32f + 5f + 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Cursor mode: Rotation") borderless() onClick { Dispatch.run("cursor.set.mode.rotate") } } +ToggleButton("selection_mode_scale", thirdButton, 32f + 5f + 32f + 5f + 4f, 4f, 32f, 32f).apply { tooltip = InstantTooltip("Cursor mode: Scale") borderless() onClick { Dispatch.run("cursor.set.mode.scale") } } onCmd("updateCursorMode") { rerender() } } } class ModelStatistics : RStatelessComponent<ModelAccessorProps>() { override fun RBuilder.render() = div("ModelStatistics") { style { width = 288f height = 45f classes("statistics_panel") } postMount { posX = parent.sizeX - sizeX } val model = props.access.model val objs = model.objects.size val quads = model.objects.map { it.mesh.faces.size }.sum() val posVertex = model.objects.map { it.mesh.pos.size }.sum() val texVertex = model.objects.map { it.mesh.tex.size }.sum() val config: FixedLabel.() -> Unit = { fontSize = 18f horizontalAlign = HorizontalAlign.LEFT paddingLeft(10f) classes("statistics_panel_item") } +FixedLabel("Objs: $objs", 5f, 7f, 135f, 16f).apply(config) +FixedLabel("Quads: $quads", 5f, 27f, 135f, 16f).apply(config) +FixedLabel("Pos vertex: $posVertex", 144f, 7f, 140f, 16f).apply(config) +FixedLabel("Tex vertex: $texVertex", 144f, 27f, 140f, 16f).apply(config) onCmd("updateModel") { rerender() } } }
gpl-3.0
95049d809c33e21ddfadb9881bb4b9ad
34.403162
106
0.591335
4.119595
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/BaseMainFragment.kt
1
3579
package com.habitrpg.android.habitica.ui.fragments import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.appbar.AppBarLayout import com.google.android.material.tabs.TabLayout import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.helpers.SoundManager import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import io.reactivex.functions.Consumer import javax.inject.Inject abstract class BaseMainFragment : BaseFragment() { @Inject lateinit var apiClient: ApiClient @Inject lateinit var userRepository: UserRepository @Inject lateinit var soundManager: SoundManager open val activity get() = getActivity() as? MainActivity val tabLayout get() = activity?.binding?.detailTabs val collapsingToolbar get() = activity?.binding?.toolbar val toolbarAccessoryContainer get() = activity?.binding?.toolbarAccessoryContainer val bottomNavigation get() = activity?.binding?.bottomNavigation var usesTabLayout: Boolean = false var hidesToolbar: Boolean = false var usesBottomNavigation = false open var user: User? = null override fun onAttach(context: Context) { super.onAttach(context) if (getActivity()?.javaClass == MainActivity::class.java) { user = activity?.user } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) compositeSubscription.add(userRepository.getUser().subscribe(Consumer { user = it }, RxErrorHandler.handleEmptyError())) if (this.usesBottomNavigation) { bottomNavigation?.visibility = View.VISIBLE } else { bottomNavigation?.visibility = View.GONE } setHasOptionsMenu(true) updateTabLayoutVisibility() if (hidesToolbar) { hideToolbar() disableToolbarScrolling() } else { showToolbar() enableToolbarScrolling() } return null } private fun updateTabLayoutVisibility() { if (this.usesTabLayout) { tabLayout?.removeAllTabs() tabLayout?.visibility = View.VISIBLE tabLayout?.tabMode = TabLayout.MODE_FIXED } else { tabLayout?.visibility = View.GONE } } override fun onDestroy() { userRepository.close() super.onDestroy() } private fun hideToolbar() { activity?.binding?.avatarWithBars?.root?.visibility = View.GONE } private fun showToolbar() { activity?.binding?.avatarWithBars?.root?.visibility = View.VISIBLE } private fun disableToolbarScrolling() { val params = collapsingToolbar?.layoutParams as? AppBarLayout.LayoutParams params?.scrollFlags = 0 } private fun enableToolbarScrolling() { val params = collapsingToolbar?.layoutParams as? AppBarLayout.LayoutParams params?.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED } }
gpl-3.0
2289484b49caea550263a5eb8e75f562
32.413462
136
0.677005
5.142241
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/SwitcherRendering.kt
1
9938
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.ide.IdeBundle.message import com.intellij.ide.ui.UISettings import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.editor.colors.EditorFontType.PLAIN import com.intellij.openapi.fileEditor.impl.EditorWindow import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl.OpenMode import com.intellij.openapi.keymap.KeymapUtil.getShortcutText import com.intellij.openapi.project.Project import com.intellij.openapi.util.Iconable.ICON_FLAG_READ_STATUS import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil.getLocationRelativeToUserHome import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.NaturalComparator import com.intellij.openapi.vcs.FileStatusManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil.getFileBackgroundColor import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.ToolWindowEventSource import com.intellij.openapi.wm.impl.ToolWindowManagerImpl import com.intellij.problems.WolfTheProblemSolver import com.intellij.ui.BackgroundSupplier import com.intellij.ui.CellRendererPanel import com.intellij.ui.JBColor import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.paint.EffectPainter.LINE_UNDERSCORE import com.intellij.ui.render.RenderingUtil import com.intellij.ui.speedSearch.SpeedSearchUtil.applySpeedSearchHighlighting import com.intellij.util.IconUtil import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Component import java.awt.Graphics import java.awt.Graphics2D import javax.swing.Icon import javax.swing.JList import javax.swing.ListCellRenderer private fun shortcutText(actionId: String) = ActionManager.getInstance().getKeyboardShortcut(actionId)?.let { getShortcutText(it) } private val mainTextComparator by lazy { Comparator.comparing(SwitcherListItem::mainText, NaturalComparator.INSTANCE) } internal interface SwitcherListItem { val mainText: String val statusText: String get() = "" val shortcutText: String? get() = null val separatorAbove: Boolean get() = false fun navigate(switcher: Switcher.SwitcherPanel, mode: OpenMode) fun close(switcher: Switcher.SwitcherPanel) = Unit fun prepareMainRenderer(component: SimpleColoredComponent, selected: Boolean) fun prepareExtraRenderer(component: SimpleColoredComponent, selected: Boolean) { shortcutText?.let { component.append(it, when (selected) { true -> SimpleTextAttributes.REGULAR_ATTRIBUTES else -> SimpleTextAttributes.SHORTCUT_ATTRIBUTES }) } } } internal class SwitcherRecentLocations(val switcher: Switcher.SwitcherPanel) : SwitcherListItem { override val separatorAbove = true override val mainText: String get() = when (switcher.isOnlyEditedFilesShown) { true -> message("recent.locations.changed.locations") else -> message("recent.locations.popup.title") } override val statusText: String get() = when (switcher.isOnlyEditedFilesShown) { true -> message("recent.files.accessible.open.recently.edited.locations") else -> message("recent.files.accessible.open.recently.viewed.locations") } override val shortcutText: String? get() = when (switcher.isOnlyEditedFilesShown) { true -> null else -> shortcutText(RecentLocationsAction.RECENT_LOCATIONS_ACTION_ID) } override fun navigate(switcher: Switcher.SwitcherPanel, mode: OpenMode) { RecentLocationsAction.showPopup(switcher.project, switcher.isOnlyEditedFilesShown) } override fun prepareMainRenderer(component: SimpleColoredComponent, selected: Boolean) { component.append(mainText) } } internal class SwitcherToolWindow(val window: ToolWindow, shortcut: Boolean) : SwitcherListItem { private val actionId = ActivateToolWindowAction.getActionIdForToolWindow(window.id) var mnemonic: String? = null override val mainText = window.stripeTitle override val statusText = message("recent.files.accessible.show.tool.window", mainText) override val shortcutText = if (shortcut) shortcutText(actionId) else null override fun navigate(switcher: Switcher.SwitcherPanel, mode: OpenMode) { val manager = ToolWindowManager.getInstance(switcher.project) as? ToolWindowManagerImpl manager?.activateToolWindow(window.id, null, true, when (switcher.isSpeedSearchPopupActive) { true -> ToolWindowEventSource.SwitcherSearch else -> ToolWindowEventSource.Switcher }) ?: window.activate(null, true) } override fun close(switcher: Switcher.SwitcherPanel) { val manager = ToolWindowManager.getInstance(switcher.project) as? ToolWindowManagerImpl manager?.hideToolWindow(window.id, false, false, ToolWindowEventSource.CloseFromSwitcher) ?: window.hide() } override fun prepareMainRenderer(component: SimpleColoredComponent, selected: Boolean) { component.icon = MnemonicIcon(window.icon, mnemonic, selected) component.append(mainText) } } internal class SwitcherVirtualFile( val project: Project, val file: VirtualFile, val window: EditorWindow? ) : SwitcherListItem, BackgroundSupplier { private val icon by lazy { IconUtil.getIcon(file, ICON_FLAG_READ_STATUS, project) } val isProblemFile get() = WolfTheProblemSolver.getInstance(project)?.isProblemFile(file) == true override var mainText: String = "" override val statusText: String get() = getLocationRelativeToUserHome((file.parent ?: file).presentableUrl) override fun navigate(switcher: Switcher.SwitcherPanel, mode: OpenMode) { } override fun close(switcher: Switcher.SwitcherPanel) { } override fun prepareMainRenderer(component: SimpleColoredComponent, selected: Boolean) { component.icon = when (Registry.`is`("ide.project.view.change.icon.on.selection", true)) { true -> RenderingUtil.getIcon(icon, selected) else -> icon } val foreground = if (selected) null else FileStatusManager.getInstance(project).getStatus(file).color val effectColor = if (isProblemFile) JBColor.red else null val style = when (effectColor) { null -> SimpleTextAttributes.STYLE_PLAIN else -> SimpleTextAttributes.STYLE_PLAIN or SimpleTextAttributes.STYLE_WAVED } component.append(mainText, SimpleTextAttributes(style, foreground, effectColor)) } override fun getElementBackground(row: Int) = getFileBackgroundColor(project, file) } internal class SwitcherListRenderer(val switcher: Switcher.SwitcherPanel) : ListCellRenderer<SwitcherListItem> { private val SEPARATOR = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground() private val main = SimpleColoredComponent().apply { isOpaque = false } private val extra = SimpleColoredComponent().apply { isOpaque = false } private val panel = CellRendererPanel().apply { layout = BorderLayout() add(BorderLayout.WEST, main) add(BorderLayout.EAST, extra) } override fun getListCellRendererComponent(list: JList<out SwitcherListItem>, value: SwitcherListItem, index: Int, selected: Boolean, focused: Boolean): Component { main.clear() extra.clear() val border = JBUI.Borders.empty(0, 10) panel.border = when (!selected && value.separatorAbove) { true -> JBUI.Borders.compound(border, JBUI.Borders.customLine(SEPARATOR, 1, 0, 0, 0)) else -> border } RenderingUtil.getForeground(list, selected).let { main.foreground = it extra.foreground = it } value.prepareMainRenderer(main, selected) value.prepareExtraRenderer(extra, selected) applySpeedSearchHighlighting(switcher, main, false, selected) panel.accessibleContext.accessibleName = value.mainText panel.accessibleContext.accessibleDescription = value.statusText return panel } private val toolWindowsAllowed = when (switcher.recent) { true -> Registry.`is`("ide.recent.files.tool.window.list") else -> Registry.`is`("ide.switcher.tool.window.list") } val toolWindows: List<SwitcherToolWindow> = if (toolWindowsAllowed) { val manager = ToolWindowManager.getInstance(switcher.project) val windows = manager.toolWindowIds .mapNotNull { manager.getToolWindow(it) } .filter { it.isAvailable && it.isShowStripeButton } .map { SwitcherToolWindow(it, switcher.pinned) } .sortedWith(mainTextComparator) // TODO: assign mnemonics windows } else emptyList() } private class MnemonicIcon(val icon: Icon?, val mnemonic: String?, val selected: Boolean) : Icon { private val size = JBUI.scale(16) private val width = mnemonic?.let { JBUI.scale(10) } ?: 0 override fun getIconWidth() = size + width override fun getIconHeight() = size override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { RenderingUtil.getIcon(icon, selected)?.let { val dx = x + (size - it.iconWidth) / 2 val dy = y + (size - it.iconHeight) / 2 it.paintIcon(c, g, dx, dy) } if (g is Graphics2D && false == mnemonic?.isEmpty()) { val font = PLAIN.globalFont.deriveFont(.8f * size) g.font = font g.paint = when (selected) { true -> JBUI.CurrentTheme.List.foreground(true, true) else -> JBUI.CurrentTheme.ActionsList.MNEMONIC_FOREGROUND } UISettings.setupAntialiasing(g) val metrics = g.fontMetrics val w = metrics.stringWidth(mnemonic) val dx = x + size - (w - width) / 2 val dy = y + size - metrics.descent g.drawString(mnemonic, dx, dy) if (SystemInfo.isWindows) { LINE_UNDERSCORE.paint(g, dx, dy, w, metrics.descent, font) } } } }
apache-2.0
0f5f04acf6b1a5f5944bdeb792ef55d7
39.072581
140
0.750956
4.345431
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-jobs/src/main/kotlin/slatekit/jobs/support/Scheduler.kt
1
1011
package slatekit.jobs.support import kotlinx.coroutines.runBlocking import org.threeten.bp.Duration import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import slatekit.common.DateTime import slatekit.common.ext.atUtc import java.util.concurrent.TimeUnit interface Scheduler { suspend fun schedule(time: DateTime, op: suspend () -> Unit) } class DefaultScheduler(val scheduler: ScheduledExecutorService = scheduler(2)) : Scheduler { override suspend fun schedule(time: DateTime, op: suspend () -> Unit) { val curr = DateTime.now().atUtc() val dest = time.atUtc() val diff = Duration.between(curr, dest) val secs = diff.seconds scheduler.schedule({ runBlocking { op() } }, secs, TimeUnit.SECONDS) } companion object { fun scheduler(poolSize: Int): ScheduledExecutorService { return Executors.newScheduledThreadPool(poolSize) } } }
apache-2.0
5ea331c600f81ed266d74d6a823aa152
27.083333
92
0.679525
4.658986
false
false
false
false
leafclick/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyParameterTypeHintsCollector.kt
1
2600
// 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 org.jetbrains.plugins.groovy.codeInsight.hint import com.intellij.codeInsight.hints.FactoryInlayHintsCollector import com.intellij.codeInsight.hints.InlayHintsSink import com.intellij.openapi.editor.Editor import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeAugmenter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrVariableEnhancer class GroovyParameterTypeHintsCollector(editor: Editor, private val settings: GroovyParameterTypeHintsInlayProvider.Settings) : FactoryInlayHintsCollector(editor) { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { if (!settings.showInferredParameterTypes) { return false } if (element is GrParameter && element.typeElement == null && !element.isVarArgs) { val type = (GrVariableEnhancer.getEnhancedType(element) ?: TypeAugmenter.inferAugmentedType(element)) ?.takeIf { !it.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) } ?: return true val typeRepresentation = factory.buildRepresentation(type, " ").run { factory.roundWithBackground(this) } sink.addInlineElement(element.textOffset, false, typeRepresentation) } if (settings.showTypeParameterList && element is GrMethod && !element.hasTypeParameters() && element.parameters.any { it.typeElement == null }) { val (virtualMethod, _) = MethodParameterAugmenter.createInferenceResult(element) ?: return true val typeParameterList = virtualMethod?.typeParameterList?.takeIf { it.typeParameters.isNotEmpty() } ?: return true val representation = factory.buildRepresentation(typeParameterList) if (element.modifierList.hasModifierProperty(DEF)) { sink.addInlineElement(element.modifierList.getModifier(DEF)!!.textRange.endOffset, true, representation) } else { sink.addInlineElement(element.textRange.startOffset, true, representation) } } return true } }
apache-2.0
5c34167326df25128525342f0a696924
52.081633
140
0.750385
4.634581
false
false
false
false
nsk-mironov/sento
sento-compiler/src/main/kotlin/io/mironov/sento/compiler/model/ListenerClassSpec.kt
1
6126
package io.mironov.sento.compiler.model import io.mironov.sento.compiler.ClassRegistry import io.mironov.sento.compiler.SentoException import io.mironov.sento.compiler.annotations.ListenerClass import io.mironov.sento.compiler.common.Methods import io.mironov.sento.compiler.common.Types import io.mironov.sento.compiler.common.isAbstract import io.mironov.sento.compiler.common.isInterface import io.mironov.sento.compiler.common.isPublic import io.mironov.sento.compiler.common.simpleName import io.mironov.sento.compiler.reflect.ClassSpec import io.mironov.sento.compiler.reflect.MethodSpec import org.objectweb.asm.Type internal data class ListenerClassSpec private constructor( val owner: ClassSpec, val listener: ClassSpec, val setter: MethodSpec, val unsetter: MethodSpec, val callback: MethodSpec ) { companion object { fun create(annotation: ClassSpec, binding: ListenerClass, registry: ClassRegistry): ListenerClassSpec { val ownerSpec = resolveClassSpec(binding.owner(), "owner", annotation, registry) val listenerSpec = resolveClassSpec(binding.listener(), "listener", annotation, registry) val listenerConstructor = listenerSpec.getConstructor() val listenerCallbacks = listenerSpec.methods.filter { it.name == binding.callback() } val listenerSetter = resolveMethodSpec(binding.setter(), annotation, binding, registry) val listenerUnsetter = resolveMethodSpec(binding.unsetter() ?: binding.setter(), annotation, binding, registry) if (!listenerSpec.isInterface && (listenerConstructor == null || !listenerConstructor.isPublic)) { throw SentoException("Unable to process @{0} annotation - listener type ''{1}'' must have a zero-arg constructor with public visibility.", annotation.type.simpleName, listenerSpec.type.className) } if (listenerCallbacks.size == 0) { throw SentoException("Unable to process @{0} annotation - listener type ''{1}'' must have exactly one abstract method named ''{2}'', but none was found.", annotation.type.simpleName, listenerSpec.type.className, binding.callback()) } if (listenerCallbacks.size > 1) { throw SentoException("Unable to process @{0} annotation - listener type ''{1}'' must have exactly one abstract method named ''{2}'', but {3} were found {4}.", annotation.type.simpleName, listenerSpec.type.className, binding.callback(), listenerCallbacks.size, listenerCallbacks.map { Methods.asJavaDeclaration(it) }) } listenerSpec.methods.forEach { if (it.isAbstract && it.returns !in listOf(Types.VOID, Types.BOOLEAN)) { throw SentoException("Unable to process @{0} annotation - listener method ''{1}'' returns ''{2}'', but only {3} are supported.", annotation.type.simpleName, it.name, it.returns.className, listOf(Types.VOID.className, Types.BOOLEAN.className)) } } return ListenerClassSpec(ownerSpec, listenerSpec, listenerSetter, listenerUnsetter, listenerCallbacks[0]) } private fun resolveClassSpec(name: String, kind: String, annotation: ClassSpec, registry: ClassRegistry): ClassSpec { val type = Types.getClassType(name) if (type.sort == Type.ARRAY) { throw SentoException("Unable to process @{0} annotation - $kind type mustn''t be an array, but ''{1}'' was found.", annotation.type.simpleName, type.className) } if (Types.isPrimitive(type)) { throw SentoException("Unable to process @{0} annotation - $kind type mustn''t be a primitive one, but ''{1}'' was found.", annotation.type.simpleName, type.className) } if (!registry.contains(type)) { throw SentoException("Unable to process @{0} annotation - $kind type ''{1}'' wasn''t found.", annotation.type.simpleName, type.className) } return registry.resolve(type).apply { if (!isPublic) { throw SentoException("Unable to process @{0} annotation - $kind type ''{1}'' must be public.", annotation.type.simpleName, type.className) } } } private fun resolveMethodSpec(name: String, annotation: ClassSpec, binding: ListenerClass, registry: ClassRegistry): MethodSpec { val ownerType = Types.getClassType(binding.owner()) val listenerType = Types.getClassType(binding.listener()) val ownerSpec = registry.resolve(ownerType) val listenerSpec = registry.resolve(listenerType) val listenerSetters = ownerSpec.methods.filter { it.name == name && it.arguments.size == 1 } if (listenerSetters.size == 0) { throw SentoException("Unable to process @{0} annotation - owner type ''{1}'' must have exactly one single-arg method ''{2}'', but none was found.", annotation.type.simpleName, ownerType.className, name) } if (listenerSetters.size > 1) { throw SentoException("Unable to process @{0} annotation - owner type ''{1}'' must have exactly one single-arg method ''{2}'', but {3} were found {4}.", annotation.type.simpleName, ownerType.className, name, listenerSetters.size, listenerSetters.map { Methods.asJavaDeclaration(it) }) } if (!registry.isSubclassOf(listenerSpec.type, listenerSetters[0].arguments[0])) { throw SentoException("Unable to process @{0} annotation - method ''{1}'' doesn''t accept ''{2}'' as an argument. Only subclasses of ''{3}'' are allowed.", annotation.type.simpleName, listenerSetters[0].name, listenerSpec.type.className, listenerSetters[0].arguments[0].className) } registry.resolve(listenerSetters[0].arguments[0]).methods.forEach { if (it.isAbstract && it.returns !in listOf(Types.VOID, Types.BOOLEAN)) { throw SentoException("Unable to process @{0} annotation - method ''{1}'' returns ''{2}'', but only {3} are supported.", annotation.type.simpleName, it.name, it.returns.className, listOf(Types.VOID.className, Types.BOOLEAN.className)) } } return listenerSetters[0] } } }
apache-2.0
f05bf51a27bf05f968bc805adbec7adf
48.804878
169
0.690826
4.248266
false
false
false
false
ncoe/rosetta
Lah_numbers/Kotlin/src/LahNumbers.kt
1
1258
import java.math.BigInteger fun factorial(n: BigInteger): BigInteger { if (n == BigInteger.ZERO) return BigInteger.ONE if (n == BigInteger.ONE) return BigInteger.ONE var prod = BigInteger.ONE var num = n while (num > BigInteger.ONE) { prod *= num num-- } return prod } fun lah(n: BigInteger, k: BigInteger): BigInteger { if (k == BigInteger.ONE) return factorial(n) if (k == n) return BigInteger.ONE if (k > n) return BigInteger.ZERO if (k < BigInteger.ONE || n < BigInteger.ONE) return BigInteger.ZERO return (factorial(n) * factorial(n - BigInteger.ONE)) / (factorial(k) * factorial(k - BigInteger.ONE)) / factorial(n - k) } fun main() { println("Unsigned Lah numbers: L(n, k):") print("n/k ") for (i in 0..12) { print("%10d ".format(i)) } println() for (row in 0..12) { print("%-3d".format(row)) for (i in 0..row) { val l = lah(BigInteger.valueOf(row.toLong()), BigInteger.valueOf(i.toLong())) print("%11d".format(l)) } println() } println("\nMaximum value from the L(100, *) row:") println((0..100).map { lah(BigInteger.valueOf(100.toLong()), BigInteger.valueOf(it.toLong())) }.max()) }
mit
a2c609b38731437a3fdd36a60dc54ac1
30.45
125
0.588235
3.456044
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/old/tests/test/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterSingleFileTest.kt
2
7607
// 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.j2k import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiJavaFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.impl.source.PostprocessReformattingAspect import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.test.dumpTextWithErrors import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm import org.jetbrains.kotlin.test.Directives import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.types.FlexibleTypeImpl import java.io.File import java.util.regex.Pattern abstract class AbstractJavaToKotlinConverterSingleFileTest : AbstractJavaToKotlinConverterTest() { val testHeaderPattern = Pattern.compile("//(element|expression|statement|method|class|file|comp)\n") // FIXME: remove after KTIJ-5630 private fun doTestWithSlowAssertion(directives: Directives, block: () -> Unit) { val oldValue = FlexibleTypeImpl.RUN_SLOW_ASSERTIONS try { FlexibleTypeImpl.RUN_SLOW_ASSERTIONS = directives["WITHOUT_SLOW_ASSERTIONS"] == null block() } finally { FlexibleTypeImpl.RUN_SLOW_ASSERTIONS = oldValue } } open fun doTest(javaPath: String) { val javaFile = File(javaPath) val fileContents = FileUtil.loadFile(javaFile, true) val matcher = testHeaderPattern.matcher(fileContents) val (prefix, javaCode) = if (matcher.find()) { Pair(matcher.group().trim().substring(2), matcher.replaceFirst("")) } else { Pair("file", fileContents) } val settings = ConverterSettings.defaultSettings.copy() val directives = KotlinTestUtils.parseDirectives(javaCode) doTestWithSlowAssertion(directives) { directives["FORCE_NOT_NULL_TYPES"]?.let { settings.forceNotNullTypes = it.toBoolean() } directives["SPECIFY_LOCAL_VARIABLE_TYPE_BY_DEFAULT"]?.let { settings.specifyLocalVariableTypeByDefault = it.toBoolean() } directives["SPECIFY_FIELD_TYPE_BY_DEFAULT"]?.let { settings.specifyFieldTypeByDefault = it.toBoolean() } directives["OPEN_BY_DEFAULT"]?.let { settings.openByDefault = it.toBoolean() } val rawConverted = WriteCommandAction.runWriteCommandAction(project, Computable { PostprocessReformattingAspect.getInstance(project).doPostponedFormatting() return@Computable when (prefix) { "expression" -> expressionToKotlin(javaCode, settings, project) "statement" -> statementToKotlin(javaCode, settings, project) "method" -> methodToKotlin(javaCode, settings, project) "class" -> fileToKotlin(javaCode, settings, project) "file" -> fileToKotlin(javaCode, settings, project) else -> throw IllegalStateException( "Specify what is it: file, class, method, statement or expression using the first line of test data file" ) } }) val reformatInFun = prefix in setOf("element", "expression", "statement") var actual = reformat(rawConverted, project, reformatInFun) if (prefix == "file") { actual = createKotlinFile(actual) .dumpTextWithErrors(setOf(element = ErrorsJvm.INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET_ERROR)) } val expectedFile = provideExpectedFile(javaPath) compareResults(expectedFile, actual) } } open fun provideExpectedFile(javaPath: String): File { val kotlinPath = javaPath.replace(".java", ".kt") return File(kotlinPath) } open fun compareResults(expectedFile: File, actual: String) { KotlinTestUtils.assertEqualsToFile(expectedFile, actual) } private fun reformat(text: String, project: Project, inFunContext: Boolean): String { val funBody = text.lines().joinToString(separator = "\n", transform = { " $it" }) val textToFormat = if (inFunContext) "fun convertedTemp() {\n$funBody\n}" else text val convertedFile = KotlinTestUtils.createFile("converted", textToFormat, project) WriteCommandAction.runWriteCommandAction(project) { CodeStyleManager.getInstance(project)!!.reformat(convertedFile) } val reformattedText = convertedFile.text!! return if (inFunContext) reformattedText.removeFirstLine().removeLastLine().trimIndent() else reformattedText } protected open fun fileToKotlin(text: String, settings: ConverterSettings, project: Project): String { val file = createJavaFile(text) val converter = OldJavaToKotlinConverter(project, settings, IdeaJavaToKotlinServices) return converter.filesToKotlin(listOf(file), J2kPostProcessor(formatCode = true)).results.single() } private fun methodToKotlin(text: String, settings: ConverterSettings, project: Project): String { val result = fileToKotlin("final class C {$text}", settings, project) return result .substringBeforeLast("}") .replace("internal class C {", "\n") .replace("internal object C {", "\n") .trimIndent().trim() } private fun statementToKotlin(text: String, settings: ConverterSettings, project: Project): String { val funBody = text.lines().joinToString(separator = "\n", transform = { " $it" }) val result = methodToKotlin("public void main() {\n$funBody\n}", settings, project) return result .substringBeforeLast("}") .replaceFirst("fun main() {", "\n") .trimIndent().trim() } private fun expressionToKotlin(code: String, settings: ConverterSettings, project: Project): String { val result = statementToKotlin("final Object o =$code}", settings, project) return result .replaceFirst("val o: Any? = ", "") .replaceFirst("val o: Any = ", "") .replaceFirst("val o = ", "") .trim() } override fun getProjectDescriptor(): KotlinWithJdkAndRuntimeLightProjectDescriptor { val testName = getTestName(false) return if (testName.contains("WithFullJdk") || testName.contains("withFullJdk")) KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK else KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } private fun String.removeFirstLine() = substringAfter('\n', "") private fun String.removeLastLine() = substringBeforeLast('\n', "") protected fun createJavaFile(text: String): PsiJavaFile { return myFixture.configureByText("converterTestFile.java", text) as PsiJavaFile } protected fun createKotlinFile(text: String): KtFile { return myFixture.configureByText("converterTestFile.kt", text) as KtFile } }
apache-2.0
314a14e429af83685f0f10cf947e4bae
42.971098
158
0.665571
4.962166
false
true
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/ch0202/OfflineNetworkingSession.kt
1
3522
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch0202 import cc.altruix.econsimtr01.DefaultAction import cc.altruix.econsimtr01.IActionSubscriber import cc.altruix.econsimtr01.randomEventWithProbability import org.joda.time.DateTime /** * Created by pisarenko on 27.04.2016. */ open class OfflineNetworkingSession(val agent: Protagonist, val maxNetworkingSessionsPerBusinessDay: Int, val timePerOfflineNetworkingSession:Double, val recommendationConversion:Double, val willingnessToPurchaseConversion:Double, val population: IPopulation) : DefaultAction( OfflineNetworkingSessionTriggerFun( agent, maxNetworkingSessionsPerBusinessDay ) ) { override fun run(time: DateTime) { if (!validate()) { return } val meetingPartner = findMeetingPartner() if (meetingPartner != null) { agent.offlineNetworkingSessionsHeldDuringCurrentDay++ agent.remove(Sim1ParametersProvider.RESOURCE_AVAILABLE_TIME.id, timePerOfflineNetworkingSession) updateWillingnessToRecommend(meetingPartner) updateWillingnessToPurchase(meetingPartner) meetingPartner.offlineNetworkingSessionHeld = true } } open fun updateWillingnessToPurchase(meetingPartner: Person) { if (experiment(willingnessToPurchaseConversion)) { meetingPartner.willingToPurchase = true } } open fun updateWillingnessToRecommend(meetingPartner: Person) { if (experiment(recommendationConversion)) { meetingPartner.willingToRecommend = true } } open fun experiment(probability:Double):Boolean = randomEventWithProbability(probability) open fun findMeetingPartner(): Person? = population.people() .filter { it.willingToMeet && !it.offlineNetworkingSessionHeld } .firstOrNull() open fun validate():Boolean { if (agent.offlineNetworkingSessionsHeldDuringCurrentDay >= maxNetworkingSessionsPerBusinessDay) { return false } if (agent.amount(Sim1ParametersProvider.RESOURCE_AVAILABLE_TIME.id) < timePerOfflineNetworkingSession) { return false } return true } override fun notifySubscribers(time: DateTime) { } override fun subscribe(subscriber: IActionSubscriber) { } }
gpl-3.0
3314725f8fe0b9d0c1667d68ae1cd6d7
34.22
112
0.668086
4.708556
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt
2
1494
// 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.references import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtNameReferenceExpression abstract class SyntheticPropertyAccessorReference( expression: KtNameReferenceExpression, val getter: Boolean ) : KtSimpleReference<KtNameReferenceExpression>(expression) { override fun isReferenceTo(element: PsiElement): Boolean { if (element !is PsiMethod || !isAccessorName(element.name)) return false if (!getter && expression.readWriteAccess(true) == ReferenceAccess.READ) return false return additionalIsReferenceToChecker(element) } protected abstract fun additionalIsReferenceToChecker(element: PsiElement): Boolean private fun isAccessorName(name: String): Boolean { if (getter) { return name.startsWith("get") || name.startsWith("is") } return name.startsWith("set") } override fun getRangeInElement() = TextRange(0, expression.textLength) override fun canRename() = true abstract override fun handleElementRename(newElementName: String): PsiElement? override val resolvesByNames: Collection<Name> get() = listOf(element.getReferencedNameAsName()) }
apache-2.0
5caf511438964005f2f24cd38a250ce4
37.307692
158
0.749665
4.930693
false
false
false
false
chemickypes/Glitchy
glitchappcore/src/main/java/me/bemind/glitchappcore/app/Implementations.kt
1
2126
package me.bemind.glitchappcore.app import android.content.res.Configuration import android.os.Bundle import me.bemind.glitchappcore.EffectState import me.bemind.glitchappcore.GlitchyBaseActivity import me.bemind.glitchappcore.State /** * Created by angelomoroni on 18/04/17. */ class AppPresenter : IAppPresenter { private val STATE_K = "state_k" private val EFFECT_LAYOUT_K = "effect_l_k" private val EMPTY_IMAGE_IEW_K = "empty_image_view_k" private var savedInstanceState : Bundle? = null override var modState: State = State.BASE set(value) { field = value appView?.updateState(field) if(value == State.BASE) effectState = null } override var effectState: EffectState? = null override var appView: IAppView? = null override var emptyImageView = true override fun saveInstanceState(activity: GlitchyBaseActivity, outState: Bundle?) { outState?.putSerializable(STATE_K,modState) if(effectState!=null) outState?.putParcelable(EFFECT_LAYOUT_K,effectState) outState?.putBoolean(EMPTY_IMAGE_IEW_K,emptyImageView) } override fun restoreInstanceState(activity: GlitchyBaseActivity, savedInstanceState: Bundle?) { this.savedInstanceState = savedInstanceState if(savedInstanceState?.containsKey(STATE_K)?:false) modState = savedInstanceState?.getSerializable(STATE_K) as State if(savedInstanceState?.containsKey(EFFECT_LAYOUT_K)?:false) effectState = savedInstanceState?.getParcelable(EFFECT_LAYOUT_K) savedInstanceState?.containsKey(EMPTY_IMAGE_IEW_K)?.let { emptyImageView = savedInstanceState.getBoolean(EMPTY_IMAGE_IEW_K,false) } } override fun onBackPressed(): Boolean { if(modState!=State.BASE){ modState = State.BASE return true }else{ return false } } override fun onResume() { appView?.restoreView(effectState,emptyImageView) appView?.updateState(modState) } override fun onConfigurationChanged(newConfig: Configuration?) { } }
apache-2.0
e29a159fa767c3cd9a255a9344018d62
30.264706
132
0.69238
4.22664
false
true
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/ReindexAction.kt
9
1506
// 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.util.indexing import com.intellij.ide.actions.cache.CacheInconsistencyProblem import com.intellij.ide.actions.cache.ProjectRecoveryScope import com.intellij.ide.actions.cache.RecoveryAction import com.intellij.ide.actions.cache.RecoveryScope import com.intellij.lang.LangBundle import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.project.DumbUtilImpl import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls @ApiStatus.Internal class ReindexAction : RecoveryAction { override val performanceRate: Int get() = 1000 override val presentableName: @Nls(capitalization = Nls.Capitalization.Title) String get() = LangBundle.message("reindex.project.recovery.action.name") override val actionKey: String get() = "reindex" override fun performSync(recoveryScope: RecoveryScope): List<CacheInconsistencyProblem> { invokeAndWaitIfNeeded { val tumbler = FileBasedIndexTumbler("Reindex recovery action") tumbler.turnOff() try { CorruptionMarker.requestInvalidation() } finally { tumbler.turnOn() } } DumbUtilImpl.waitForSmartMode(recoveryScope.project) return emptyList() } override fun canBeApplied(recoveryScope: RecoveryScope): Boolean = recoveryScope is ProjectRecoveryScope }
apache-2.0
eca293ca3db61d0ff5eaa92d5618978d
36.675
158
0.778884
4.365217
false
false
false
false
yschimke/okhttp
okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt
4
5766
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.tls.internal.der import java.math.BigInteger import okio.Buffer import okio.BufferedSink import okio.ByteString internal class DerWriter(sink: BufferedSink) { /** A stack of buffers that will be concatenated once we know the length of each. */ private val stack = mutableListOf(sink) /** Type hints scoped to the call stack, manipulated with [pushTypeHint] and [popTypeHint]. */ private val typeHintStack = mutableListOf<Any?>() /** * The type hint for the current object. Used to pick adapters based on other fields, such as * in extensions which have different types depending on their extension ID. */ var typeHint: Any? get() = typeHintStack.lastOrNull() set(value) { typeHintStack[typeHintStack.size - 1] = value } /** Names leading to the current location in the ASN.1 document. */ private val path = mutableListOf<String>() /** * False unless we made a recursive call to [write] at the current stack frame. The explicit box * adapter can clear this to synthesize non-constructed values that are embedded in octet strings. */ var constructed = false fun write(name: String, tagClass: Int, tag: Long, block: (BufferedSink) -> Unit) { val constructedBit: Int val content = Buffer() stack.add(content) constructed = false // The enclosed object written in block() is not constructed. path += name try { block(content) constructedBit = if (constructed) 0b0010_0000 else 0 constructed = true // The enclosing object is constructed. } finally { stack.removeAt(stack.size - 1) path.removeAt(path.size - 1) } val sink = sink() // Write the tagClass, tag, and constructed bit. This takes 1 byte if tag is less than 31. if (tag < 31) { val byte0 = tagClass or constructedBit or tag.toInt() sink.writeByte(byte0) } else { val byte0 = tagClass or constructedBit or 0b0001_1111 sink.writeByte(byte0) writeVariableLengthLong(tag) } // Write the length. This takes 1 byte if length is less than 128. val length = content.size if (length < 128) { sink.writeByte(length.toInt()) } else { // count how many bytes we'll need to express the length. val lengthBitCount = 64 - java.lang.Long.numberOfLeadingZeros(length) val lengthByteCount = (lengthBitCount + 7) / 8 sink.writeByte(0b1000_0000 or lengthByteCount) for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) { sink.writeByte((length shr shift).toInt()) } } // Write the payload. sink.writeAll(content) } /** * Execute [block] with a new namespace for type hints. Type hints from the enclosing type are no * longer usable by the current type's members. */ fun <T> withTypeHint(block: () -> T): T { typeHintStack.add(null) try { return block() } finally { typeHintStack.removeAt(typeHintStack.size - 1) } } private fun sink(): BufferedSink = stack[stack.size - 1] fun writeBoolean(b: Boolean) { sink().writeByte(if (b) -1 else 0) } fun writeBigInteger(value: BigInteger) { sink().write(value.toByteArray()) } fun writeLong(v: Long) { val sink = sink() val lengthBitCount: Int = if (v < 0L) { 65 - java.lang.Long.numberOfLeadingZeros(v xor -1L) } else { 65 - java.lang.Long.numberOfLeadingZeros(v) } val lengthByteCount = (lengthBitCount + 7) / 8 for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) { sink.writeByte((v shr shift).toInt()) } } fun writeBitString(bitString: BitString) { val sink = sink() sink.writeByte(bitString.unusedBitsCount) sink.write(bitString.byteString) } fun writeOctetString(byteString: ByteString) { sink().write(byteString) } fun writeUtf8(value: String) { sink().writeUtf8(value) } fun writeObjectIdentifier(s: String) { val utf8 = Buffer().writeUtf8(s) val v1 = utf8.readDecimalLong() require(utf8.readByte() == '.'.code.toByte()) val v2 = utf8.readDecimalLong() writeVariableLengthLong(v1 * 40 + v2) while (!utf8.exhausted()) { require(utf8.readByte() == '.'.code.toByte()) val vN = utf8.readDecimalLong() writeVariableLengthLong(vN) } } fun writeRelativeObjectIdentifier(s: String) { // Add a leading dot so each subidentifier has a dot prefix. val utf8 = Buffer() .writeByte('.'.code.toByte().toInt()) .writeUtf8(s) while (!utf8.exhausted()) { require(utf8.readByte() == '.'.code.toByte()) val vN = utf8.readDecimalLong() writeVariableLengthLong(vN) } } /** Used for tags and subidentifiers. */ private fun writeVariableLengthLong(v: Long) { val sink = sink() val bitCount = 64 - java.lang.Long.numberOfLeadingZeros(v) val byteCount = (bitCount + 6) / 7 for (shift in (byteCount - 1) * 7 downTo 0 step 7) { val lastBit = if (shift == 0) 0 else 0b1000_0000 sink.writeByte(((v shr shift) and 0b0111_1111).toInt() or lastBit) } } override fun toString(): String = path.joinToString(separator = " / ") }
apache-2.0
9f4516f47a5e8aa44d1cdb7b74e5d6bc
30
100
0.661464
3.971074
false
false
false
false
androidx/androidx
wear/watchface/watchface-client-guava/src/androidTest/java/androidx/wear/watchface/client/guava/ListenableWatchFaceControlClientTest.kt
3
14619
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.client.guava import android.content.ComponentName import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.view.Surface import android.view.SurfaceHolder import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.wear.watchface.CanvasType import androidx.wear.watchface.ComplicationSlotsManager import androidx.wear.watchface.Renderer import androidx.wear.watchface.WatchFace import androidx.wear.watchface.WatchFaceService import androidx.wear.watchface.WatchFaceType import androidx.wear.watchface.WatchState import androidx.wear.watchface.client.DeviceConfig import androidx.wear.watchface.client.ListenableWatchFaceControlClient import androidx.wear.watchface.client.WatchUiState import androidx.wear.watchface.samples.ExampleCanvasAnalogWatchFaceService import androidx.wear.watchface.style.CurrentUserStyleRepository import com.google.common.truth.Truth.assertThat import java.time.ZonedDateTime import java.util.concurrent.CountDownLatch import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations import java.util.concurrent.TimeUnit import org.junit.Assert private const val TIMEOUT_MS = 500L @RunWith(AndroidJUnit4::class) @MediumTest public class ListenableWatchFaceControlClientTest { @Mock private lateinit var surfaceHolder: SurfaceHolder @Mock private lateinit var surface: Surface private val context = ApplicationProvider.getApplicationContext<Context>() @Before public fun setUp() { MockitoAnnotations.initMocks(this) Mockito.`when`(surfaceHolder.surfaceFrame) .thenReturn(Rect(0, 0, 400, 400)) Mockito.`when`(surfaceHolder.surface).thenReturn(surface) } @Test @Suppress("Deprecation") // userStyleSettings public fun headlessSchemaSettingIds() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) val headlessInstance = client.createHeadlessWatchFaceClient( "id", ComponentName(context, ExampleCanvasAnalogWatchFaceService::class.java), DeviceConfig( false, false, 0, 0 ), 400, 400 )!! assertThat(headlessInstance.userStyleSchema.userStyleSettings.map { it.id.value }) .containsExactly( "color_style_setting", "draw_hour_pips_style_setting", "watch_hand_length_style_setting", "complications_style_setting", "hours_draw_freq_style_setting" ) headlessInstance.close() client.close() } @Test public fun createHeadlessWatchFaceClient_nonExistentWatchFaceComponentName() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) assertNull( client.createHeadlessWatchFaceClient( "id", ComponentName("?", "i.do.not.exist"), DeviceConfig( false, false, 0, 0 ), 400, 400 ) ) client.close() } @Test @Suppress("Deprecation") // userStyleSettings public fun listenableGetOrCreateWallpaperServiceBackedInteractiveWatchFaceWcsClient() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) @Suppress("deprecation") val interactiveInstanceFuture = client.listenableGetOrCreateInteractiveWatchFaceClient( "listenableTestId", DeviceConfig( false, false, 0, 0 ), WatchUiState(false, 0), null, null ) val service = object : ExampleCanvasAnalogWatchFaceService() { init { attachBaseContext(context) } } service.onCreateEngine().onSurfaceChanged( surfaceHolder, 0, surfaceHolder.surfaceFrame.width(), surfaceHolder.surfaceFrame.height() ) val interactiveInstance = interactiveInstanceFuture.get(TIMEOUT_MS, TimeUnit.MILLISECONDS) assertThat(interactiveInstance.userStyleSchema.userStyleSettings.map { it.id.value }) .containsExactly( "color_style_setting", "draw_hour_pips_style_setting", "watch_hand_length_style_setting", "complications_style_setting", "hours_draw_freq_style_setting" ) interactiveInstance.close() client.close() } @Test public fun createMultipleHeadlessInstances() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) val headlessInstance1 = client.createHeadlessWatchFaceClient( "id1", ComponentName(context, ExampleCanvasAnalogWatchFaceService::class.java), DeviceConfig( false, false, 0, 0 ), 400, 400 )!! val headlessInstance2 = client.createHeadlessWatchFaceClient( "id2", ComponentName(context, ExampleCanvasAnalogWatchFaceService::class.java), DeviceConfig( false, false, 0, 0 ), 400, 400 )!! val headlessInstance3 = client.createHeadlessWatchFaceClient( "id3", ComponentName(context, ExampleCanvasAnalogWatchFaceService::class.java), DeviceConfig( false, false, 0, 0 ), 400, 400 )!! headlessInstance3.close() headlessInstance2.close() headlessInstance1.close() client.close() } @Test public fun createInteractiveAndHeadlessInstances() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) @Suppress("deprecation") val interactiveInstanceFuture = client.listenableGetOrCreateInteractiveWatchFaceClient( "listenableTestId", DeviceConfig( false, false, 0, 0 ), WatchUiState(false, 0), null, null ) val service = object : ExampleCanvasAnalogWatchFaceService() { init { attachBaseContext(context) } } service.onCreateEngine().onSurfaceChanged( surfaceHolder, 0, surfaceHolder.surfaceFrame.width(), surfaceHolder.surfaceFrame.height() ) val interactiveInstance = interactiveInstanceFuture.get(TIMEOUT_MS, TimeUnit.MILLISECONDS) val headlessInstance1 = client.createHeadlessWatchFaceClient( "id", ComponentName(context, ExampleCanvasAnalogWatchFaceService::class.java), DeviceConfig( false, false, 0, 0 ), 400, 400 )!! headlessInstance1.close() interactiveInstance.close() client.close() } @Test public fun getInteractiveWatchFaceInstanceSysUI_notExist() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) assertNull(client.getInteractiveWatchFaceClientInstance("I do not exist")) } @Test public fun createWatchFaceControlClient_cancel() { ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).cancel(true) // Canceling should not prevent a subsequent createWatchFaceControlClient. val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) assertThat(client).isNotNull() client.close() } @Test public fun listenableGetOrCreateInteractiveWatchFaceClient_cancel() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) @Suppress("deprecation") client.listenableGetOrCreateInteractiveWatchFaceClient( "listenableTestId", DeviceConfig( false, false, 0, 0 ), WatchUiState(false, 0), null, null ).cancel(true) // Canceling should not prevent a subsequent listenableGetOrCreateInteractiveWatchFaceClient @Suppress("deprecation") val interactiveInstanceFuture = client.listenableGetOrCreateInteractiveWatchFaceClient( "listenableTestId", DeviceConfig( false, false, 0, 0 ), WatchUiState(false, 0), null, null ) val service = object : ExampleCanvasAnalogWatchFaceService() { init { attachBaseContext(context) } } service.onCreateEngine().onSurfaceChanged( surfaceHolder, 0, surfaceHolder.surfaceFrame.width(), surfaceHolder.surfaceFrame.height() ) val interactiveInstance = interactiveInstanceFuture.get(TIMEOUT_MS, TimeUnit.MILLISECONDS) assertThat(interactiveInstance).isNotNull() interactiveInstance.close() client.close() } @Test public fun previewImageUpdateRequestedListener() { val client = ListenableWatchFaceControlClient.createWatchFaceControlClient( context, context.packageName ).get(TIMEOUT_MS, TimeUnit.MILLISECONDS) var lastPreviewImageUpdateRequestedId = "" val interactiveInstanceFuture = client.listenableGetOrCreateInteractiveWatchFaceClient( "listenableTestId", DeviceConfig( false, false, 0, 0 ), WatchUiState(false, 0), null, null, { runnable -> runnable.run() }, { lastPreviewImageUpdateRequestedId = it } ) val service = TestWatchFaceServiceWithPreviewImageUpdateRequest(context, surfaceHolder) service.onCreateEngine().onSurfaceChanged( surfaceHolder, 0, surfaceHolder.surfaceFrame.width(), surfaceHolder.surfaceFrame.height() ) val interactiveInstance = interactiveInstanceFuture.get(TIMEOUT_MS, TimeUnit.MILLISECONDS) Assert.assertTrue(service.rendererInitializedLatch.await(500, TimeUnit.MILLISECONDS)) assertThat(lastPreviewImageUpdateRequestedId).isEmpty() service.triggerPreviewImageUpdateRequest() assertThat(lastPreviewImageUpdateRequestedId).isEqualTo("listenableTestId") interactiveInstance.close() } } internal class TestWatchFaceServiceWithPreviewImageUpdateRequest( testContext: Context, private var surfaceHolderOverride: SurfaceHolder, ) : WatchFaceService() { val rendererInitializedLatch = CountDownLatch(1) init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride @Suppress("deprecation") private lateinit var renderer: Renderer.CanvasRenderer fun triggerPreviewImageUpdateRequest() { renderer.sendPreviewImageNeedsUpdateRequest() } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ): WatchFace { @Suppress("deprecation") renderer = object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override suspend fun init() { rendererInitializedLatch.countDown() } override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) {} override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) {} } return WatchFace(WatchFaceType.DIGITAL, renderer) } }
apache-2.0
f2ae99854dd50ff159b254b880a5a784
31.061404
100
0.608592
5.529123
false
true
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/RenameSimpleTab.kt
1
8030
package com.simplemobiletools.commons.views import android.content.ContentValues import android.content.Context import android.provider.MediaStore import android.util.AttributeSet import android.widget.RelativeLayout import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.interfaces.RenameTab import com.simplemobiletools.commons.models.Android30RenameFormat import com.simplemobiletools.commons.models.FileDirItem import kotlinx.android.synthetic.main.tab_rename_simple.view.* import java.io.File class RenameSimpleTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), RenameTab { var ignoreClicks = false var stopLooping = false // we should request the permission on Android 30+ for all uris at once, not one by one var activity: BaseSimpleActivity? = null var paths = ArrayList<String>() override fun onFinishInflate() { super.onFinishInflate() context.updateTextColors(rename_simple_holder) } override fun initTab(activity: BaseSimpleActivity, paths: ArrayList<String>) { this.activity = activity this.paths = paths } override fun dialogConfirmed(useMediaFileExtension: Boolean, callback: (success: Boolean) -> Unit) { stopLooping = false val valueToAdd = rename_simple_value.text.toString() val append = rename_simple_radio_group.checkedRadioButtonId == rename_simple_radio_append.id if (valueToAdd.isEmpty()) { callback(false) return } if (!valueToAdd.isAValidFilename()) { activity?.toast(R.string.invalid_name) return } val validPaths = paths.filter { activity?.getDoesFilePathExist(it) == true } val firstPath = validPaths.firstOrNull() val sdFilePath = validPaths.firstOrNull { activity?.isPathOnSD(it) == true } ?: firstPath if (firstPath == null || sdFilePath == null) { activity?.toast(R.string.unknown_error_occurred) return } activity?.handleSAFDialog(sdFilePath) { if (!it) { return@handleSAFDialog } activity?.checkManageMediaOrHandleSAFDialogSdk30(firstPath) { if (!it) { return@checkManageMediaOrHandleSAFDialogSdk30 } ignoreClicks = true var pathsCnt = validPaths.size for (path in validPaths) { if (stopLooping) { return@checkManageMediaOrHandleSAFDialogSdk30 } val fullName = path.getFilenameFromPath() var dotAt = fullName.lastIndexOf(".") if (dotAt == -1) { dotAt = fullName.length } val name = fullName.substring(0, dotAt) val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else "" val newName = if (append) { "$name$valueToAdd$extension" } else { "$valueToAdd$fullName" } val newPath = "${path.getParentPath()}/$newName" if (activity?.getDoesFilePathExist(newPath) == true) { continue } activity?.renameFile(path, newPath, true) { success, android30Format -> if (success) { pathsCnt-- if (pathsCnt == 0) { callback(true) } } else { ignoreClicks = false if (android30Format != Android30RenameFormat.NONE) { stopLooping = true renameAllFiles(validPaths, append, valueToAdd, android30Format, callback) } } } } stopLooping = false } } } private fun renameAllFiles( paths: List<String>, appendString: Boolean, stringToAdd: String, android30Format: Android30RenameFormat, callback: (success: Boolean) -> Unit ) { val fileDirItems = paths.map { File(it).toFileDirItem(context) } val uriPairs = context.getUrisPathsFromFileDirItems(fileDirItems) val validPaths = uriPairs.first val uris = uriPairs.second val activity = activity activity?.updateSDK30Uris(uris) { success -> if (success) { try { uris.forEachIndexed { index, uri -> val path = validPaths[index] val fullName = path.getFilenameFromPath() var dotAt = fullName.lastIndexOf(".") if (dotAt == -1) { dotAt = fullName.length } val name = fullName.substring(0, dotAt) val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else "" val newName = if (appendString) { "$name$stringToAdd$extension" } else { "$stringToAdd$fullName" } when (android30Format) { Android30RenameFormat.SAF -> { val sourceFile = File(path).toFileDirItem(activity) val newPath = "${path.getParentPath()}/$newName" val destinationFile = FileDirItem( newPath, newName, sourceFile.isDirectory, sourceFile.children, sourceFile.size, sourceFile.modified ) if (activity.copySingleFileSdk30(sourceFile, destinationFile)) { if (!activity.baseConfig.keepLastModified) { File(newPath).setLastModified(System.currentTimeMillis()) } activity.contentResolver.delete(uri, null) activity.updateInMediaStore(path, newPath) activity.scanPathsRecursively(arrayListOf(newPath)) } } Android30RenameFormat.CONTENT_RESOLVER -> { val values = ContentValues().apply { put(MediaStore.Images.Media.DISPLAY_NAME, newName) } context.contentResolver.update(uri, values, null, null) } Android30RenameFormat.NONE -> { activity.runOnUiThread { callback(true) } return@forEachIndexed } } } activity.runOnUiThread { callback(true) } } catch (e: Exception) { activity.runOnUiThread { activity.showErrorToast(e) callback(false) } } } } } }
gpl-3.0
c78cd194d251a41d2a63f312b4ad22dc
40.391753
119
0.482814
6.078728
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-reference-index/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerReferenceIndexStorage.kt
1
7789
// 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.search.refIndex import com.intellij.compiler.server.BuildManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.MultiMap import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.io.CorruptedException import com.intellij.util.io.EnumeratorStringDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.builders.impl.BuildDataPathsImpl import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.kotlin.config.SettingConstants import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.incremental.KOTLIN_CACHE_DIRECTORY_NAME import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner import org.jetbrains.kotlin.incremental.storage.CollectionExternalizer import org.jetbrains.kotlin.name.FqName import java.nio.file.Path import java.util.concurrent.Future import kotlin.io.path.* import kotlin.system.measureTimeMillis class KotlinCompilerReferenceIndexStorage private constructor( kotlinDataContainerPath: Path, private val lookupStorageReader: LookupStorageReader, ) { companion object { /** * [org.jetbrains.kotlin.incremental.AbstractIncrementalCache.Companion.SUBTYPES] */ private val SUBTYPES_STORAGE_NAME = "subtypes.${BasicMapsOwner.CACHE_EXTENSION}" private val STORAGE_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Kotlin compiler references indexing", UnindexedFilesUpdater.getMaxNumberOfIndexingThreads() ) private val LOG = logger<KotlinCompilerReferenceIndexStorage>() fun open(project: Project): KotlinCompilerReferenceIndexStorage? { val projectPath = runReadAction { project.takeUnless(Project::isDisposed)?.basePath } ?: return null val buildDataPaths = project.buildDataPaths val kotlinDataContainerPath = buildDataPaths?.kotlinDataContainer ?: kotlin.run { LOG.warn("${SettingConstants.KOTLIN_DATA_CONTAINER_ID} is not found") return null } val lookupStorageReader = LookupStorageReader.create(kotlinDataContainerPath, projectPath) ?: kotlin.run { LOG.warn("LookupStorage not found or corrupted") return null } val storage = KotlinCompilerReferenceIndexStorage(kotlinDataContainerPath, lookupStorageReader) if (!storage.initialize(buildDataPaths)) return null return storage } fun close(storage: KotlinCompilerReferenceIndexStorage?) { storage?.close().let { LOG.info("KCRI storage is closed" + if (it == null) " (didn't exist)" else "") } } fun hasIndex(project: Project): Boolean = LookupStorageReader.hasStorage(project) @TestOnly fun initializeForTests( buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage, ) = initializeSubtypeStorage(buildDataPaths, destination) internal val Project.buildDataPaths: BuildDataPaths? get() = BuildManager.getInstance().getProjectSystemDirectory(this)?.let(::BuildDataPathsImpl) internal val BuildDataPaths.kotlinDataContainer: Path? get() = targetsDataRoot?.toPath() ?.resolve(SettingConstants.KOTLIN_DATA_CONTAINER_ID) ?.takeIf { it.exists() && it.isDirectory() } ?.listDirectoryEntries("${SettingConstants.KOTLIN_DATA_CONTAINER_ID}*") ?.firstOrNull() private fun initializeSubtypeStorage(buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage): Boolean { var wasCorrupted = false val destinationMap = MultiMap.createConcurrentSet<String, String>() val futures = mutableListOf<Future<*>>() val timeOfFilling = measureTimeMillis { visitSubtypeStorages(buildDataPaths) { storagePath -> futures += STORAGE_INDEXING_EXECUTOR.submit { try { initializeStorage(destinationMap, storagePath) } catch (e: CorruptedException) { wasCorrupted = true LOG.warn("KCRI storage was corrupted", e) } } } try { for (future in futures) { future.get() } } catch (e: InterruptedException) { LOG.warn("KCRI initialization was interrupted") throw e } } if (wasCorrupted) return false val timeOfFlush = measureTimeMillis { for ((key, values) in destinationMap.entrySet()) { destination.put(key, values) } } LOG.info("KCRI storage is opened: took ${timeOfFilling + timeOfFlush} ms for ${futures.size} storages (filling map: $timeOfFilling ms, flush to storage: $timeOfFlush ms)") return true } private fun visitSubtypeStorages(buildDataPaths: BuildDataPaths, processor: (Path) -> Unit) { for (buildTargetType in JavaModuleBuildTargetType.ALL_TYPES) { val buildTargetPath = buildDataPaths.getTargetTypeDataRoot(buildTargetType).toPath() if (buildTargetPath.notExists() || !buildTargetPath.isDirectory()) continue buildTargetPath.forEachDirectoryEntry { targetDataRoot -> val workingPath = targetDataRoot.takeIf { it.isDirectory() } ?.resolve(KOTLIN_CACHE_DIRECTORY_NAME) ?.resolve(SUBTYPES_STORAGE_NAME) ?.takeUnless { it.notExists() } ?: return@forEachDirectoryEntry processor(workingPath) } } } } private val subtypesStorage = ClassOneToManyStorage(kotlinDataContainerPath.resolve(SUBTYPES_STORAGE_NAME)) /** * @return true if initialization was successful */ private fun initialize(buildDataPaths: BuildDataPaths): Boolean = initializeSubtypeStorage(buildDataPaths, subtypesStorage) private fun close() { lookupStorageReader.close() subtypesStorage.closeAndClean() } fun getUsages(fqName: FqName): List<VirtualFile> = lookupStorageReader[fqName].mapNotNull { VfsUtil.findFile(it, false) } fun getSubtypesOf(fqName: FqName, deep: Boolean): Sequence<FqName> = subtypesStorage[fqName, deep] } private fun initializeStorage(destinationMap: MultiMap<String, String>, subtypesSourcePath: Path) { createKotlinDataReader(subtypesSourcePath).use { source -> source.processKeys { key -> source[key]?.let { values -> destinationMap.putValues(key, values) } true } } } private fun createKotlinDataReader(storagePath: Path): PersistentHashMap<String, Collection<String>> = openReadOnlyPersistentHashMap( storagePath, EnumeratorStringDescriptor.INSTANCE, CollectionExternalizer<String>(EnumeratorStringDescriptor.INSTANCE, ::SmartList), )
apache-2.0
0641864de967d246d559ca6ad2b15e90
42.758427
183
0.663757
5.394044
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceExplicitFunctionLiteralParamWithItIntention.kt
3
6060
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.refactoring.rename.RenameProcessor import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.descriptors.ParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ReplaceExplicitFunctionLiteralParamWithItIntention : PsiElementBaseIntentionAction() { override fun getFamilyName() = KotlinBundle.message("replace.explicit.lambda.parameter.with.it") override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { val functionLiteral = targetFunctionLiteral(element, editor.caretModel.offset) ?: return false val parameter = functionLiteral.valueParameters.singleOrNull() ?: return false if (parameter.typeReference != null) return false if (parameter.destructuringDeclaration != null) return false if (functionLiteral.anyDescendantOfType<KtFunctionLiteral> { literal -> literal.usesName(element.text) && (!literal.hasParameterSpecification() || literal.usesName("it")) }) return false val lambda = functionLiteral.parent as? KtLambdaExpression ?: return false val lambdaParent = lambda.parent if (lambdaParent is KtWhenEntry || lambdaParent is KtContainerNodeForControlStructureBody) return false val call = lambda.getStrictParentOfType<KtCallExpression>() if (call != null) { val argumentIndex = call.valueArguments.indexOfFirst { it.getArgumentExpression() == lambda } val callOrQualified = call.getQualifiedExpressionForSelectorOrThis() val newCallOrQualified = callOrQualified.copied() val newCall = newCallOrQualified.safeAs<KtQualifiedExpression>()?.callExpression ?: newCallOrQualified as? KtCallExpression ?: return false val newArgument = newCall.valueArguments.getOrNull(argumentIndex) ?: newCall.lambdaArguments.singleOrNull() ?: return false newArgument.replace(KtPsiFactory(element).createLambdaExpression("", "TODO()")) val newContext = newCallOrQualified.analyzeAsReplacement(callOrQualified, callOrQualified.analyze(BodyResolveMode.PARTIAL)) if (newCallOrQualified.getResolvedCall(newContext)?.resultingDescriptor == null) return false } text = KotlinBundle.message("replace.explicit.parameter.0.with.it", parameter.name.toString()) return true } private fun KtFunctionLiteral.usesName(name: String): Boolean = anyDescendantOfType<KtSimpleNameExpression> { nameExpr -> nameExpr.getReferencedName() == name } override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor, element: PsiElement) { val caretOffset = editor.caretModel.offset val functionLiteral = targetFunctionLiteral(element, editor.caretModel.offset) ?: return val cursorInParameterList = functionLiteral.valueParameterList?.textRange?.containsOffset(caretOffset) ?: return ParamRenamingProcessor(editor, functionLiteral, cursorInParameterList).run() } private fun targetFunctionLiteral(element: PsiElement, caretOffset: Int): KtFunctionLiteral? { val expression = element.getParentOfType<KtNameReferenceExpression>(true) if (expression != null) { val target = expression.resolveMainReferenceToDescriptors().singleOrNull() as? ParameterDescriptor ?: return null val functionDescriptor = target.containingDeclaration as? AnonymousFunctionDescriptor ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor) as? KtFunctionLiteral } val functionLiteral = element.getParentOfType<KtFunctionLiteral>(true) ?: return null val arrow = functionLiteral.arrow ?: return null if (caretOffset > arrow.endOffset) return null return functionLiteral } private class ParamRenamingProcessor( val editor: Editor, val functionLiteral: KtFunctionLiteral, val cursorWasInParameterList: Boolean ) : RenameProcessor( editor.project!!, functionLiteral.valueParameters.single(), "it", false, false ) { override fun performRefactoring(usages: Array<out UsageInfo>) { super.performRefactoring(usages) functionLiteral.deleteChildRange(functionLiteral.valueParameterList, functionLiteral.arrow ?: return) if (cursorWasInParameterList) { editor.caretModel.moveToOffset(functionLiteral.bodyExpression?.textOffset ?: return) } val project = functionLiteral.project PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) CodeStyleManager.getInstance(project).adjustLineIndent(functionLiteral.containingFile, functionLiteral.textRange) } } }
apache-2.0
c55222a6cd743bd30ca1668c635469d8
51.695652
158
0.748185
5.652985
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/vmstat/AbstractVmstatOutputStream.kt
2
620
package com.github.kerubistan.kerub.utils.junix.vmstat import java.io.OutputStream abstract class AbstractVmstatOutputStream : OutputStream() { private val buff: StringBuilder = StringBuilder(128) companion object { private val someSpaces = "\\s+".toRegex() } override fun write(data: Int) { if (data == 10) { val line = buff.toString().trim() buff.clear() if (line.startsWith("procs") || line.startsWith("r")) { return } val split = line.split(someSpaces) handleInput(split) } else { buff.append(data.toChar()) } } protected abstract fun handleInput(split: List<String>) }
apache-2.0
0449dead7dd9c224a32308ac7f432cc0
19.7
60
0.687097
3.369565
false
false
false
false
smmribeiro/intellij-community
java/java-tests/testSrc/com/intellij/projectView/ModulesInProjectViewTest.kt
4
6326
// 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.projectView import com.intellij.ide.highlighter.ModuleFileType import com.intellij.openapi.application.WriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.ui.Queryable import com.intellij.project.stateStore import com.intellij.testFramework.PsiTestUtil import com.intellij.util.io.directoryContent import com.intellij.util.io.generateInVirtualTempDir // directory-based project must be used to ensure that .iws/.ipr file won't break the test (they may be created if workspace model is used) class ModulesInProjectViewTest : BaseProjectViewTestCase() { init { myPrintInfo = Queryable.PrintInfo() } override fun setUp() { super.setUp() myStructure.isShowLibraryContents = false } fun `test unloaded modules`() { val root = directoryContent { dir("loaded") { dir("unloaded-inner") { dir("subdir") { } file("y.txt") } } dir("unloaded") { dir("loaded-inner") { dir("subdir") { } file("z.txt") } } }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("loaded"), root.findChild("loaded")!!) PsiTestUtil.addContentRoot(createModule("unloaded-inner"), root.findFileByRelativePath("loaded/unloaded-inner")!!) PsiTestUtil.addContentRoot(createModule("unloaded"), root.findChild("unloaded")!!) PsiTestUtil.addContentRoot(createModule("loaded-inner"), root.findFileByRelativePath("unloaded/loaded-inner")!!) val expected = """ Project loaded unloaded-inner subdir y.txt unloaded loaded-inner subdir z.txt """.trimIndent() assertStructureEqual(expected) ModuleManager.getInstance(myProject).setUnloadedModules(listOf("unloaded", "unloaded-inner")) assertStructureEqual(""" Project loaded unloaded-inner subdir y.txt unloaded loaded-inner subdir z.txt """.trimIndent()) } fun `test unloaded module with qualified name`() { val root = directoryContent { dir("unloaded") { dir("subdir") {} file("y.txt") } dir("unloaded2") { dir("subdir") {} } }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("foo.bar.unloaded"), root.findChild("unloaded")!!) PsiTestUtil.addContentRoot(createModule("unloaded2"), root.findChild("unloaded2")!!) val expected = """ Project Group: foo.bar unloaded subdir y.txt unloaded2 subdir """.trimIndent() assertStructureEqual(expected) ModuleManager.getInstance(myProject).setUnloadedModules(listOf("unloaded")) assertStructureEqual(expected) } fun `test do not show parent groups for single module`() { val root = directoryContent { dir("module") { dir("subdir") {} } }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("foo.bar.module"), root.findChild("module")!!) assertStructureEqual(""" |Project | module | subdir | """.trimMargin()) } fun `test flatten modules option`() { val root = directoryContent { dir("module1") {} dir("module2") {} }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("foo.bar.module1"), root.findChild("module1")!!) PsiTestUtil.addContentRoot(createModule("foo.bar.module2"), root.findChild("module2")!!) myStructure.isFlattenModules = true assertStructureEqual(""" |Project | module1 | module2 | """.trimMargin()) } fun `test do not show groups duplicating module names`() { val root = directoryContent { dir("foo") {} dir("foo.bar") {} }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("xxx.foo"), root.findChild("foo")!!) PsiTestUtil.addContentRoot(createModule("xxx.foo.bar"), root.findChild("foo.bar")!!) assertStructureEqual(""" |Project | Group: xxx | foo | foo.bar | """.trimMargin()) } fun `test modules with common parent group`() { val root = directoryContent { dir("module1") { dir("subdir") {} } dir("module2") { dir("subdir") {} } }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("foo.bar.module1"), root.findChild("module1")!!) PsiTestUtil.addContentRoot(createModule("foo.baz.module2"), root.findChild("module2")!!) assertStructureEqual(""" |Project | Group: foo | Group: bar | module1 | subdir | Group: baz | module2 | subdir | """.trimMargin()) } fun `test modules in nested groups`() { val root = directoryContent { dir("module1") { dir("subdir") {} } dir("module2") { dir("subdir") {} } }.generateInVirtualTempDir() PsiTestUtil.addContentRoot(createModule("foo.bar.module1"), root.findChild("module1")!!) PsiTestUtil.addContentRoot(createModule("foo.module2"), root.findChild("module2")!!) assertStructureEqual(""" |Project | Group: foo | Group: bar | module1 | subdir | module2 | subdir | """.trimMargin()) } override fun doCreateRealModule(moduleName: String): Module { return WriteAction.computeAndWait<Module, RuntimeException> { /* iml files are created under .idea directory to ensure that they won't affect expected structure of Project View; this is needed to ensure that tests work the same way under the old project model and under workspace model where all modules are saved when a single module is unloaded */ val imlPath = project.stateStore.projectBasePath.resolve(".idea/$moduleName${ModuleFileType.DOT_DEFAULT_EXTENSION}") ModuleManager.getInstance(myProject).newModule(imlPath, moduleType.id) } } override fun getTestPath(): String? = null }
apache-2.0
ca78717903ba18a3b70cd2b91f5c420b
29.863415
140
0.633101
4.724421
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/memberOrder/topLevelCallables.kt
10
128
//ALLOW_AST_ACCESS package test val f1 = { 1 }() fun f2() = 1 val f3 = { 1 }() fun f4() = 1 fun f4(i: Int) = 1 val f5 = { 1 }()
apache-2.0
9739cd77a1786a3e93d7652e1d587fc2
13.333333
18
0.507813
2.169492
false
true
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/formatting/engine/testModelTests/TestModelParserTest.kt
32
3736
/* * 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.formatting.engine.testModelTests import com.intellij.formatting.engine.testModel.TestBlock import com.intellij.formatting.engine.testModel.getRoot import com.intellij.testFramework.assertions.Assertions.assertThat import org.junit.Test class TestModelParserTest { @Test fun `test simple block parsing`() { val children = getBlocks("[a1]block") assertThat(children).hasSize(1) val child = children[0] assertLeaf(child, "a1", "block") } @Test fun `test block with no attributes`() { val children = getBlocks("[]block") assertThat(children).hasSize(1) val child = children[0] assertLeaf(child, "", "block") } @Test fun `test empty block with no attributes`() { val children = getBlocks("[]") assertThat(children).hasSize(1) val child = children[0] assertLeaf(child, "", "") } @Test fun `test multiple blocks`() { val children = getRoot("[a1]foo \n\n\n \n\n\n [a2]goo").children assertThat(children).hasSize(3) assertLeaf(children[0], "a1", "foo") assertSpace(children[1], " \n\n\n \n\n\n ") assertLeaf(children[2], "a2", "goo") } @Test fun `test simple block with space`() { val children = getBlocks("[a1]foo \n ") assertThat(children).hasSize(2) assertLeaf(children[0], "a1", "foo") assertSpace(children[1], " \n ") } @Test fun `test composite block`() { var children = getBlocks("[]([]foo \n \n \n [a3]goo)") assertThat(children).hasSize(1) children = (children[0] as TestBlock.Composite).children assertThat(children).hasSize(3) assertLeaf(children[0], "", "foo") assertSpace(children[1], " \n \n \n ") assertLeaf(children[2], "a3", "goo") } @Test fun `test multiple composite blocks`() { var children = getBlocks("[]([]([]foo \n\n\n []goo) \n\n\n []([]woo))") assertThat(children).hasSize(1) children = (children[0] as TestBlock.Composite).children assertThat(children).hasSize(3) assertThat((children[0] as TestBlock.Composite).children).hasSize(3) assertThat((children[2] as TestBlock.Composite).children).hasSize(1) } @Test fun `test nested composite blocks`() { var children = getBlocks("[a0]([a1]([a2]([a3]([a4]foo))))") for (i in 0..3) { assertThat(children).hasSize(1) val child = children[0] as TestBlock.Composite assertThat(child.attributes).isEqualTo("a$i") children = child.children } val leaf = children[0] as TestBlock.Leaf assertThat(leaf.attributes).isEqualTo("a4") assertThat(leaf.text).isEqualTo("foo") } private fun assertLeaf(testBlock: TestBlock, attrs: String, text: String) { val leaf = testBlock as TestBlock.Leaf assertThat(leaf.text).isEqualTo(text) assertThat(leaf.attributes).isEqualTo(attrs) } private fun assertSpace(testBlock: TestBlock, space: String) { val leaf = testBlock as TestBlock.Space assertThat(leaf.text).isEqualTo(space) } private fun getBlocks(text: String): MutableList<TestBlock> { val root = getRoot(text) val children = root.children return children } }
apache-2.0
065f1b8b2d0e56451442f0b842e5be3a
28.195313
77
0.671842
3.599229
false
true
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/pkg/vault/VaultClient.kt
1
1993
package com.cognifide.gradle.aem.common.pkg.vault import com.cognifide.gradle.aem.AemExtension import com.cognifide.gradle.aem.common.instance.service.pkg.Package import com.cognifide.gradle.aem.common.cli.CliApp import com.cognifide.gradle.common.utils.using import java.io.File import kotlin.system.measureTimeMillis class VaultClient(val aem: AemExtension) { private val cli = CliApp(aem).apply { dependencyNotation.apply { convention("org.apache.jackrabbit.vault:vault-cli:3.4.0:bin") aem.prop.string(("vault.cli.dependency"))?.let { set(it) } } executable.apply { convention("vault-cli-3.4.0/bin/vlt") aem.prop.string("vault.cli.executable")?.let { set(it) } } } fun cli(options: CliApp.() -> Unit) = cli.using(options) val command = aem.obj.string() val commandProperties = aem.obj.map<String, Any> { convention(mapOf("aem" to aem)) } val commandEffective get() = aem.prop.expand(command.get(), commandProperties.get()) val contentDir = aem.obj.dir { convention(aem.packageOptions.contentDir) } val contentRelativePath = aem.obj.string() val contentDirEffective: File get() { var workingDir = contentDir.map { it.asFile.resolve(Package.JCR_ROOT) }.get() if (!contentRelativePath.orNull.isNullOrBlank()) { workingDir = workingDir.resolve(contentRelativePath.get()) } return workingDir } fun run(): VaultSummary { if (commandEffective.isBlank()) { throw VaultException("Vault command cannot be blank.") } aem.logger.lifecycle("Working directory: $contentDirEffective") aem.logger.lifecycle("Executing command: vlt $commandEffective") val elapsed = measureTimeMillis { cli.exec(contentDirEffective, commandEffective) } return VaultSummary(commandEffective, contentDirEffective, elapsed) } }
apache-2.0
1fffc8418ca9b8c74c52fcada6fb9736
32.779661
89
0.660813
4.160752
false
false
false
false
myunusov/maxur-mserv
maxur-mserv-sample/src/test/kotlin/org/maxur/mserv/doc/MicroServiceKotlinClientIT.kt
1
1311
package org.maxur.mserv.doc import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.maxur.mserv.frame.domain.BaseService import org.maxur.mserv.frame.embedded.EmbeddedService import org.maxur.mserv.frame.kotlin.Locator import org.maxur.mserv.frame.runner.Kotlin import org.maxur.mserv.frame.service.properties.Properties class MicroServiceKotlinClientIT { private var service1: BaseService? = null @Test fun main() { // tag::launcher[] Kotlin.runner { name = ":name" // <1> packages += "org.maxur.mserv.sample" // <2> properties += file { format = "hocon" } // <3> services += rest { } // <4> afterStart += this@MicroServiceKotlinClientIT::afterStart // <5> beforeStop += this@MicroServiceKotlinClientIT::beforeStop }.start() // <6> // end::launcher[] service1?.stop() Locator.stop() } fun beforeStop(service: EmbeddedService) { assertThat(service).isNotNull() } fun afterStart(service: BaseService, config: Properties) { service1 = service assertThat(service).isNotNull() assertThat(config).isNotNull() assertThat(config.sources.get(0).format).isEqualToIgnoringCase("Hocon") } }
apache-2.0
13a37d9f30cea17ea1c52901e6a906fb
30.238095
79
0.643783
4.021472
false
true
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WakeOnLanAction.kt
1
2817
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.framework.extensions.logException import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.exceptions.ActionException import ch.rmy.android.http_shortcuts.scripting.ExecutionContext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress import kotlin.time.Duration.Companion.milliseconds class WakeOnLanAction( private val macAddress: String, private val ipAddress: String, private val port: Int, ) : BaseAction() { override suspend fun execute(executionContext: ExecutionContext) { val macAddress = parseMacAddress(macAddress) withContext(Dispatchers.IO) { try { sendMagicPacket( macAddress = macAddress, ipAddress = InetAddress.getByName(ipAddress), port = port, ) } catch (e: CancellationException) { throw e } catch (e: Exception) { logException(e) throw ActionException { getString(R.string.error_action_type_send_wol_failed, e.message) } } } } companion object { private const val FF: Byte = 0xff.toByte() private const val RESEND_PACKET_COUNT = 3 private val RESEND_DELAY = 350.milliseconds private suspend fun sendMagicPacket(macAddress: List<Byte>, ipAddress: InetAddress, port: Int) { val data = mutableListOf(FF, FF, FF, FF, FF, FF) for (i in 0 until 16) { data.addAll(macAddress) } val bytes = data.toByteArray() val packet = DatagramPacket(bytes, bytes.size, ipAddress, port) DatagramSocket() .use { socket -> for (i in 0 until RESEND_PACKET_COUNT) { if (i != 0) { delay(RESEND_DELAY) } socket.send(packet) } } } private fun parseMacAddress(macAddress: String): List<Byte> = macAddress.split(':', '-') .mapNotNull { it .takeIf { it.length <= 2 } ?.toIntOrNull(16) ?.toByte() } .takeIf { it.size == 6 } ?: throw ActionException { getString(R.string.error_action_type_send_wol_invalid_mac_address, macAddress) } } }
mit
b4c5e411576caaf7357d6649b67005e2
34.2125
104
0.55733
4.994681
false
false
false
false
7449/Album
core/src/main/java/com/gallery/core/delegate/impl/PrevDelegateImpl.kt
1
8840
package com.gallery.core.delegate.impl import android.os.Bundle import android.provider.MediaStore import android.view.View import androidx.fragment.app.Fragment import androidx.viewpager2.widget.ViewPager2 import com.gallery.core.GalleryBundle import com.gallery.core.R import com.gallery.core.callback.IGalleryImageLoader import com.gallery.core.callback.IGalleryPrevCallback import com.gallery.core.delegate.IPrevDelegate import com.gallery.core.delegate.adapter.PrevAdapter import com.gallery.core.delegate.args.PrevArgs import com.gallery.core.delegate.args.PrevArgs.Companion.configOrDefault import com.gallery.core.delegate.args.PrevArgs.Companion.prevArgs import com.gallery.core.delegate.args.PrevArgs.Companion.prevArgsOrDefault import com.gallery.core.delegate.args.PrevArgs.Companion.putPrevArgs import com.gallery.core.delegate.args.ScanArgs import com.gallery.core.delegate.args.ScanArgs.Companion.putScanArgs import com.gallery.core.entity.ScanEntity import com.gallery.core.extensions.isFileExistsExpand import com.gallery.core.extensions.orEmptyExpand import com.gallery.core.extensions.toScanEntity import com.gallery.scan.Types.Scan.ALL import com.gallery.scan.Types.Scan.NONE import com.gallery.scan.args.ScanEntityFactory import com.gallery.scan.extensions.isScanNoNeExpand import com.gallery.scan.extensions.multipleScanExpand import com.gallery.scan.extensions.scanCore import com.gallery.scan.impl.ScanImpl import com.gallery.scan.impl.file.FileScanArgs import com.gallery.scan.impl.file.FileScanEntity import com.gallery.scan.impl.file.file /** * 预览代理 * 需要在[Fragment]的[Fragment.onViewCreated]之后初始化 */ class PrevDelegateImpl( /** * [Fragment] * 承载容器 * 使用容器获取需要的[ViewPager2] * [Fragment]中必须存在 [R.id.gallery_prev_viewpager2]和[R.id.gallery_prev_checkbox] 两个id的View */ private val fragment: Fragment, /** * [IGalleryPrevCallback] * 预览回调 */ private val galleryPrevCallback: IGalleryPrevCallback, /** * [IGalleryImageLoader] * 图片加载框架 */ private val galleryImageLoader: IGalleryImageLoader, ) : IPrevDelegate { private val pageChangeCallback: ViewPager2.OnPageChangeCallback = object : ViewPager2.OnPageChangeCallback() { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { galleryPrevCallback.onPageScrolled(position, positionOffset, positionOffsetPixels) } override fun onPageScrollStateChanged(state: Int) { galleryPrevCallback.onPageScrollStateChanged(state) } override fun onPageSelected(position: Int) { galleryPrevCallback.onPageSelected(position) checkBox.isSelected = isSelected(position) } } private val viewPager2: ViewPager2 = rootView.findViewById(R.id.gallery_prev_viewpager2) as ViewPager2 private val checkBox: View = rootView.findViewById(R.id.gallery_prev_checkbox) as View private val prevAdapter: PrevAdapter = PrevAdapter { entity, container -> galleryImageLoader.onDisplayGalleryPrev( entity, container ) } private val prevArgs: PrevArgs = fragment.arguments.orEmptyExpand().prevArgsOrDefault private val galleryBundle: GalleryBundle = prevArgs.configOrDefault override val rootView: View get() = fragment.requireView() override val allItem: ArrayList<ScanEntity> get() = prevAdapter.allItem override val selectItem: ArrayList<ScanEntity> get() = prevAdapter.currentSelectList override val currentPosition: Int get() = viewPager2.currentItem /** 保存当前position和选中的文件数据 */ override fun onSaveInstanceState(outState: Bundle) { PrevArgs.newSaveInstance(currentPosition, selectItem).putPrevArgs(outState) } /** * 如果parentId是[NONE]的话,就是不扫描,直接把传入的 selectList * 作为全部数据展示 * 否则从数据库获取数据,从数据库获取数据时会判断 scanAlone 是否是 [MediaStore.Files.FileColumns.MEDIA_TYPE_NONE] * 如果是,则使用 [GalleryBundle.scanType]作为参数,否则使用 scanAlone * 如果预览页想扫描专门的类型,则使用 scanAlone,这个时候传入[ALL]即可 */ override fun onCreate(savedInstanceState: Bundle?) { //https://github.com/7449/Album/issues/4 //新增对单独扫描的支持,获取scanAlone和parentId val singleType = prevArgs.scanSingleType val parentId: Long = prevArgs.parentId if (parentId.isScanNoNeExpand) { updateEntity(savedInstanceState, prevArgs.selectList) } else { //https://issuetracker.google.com/issues/127692541 //这个问题已经在ViewPager2上修复 val scanFileArgs = FileScanArgs( if (singleType == MediaStore.Files.FileColumns.MEDIA_TYPE_NONE) galleryBundle.scanType.map { it.toString() }.toTypedArray() else arrayOf(singleType.toString()), galleryBundle.sort.second, galleryBundle.sort.first ) ScanImpl<FileScanEntity>( fragment.scanCore( factory = ScanEntityFactory.file(), args = scanFileArgs ) ) { updateEntity(savedInstanceState, multipleValue.toScanEntity()) }.scanMultiple(parentId.multipleScanExpand()) } } override fun updateEntity(savedInstanceState: Bundle?, arrayList: ArrayList<ScanEntity>) { val prevArgs: PrevArgs = savedInstanceState?.prevArgs ?: prevArgs prevAdapter.addAll(arrayList) prevAdapter.addSelectAll(prevArgs.selectList) prevAdapter.updateEntity() viewPager2.adapter = prevAdapter viewPager2.registerOnPageChangeCallback(pageChangeCallback) setCurrentItem(prevArgs.position) checkBox.setBackgroundResource(galleryBundle.checkBoxDrawable) checkBox.setOnClickListener { itemViewClick(checkBox) } checkBox.isSelected = isSelected(currentPosition) galleryPrevCallback.onPrevCreated(this, galleryBundle, savedInstanceState) } override fun itemViewClick(box: View) { if (!currentItem.uri.isFileExistsExpand(fragment.requireActivity())) { if (prevAdapter.containsSelect(currentItem)) { prevAdapter.removeSelectEntity(currentItem) } box.isSelected = false currentItem.isSelected = false galleryPrevCallback.onClickItemFileNotExist( fragment.requireActivity(), galleryBundle, currentItem ) return } if (!prevAdapter.containsSelect(currentItem) && selectItem.size >= galleryBundle.multipleMaxCount) { galleryPrevCallback.onClickItemBoxMaxCount( fragment.requireActivity(), galleryBundle, currentItem ) return } if (currentItem.isSelected) { prevAdapter.removeSelectEntity(currentItem) currentItem.isSelected = false box.isSelected = false } else { prevAdapter.addSelectEntity(currentItem) currentItem.isSelected = true box.isSelected = true } galleryPrevCallback.onChangedCheckBox() } override fun isSelected(position: Int): Boolean { return prevAdapter.isCheck(position) } override fun setCurrentItem(position: Int, smoothScroll: Boolean) { viewPager2.setCurrentItem(position, smoothScroll) } override fun notifyItemChanged(position: Int) { prevAdapter.notifyItemChanged(position) } override fun notifyDataSetChanged() { prevAdapter.notifyDataSetChanged() } override fun resultBundle(isRefresh: Boolean): Bundle { return ScanArgs.newResultInstance(selectItem, isRefresh).putScanArgs() } override fun onDestroy() { viewPager2.unregisterOnPageChangeCallback(pageChangeCallback) } }
mpl-2.0
fa9740f74a4dc5996844dbd8dff1a2af
38.246445
108
0.651826
4.735081
false
false
false
false
parkee/messenger-send-api-client
src/main/kotlin/com/github/parkee/messenger/model/response/ResponseMessage.kt
1
681
package com.github.parkee.messenger.model.response import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.parkee.messenger.model.request.quickreply.QuickReply @JsonIgnoreProperties(ignoreUnknown = true) data class ResponseMessage( @JsonProperty("mid") val mid: String, @JsonProperty("seq") val seq: Int, @JsonProperty("sticker_id") val stickerId: Long? = null, @JsonProperty("attachments") val attachments: List<ResponseAttachment>? = null, @JsonProperty("text") val text: String? = null, @JsonProperty("quick_reply") val quickReply: QuickReply? = null )
mit
e4a1a376a4101380557ba673e88b4878
44.466667
87
0.743025
4.310127
false
false
false
false
softappeal/yass
kotlin/yass/test/ch/softappeal/yass/serialize/PrimitiveTypes.kt
1
670
package ch.softappeal.yass.serialize import ch.softappeal.yass.* import java.io.* @Tag(40) open class PrimitiveTypes : Serializable { @Tag(28) var booleanField: Boolean = false @Tag(2) var shortField: Short = 0 @Tag(3) var intField: Int = 0 @Tag(4) var longField: Long = 0 @Tag(11) var byteArrayField: ByteArray? = null @Tag(20) var booleanWrapperField: Boolean? = null @Tag(22) var shortWrapperField: Short? = null @Tag(23) var intWrapperField: Int? = null @Tag(24) var longWrapperField: Long? = null constructor(intField: Int) { this.intField = intField } constructor() }
bsd-3-clause
cace558aeb5ae09a9e7ec15aa65d6e0f
19.9375
44
0.631343
3.489583
false
false
false
false
blademainer/intellij-community
platform/built-in-server/testSrc/RestApiTest.kt
4
3555
package org.jetbrains.ide import com.google.gson.stream.JsonWriter import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.RuleChain import com.intellij.testFramework.TemporaryDirectory import io.netty.handler.codec.http.HttpResponseStatus import org.assertj.core.api.Assertions.assertThat import org.jetbrains.ide.TestManager.TestDescriptor import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.BufferedOutputStream import java.io.OutputStreamWriter import java.net.HttpURLConnection import java.net.URL class RestApiTest { companion object { @ClassRule val projectRule = ProjectRule() } private val tempDirManager = TemporaryDirectory() private val manager = TestManager(projectRule, tempDirManager) private val ruleChain = RuleChain(tempDirManager, manager) @Rule fun getChain() = ruleChain @Test(timeout = 60000) @TestDescriptor(filePath = "", status = 400) fun fileEmptyRequest() { doTest() } @Test(timeout = 60000) @TestDescriptor(filePath = "foo.txt", relativeToProject = true, status = 200) fun relativeToProject() { doTest() } @Test(timeout = 60000) @TestDescriptor(filePath = "foo.txt", relativeToProject = true, line = 1, status = 200) fun relativeToProjectWithLine() { doTest() } @Test(timeout = 60000) @TestDescriptor(filePath = "foo.txt", relativeToProject = true, line = 1, column = 13, status = 200) fun relativeToProjectWithLineAndColumn() { doTest() } @TestDescriptor(filePath = "fileInExcludedDir.txt", excluded = true, status = 200) @Test(timeout = 60000) fun inExcludedDir() { doTest() } @Test(timeout = 60000) @TestDescriptor(filePath = "bar/42/foo.txt", doNotCreate = true, status = 404) fun relativeNonExistent() { doTest() } @Test(timeout = 60000) @TestDescriptor(filePath = "_tmp_", doNotCreate = true, status = 404) fun absoluteNonExistent() { doTest() } @Test(timeout = 60000) @TestDescriptor(filePath = "_tmp_", status = 200) fun absolute() { doTest() } private fun doTest() { val serviceUrl = "http://localhost:${BuiltInServerManager.getInstance().port}/api/file" var url = serviceUrl + (if (manager.filePath == null) "" else ("/${manager.filePath}")) val line = manager.annotation?.line ?: -1 if (line != -1) { url += ":$line" } val column = manager.annotation?.column ?: -1 if (column != -1) { url += ":$column" } var connection = URL(url).openConnection() as HttpURLConnection val expectedStatus = HttpResponseStatus.valueOf(manager.annotation?.status ?: 200) assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus) connection = URL("$serviceUrl?file=${manager.filePath ?: ""}&line=$line&column=$column").openConnection() as HttpURLConnection assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus) connection = URL("$serviceUrl").openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.doOutput = true val writer = JsonWriter(OutputStreamWriter(BufferedOutputStream(connection.outputStream), CharsetToolkit.UTF8_CHARSET)) writer.beginObject() writer.name("file").value(manager.filePath) writer.name("line").value(line) writer.name("column").value(column) writer.endObject() writer.close() assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus) } }
apache-2.0
a40355cf4de79ef7a30dc3bf4e0882e0
31.614679
130
0.721238
4.345966
false
true
false
false
AVnetWS/Hentoid
app/src/main/java/me/devsaki/hentoid/viewholders/SubExpandableItem.kt
1
6675
package me.devsaki.hentoid.viewholders import android.graphics.Color import android.view.MotionEvent import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.annotation.StringRes import androidx.core.view.ViewCompat import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.* import com.mikepenz.fastadapter.drag.IExtendedDraggable import com.mikepenz.fastadapter.expandable.items.AbstractExpandableItem import com.mikepenz.fastadapter.listeners.TouchEventHook import com.mikepenz.fastadapter.ui.utils.FastAdapterUIUtils import com.mikepenz.fastadapter.ui.utils.StringHolder import me.devsaki.hentoid.R /** * Inspired by mikepenz */ open class SubExpandableItem(private val mTouchHelper: ItemTouchHelper) : AbstractExpandableItem<SubExpandableItem.ViewHolder>(), IClickable<SubExpandableItem>, ISubItem<SubExpandableItem.ViewHolder>, IExtendedDraggable<SubExpandableItem.ViewHolder>, INestedItem<SubExpandableItem.ViewHolder> { var header: String? = null var name: StringHolder? = null var description: StringHolder? = null private var draggable: Boolean = false private var mOnClickListener: ClickListener<SubExpandableItem>? = null //we define a clickListener in here so we can directly animate /** * we overwrite the item specific click listener so we can automatically animate within the item * * @return */ @Suppress("SetterBackingFieldAssignment") override var onItemClickListener: ClickListener<SubExpandableItem>? = { v: View?, adapter: IAdapter<SubExpandableItem>, item: SubExpandableItem, position: Int -> if (item.subItems.isNotEmpty()) { v?.findViewById<View>(R.id.material_drawer_icon)?.let { if (!item.isExpanded) { ViewCompat.animate(it).rotation(180f).start() } else { ViewCompat.animate(it).rotation(0f).start() } } } mOnClickListener?.invoke(v, adapter, item, position) ?: true } set(onClickListener) { this.mOnClickListener = onClickListener // on purpose } override var onPreItemClickListener: ClickListener<SubExpandableItem>? get() = null set(_) {} //this might not be true for your application override var isSelectable: Boolean get() = subItems.isEmpty() set(value) { super.isSelectable = value } /** * defines the type defining this item. must be unique. preferably an id * * @return the type */ override val type: Int get() = R.id.expandable_item; /** * defines the layout which will be used for this item in the list * * @return the layout for this item */ override val layoutRes: Int get() = R.layout.item_expandable fun withHeader(header: String): SubExpandableItem { this.header = header return this } fun withName(Name: String): SubExpandableItem { this.name = StringHolder(Name) return this } fun withName(@StringRes NameRes: Int): SubExpandableItem { this.name = StringHolder(NameRes) return this } fun withDescription(description: String): SubExpandableItem { this.description = StringHolder(description) return this } fun withDescription(@StringRes descriptionRes: Int): SubExpandableItem { this.description = StringHolder(descriptionRes) return this } fun withDraggable(value: Boolean): SubExpandableItem { this.draggable = value return this } /** * binds the data of this item onto the viewHolder * * @param holder the viewHolder of this item */ override fun bindView(holder: ViewHolder, payloads: List<Any>) { super.bindView(holder, payloads) //get the context val ctx = holder.itemView.context //set the background for the item holder.view.clearAnimation() ViewCompat.setBackground( holder.view, FastAdapterUIUtils.getSelectableBackground(ctx, Color.RED, true) ) //set the text for the name StringHolder.applyTo(name, holder.name) //set the text for the description or hide StringHolder.applyToOrHide(description, holder.description) holder.dragHandle.visibility = if (draggable) View.VISIBLE else View.GONE if (subItems.isEmpty()) { holder.icon.visibility = View.GONE } else { holder.icon.visibility = View.VISIBLE } if (isExpanded) { holder.icon.rotation = 0f } else { holder.icon.rotation = 180f } } override fun unbindView(holder: ViewHolder) { super.unbindView(holder) holder.name.text = null holder.description.text = null //make sure all animations are stopped holder.icon.clearAnimation() } override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } /** * our ViewHolder */ class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) { var name: TextView = view.findViewById(R.id.material_drawer_name) var description: TextView = view.findViewById(R.id.material_drawer_description) var icon: ImageView = view.findViewById(R.id.material_drawer_icon) var dragHandle: ImageView = view.findViewById(R.id.ivReorder) } override val isDraggable: Boolean get() = draggable override val touchHelper: ItemTouchHelper? get() = mTouchHelper override fun getDragView(viewHolder: ViewHolder): View? { return viewHolder.dragHandle } class DragHandlerTouchEvent(val action: (position: Int) -> Unit) : TouchEventHook<SubExpandableItem>() { override fun onBind(viewHolder: RecyclerView.ViewHolder): View? { return if (viewHolder is ViewHolder) viewHolder.dragHandle else null } override fun onTouch( v: View, event: MotionEvent, position: Int, fastAdapter: FastAdapter<SubExpandableItem>, item: SubExpandableItem ): Boolean { return if (event.action == MotionEvent.ACTION_DOWN) { action(position) true } else { false } } } override fun getLevel(): Int { return 0 } }
apache-2.0
17c93369829caf1990c03604dc54daa3
30.635071
100
0.644045
4.764454
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/SingleDomainMap.kt
1
1182
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.adblock.filter.unified class SingleDomainMap(override val include: Boolean, private val domain: String) : DomainMap { override val size: Int get() = 1 override fun get(domain: String): Boolean? { return if (this.domain == domain) include else null } override fun getKey(index: Int): String { if (index != 0) throw IndexOutOfBoundsException() return domain } override fun getValue(index: Int): Boolean { if (index != 0) throw IndexOutOfBoundsException() return include } }
apache-2.0
26017b98c33ead778a9238ce492817d3
31.833333
94
0.695431
4.313869
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-graphql/src/test/kotlin/org/evomaster/e2etests/spring/graphql/errors/OnlyErrorsEMTest.kt
1
1915
package org.evomaster.e2etests.spring.graphql.errors import com.foo.graphql.onlyerrors.OnlyErrorsController import org.evomaster.core.EMConfig import org.evomaster.e2etests.spring.graphql.SpringTestBase import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import java.io.File class OnlyErrorsEMTest : SpringTestBase() { companion object { @BeforeAll @JvmStatic fun init() { initClass(OnlyErrorsController()) } } @Test fun testRunEM() { runTestHandlingFlakyAndCompilation( "GQL_OnlyErrorsEM", "org.foo.graphql.OnlyErrorsEM", 100 ) { args: MutableList<String> -> args.add("--problemType") args.add(EMConfig.ProblemType.GRAPHQL.toString()) args.add("--exportCoveredTarget") args.add("true") val targetFile = "target/covered-targets/onlyerrors.txt" args.add("--coveredTargetFile") args.add(targetFile) val statFile = "target/statistics/onlyerrors_statistics.csv" args.add("--writeStatistics") args.add("true") args.add("--statisticsFile") args.add(statFile) val solution = initAndRun(args) assertTrue(solution.individuals.size >= 1) assertAnyWithErrors(solution) existErrorAndSuccessTarget(targetFile) ErrorsInStatisticsUtil.checkErrorsInStatistics(statFile, 1, 1, 1, 0, 1) } } private fun existErrorAndSuccessTarget(path : String){ val file = File(path) assertTrue(file.exists()) val targets = file.readText() assertTrue(targets.contains("GQL_ERRORS_ACTION:") && targets.contains("GQL_ERRORS_LINE"), targets) } }
lgpl-3.0
8ea6a82e1ad11536a036aed242a10394
28.9375
106
0.638642
4.342404
false
true
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/trips/detail/StopAdapter.kt
1
2003
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import androidx.annotation.ColorInt import androidx.recyclerview.widget.RecyclerView.Adapter import android.view.LayoutInflater import android.view.ViewGroup import de.grobox.transportr.R import de.grobox.transportr.trips.detail.LegViewHolder.Companion.DEFAULT_LINE_COLOR import de.schildbach.pte.dto.Stop internal class StopAdapter internal constructor(private val listener: LegClickListener) : Adapter<StopViewHolder>() { private var stops: List<Stop>? = null @ColorInt private var color: Int = DEFAULT_LINE_COLOR internal fun changeDate(stops: List<Stop>, @ColorInt color: Int) { this.stops = stops this.color = color notifyDataSetChanged() } override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): StopViewHolder { val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.list_item_stop, viewGroup, false) return StopViewHolder(v, listener) } override fun onBindViewHolder(ui: StopViewHolder, i: Int) { stops?.let { val stop = it[i] ui.bind(stop, color) } ?: throw IllegalStateException() } override fun getItemCount(): Int { return stops?.size ?: 0 } }
gpl-3.0
ee22412052817da5bec9be4b6dbc439b
34.140351
117
0.705442
4.234672
false
false
false
false
tmarsteel/kotlin-prolog
core/src/main/kotlin/com/github/prologdb/runtime/util/OperatorRegistry.kt
1
4016
package com.github.prologdb.runtime.util /** * Holds operators defined in a knowledge base. This might seem like a concern of the parser since, at the core level, * it does not make a difference whether `+(1,2)` was parsed from `1 + 2` or from `+(1,2)`. But operator definitions * are at the very heart of the language (e.g. =/2). It would be possible to define the core without the syntax sugar * but that would make it a real chore to go from core + parser to a working, compliant REPL. The core concerns itself * with operator definitions because it makes the library easier to use. */ interface OperatorRegistry { /** * Returns all definitions for operators with the given name */ fun getOperatorDefinitionsFor(name: String): Set<OperatorDefinition> /** * Is supposed to be used to display listings and merge multiple operator registries. * Should be computed on demand only. */ val allOperators: Iterable<OperatorDefinition> } interface OperatorRegistrationTarget { /** * (Re-)defines the given operator (overriding existing definitions for * the same [OperatorDefinition.name] if present). */ fun defineOperator(definition: OperatorDefinition) fun include(other: OperatorRegistry) { other.allOperators.forEach(this::defineOperator) } } interface MutableOperatorRegistry : OperatorRegistry, OperatorRegistrationTarget /** * Defines an operator to use in a prolog program. */ data class OperatorDefinition ( /** * The precedence, between 0 and 1200. */ val precedence: Short, /** * The type of this operator ; defines how it relates towards its surroundings */ val type: OperatorType, /** * The functor of the operator */ val name: String ) { init { assert(precedence >= 0) assert(precedence <= 1200) assert(name.isNotEmpty()) assert(name.none { it.isWhitespace() }) } override fun toString() = "op($precedence, ${type.name.lowercase()}, $name)" } enum class OperatorType { FX, FY, XFX, XFY, YFX, XF, YF; val isPrefix by lazy { this == FX || this == FY } val isInfix by lazy { this == XFX || this == XFY || this == YFX } val isPostfix by lazy { this == XF || this == YF } val arity: Int by lazy { if (isPrefix || isPostfix) 1 else 2 } /** * Whether the argument positioning around the operator type * is the same as with the given. */ fun isSameArgumentRelationAs(other: OperatorType): Boolean { return when { other === this -> true this.arity != other.arity -> false this.isPrefix && other.isPrefix -> true this.isPostfix && other.isPostfix -> true this.isInfix && other.isInfix -> true else -> false } } } /** * A simple implementation of [MutableOperatorRegistry]. */ class DefaultOperatorRegistry : MutableOperatorRegistry { private val operators: OperatorMap = mutableMapOf() constructor(definitions: Set<OperatorDefinition> = emptySet()) { definitions.forEach(this::defineOperator) } override fun getOperatorDefinitionsFor(name: String): Set<OperatorDefinition> = operators[name] ?: emptySet() override fun defineOperator(definition: OperatorDefinition) { val targetSet = operators.computeIfAbsent(definition.name, { HashSet() }) // remove overridden definitions targetSet.removeIf { it.type.isSameArgumentRelationAs(definition.type) } targetSet.add(definition) } override val allOperators: Iterable<OperatorDefinition> get() = operators.values.flatten() } private typealias OperatorMap = MutableMap<String, MutableSet<OperatorDefinition>> object EmptyOperatorRegistry : OperatorRegistry { override val allOperators: Set<OperatorDefinition> = emptySet() override fun getOperatorDefinitionsFor(name: String): Set<OperatorDefinition> = allOperators }
mit
5fc4fa7d10101a4e45a17fe0eb99c034
30.382813
118
0.671564
4.422907
false
false
false
false
zlsun/kotlin-koans
src/ii_collections/_22_Fold_.kt
1
601
package ii_collections fun example9() { val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult }) result == 24 } // The same as fun whatFoldDoes(): Int { var result = 1 listOf(1, 2, 3, 4).forEach { element -> result = element * result} return result } fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> { // Return the set of products ordered by every customer return customers.fold(allOrderedProducts, { orderedByAll, customer -> orderedByAll.filter { customer.orderedProducts.contains(it) }.toSet() }) }
mit
110772192e559d734068325861644e91
27.619048
92
0.667221
3.928105
false
false
false
false
shymmq/librus-client-kotlin
app/src/main/kotlin/com/wabadaba/dziennik/ui/events/EventItem.kt
1
2582
package com.wabadaba.dziennik.ui.events import android.view.View import android.widget.TextView import com.wabadaba.dziennik.R import com.wabadaba.dziennik.ui.HeaderItem import com.wabadaba.dziennik.vo.Event import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractSectionableItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import kotlinx.android.synthetic.main.item_event.view.* import org.joda.time.LocalDate class EventItem(val event: Event, header: HeaderItem) : AbstractSectionableItem<EventItem.ViewHolder, HeaderItem>(header), Comparable<EventItem> { override fun getLayoutRes() = R.layout.item_event override fun createViewHolder(view: View, adapter: FlexibleAdapter<out IFlexible<*>>) = ViewHolder(view, adapter) override fun bindViewHolder(adapter: FlexibleAdapter<out IFlexible<*>>?, holder: ViewHolder, position: Int, payloads: MutableList<Any?>?) { val date = event.date!! holder.itemView.apply { item_event_title.text = event.category?.name item_event_subtitle.text = when (date) { LocalDate.now(), LocalDate.now().plusDays(1) -> { if (event.lessonNumber != null) "lekcja ${event.lessonNumber}" else "" } else -> { val dateFormat = context.getString(R.string.date_format_full) date.toString(dateFormat) } } } } class ViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) override fun compareTo(other: EventItem): Int { if (event.date != null && other.event.date != null) { val compare1 = event.date!!.compareTo(other.event.date!!) if (compare1 == 0) { if (event.lessonNumber != null && other.event.lessonNumber != null) { return event.lessonNumber!!.compareTo(other.event.lessonNumber!!) } } else return compare1 } return 0 } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as EventItem if (event != other.event) return false return true } override fun hashCode(): Int { return event.hashCode() } }
gpl-3.0
e9376747d34de2611fa82b7b0fea7e65
35.9
146
0.606119
4.817164
false
false
false
false
google-developer-training/basic-android-kotlin-compose-training-race-tracker
app/src/main/java/com/example/racetracker/ui/RaceTrackerApp.kt
1
7403
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.racetracker.ui import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.racetracker.R import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @Composable fun RaceTrackerApp() { /** * Note: To survive the configuration changes such as screen rotation, [rememberSaveable] should * be used with custom Saver object. But to keep the example simple, and keep focus on * Coroutines that implementation detail is stripped out. */ val playerOne = remember { RaceParticipant(name = "Player 1", progressIncrement = 1) } val playerTwo = remember { RaceParticipant(name = "Player 2", progressIncrement = 2) } var raceInProgress by remember { mutableStateOf(false) } if (raceInProgress) { LaunchedEffect(playerOne, playerTwo) { coroutineScope { launch { playerOne.run() } launch { playerTwo.run() } } raceInProgress = false } } RaceTrackerScreen( playerOne = playerOne, playerTwo = playerTwo, isRunning = raceInProgress, onRunStateChange = { raceInProgress = it } ) } @Composable private fun RaceTrackerScreen( playerOne: RaceParticipant, playerTwo: RaceParticipant, isRunning: Boolean, onRunStateChange: (Boolean) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier .fillMaxSize() .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.run_a_race), style = MaterialTheme.typography.h3, modifier = Modifier.padding(bottom = 24.dp) ) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Image( painter = painterResource(R.drawable.ic_walk), contentDescription = null, modifier = Modifier.padding(bottom = 16.dp), contentScale = ContentScale.Crop ) StatusIndicator( participantName = playerOne.name, currentProgress = playerOne.currentProgress, maxProgress = stringResource( R.string.progress_percentage, playerOne.maxProgress ), progressFactor = playerOne.progressFactor ) Spacer(modifier = Modifier.size(24.dp)) StatusIndicator( participantName = playerTwo.name, currentProgress = playerTwo.currentProgress, maxProgress = stringResource( R.string.progress_percentage, playerTwo.maxProgress ), progressFactor = playerTwo.progressFactor ) RaceControls( isRunning = isRunning, onRunStateChange = onRunStateChange, onReset = { playerOne.reset() playerTwo.reset() onRunStateChange(false) } ) } } } @Composable private fun StatusIndicator( participantName: String, currentProgress: Int, maxProgress: String, progressFactor: Float, modifier: Modifier = Modifier ) { Row { Text(participantName, Modifier.padding(end = 8.dp)) Column( modifier = modifier .fillMaxWidth() .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp) ) { LinearProgressIndicator( progress = progressFactor, modifier = Modifier .fillMaxWidth() .height(16.dp) .clip(RoundedCornerShape(4.dp)) ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(R.string.progress_percentage, currentProgress), textAlign = TextAlign.Start, modifier = Modifier.weight(1f) ) Text( text = maxProgress, textAlign = TextAlign.End, modifier = Modifier.weight(1f) ) } } } } @Composable private fun RaceControls( onRunStateChange: (Boolean) -> Unit, onReset: () -> Unit, modifier: Modifier = Modifier, isRunning: Boolean = true, ) { Row( modifier = modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { Button(onClick = { onRunStateChange(!isRunning) }) { Text(if (isRunning) stringResource(R.string.pause) else stringResource(R.string.start)) } Button(onClick = onReset) { Text(stringResource(R.string.reset)) } } } @Preview @Composable fun RaceTrackerAppPreview() { MaterialTheme { RaceTrackerApp() } }
apache-2.0
85b518b925b341ec4aaa3bd40ed88900
32.65
100
0.637579
5.063611
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/listener/EntityDamageListener.kt
1
1860
/* * Copyright 2020 Ren Binden * * 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.rpkit.unconsciousness.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.unconsciousness.bukkit.unconsciousness.RPKUnconsciousnessService import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.entity.EntityDamageEvent class EntityDamageListener : Listener { @EventHandler fun onEntityDamage(event: EntityDamageEvent) { val bukkitPlayer = event.entity if (bukkitPlayer !is Player) return val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val unconsciousnessService = Services[RPKUnconsciousnessService::class.java] ?: return val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) ?: return val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return if (!unconsciousnessService.getPreloadedUnconsciousness(character)) return event.isCancelled = true } }
apache-2.0
429127f5de6d526c528b4530c2dd2df3
41.295455
107
0.776882
4.525547
false
false
false
false
kittinunf/ReactiveAndroid
reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/CalendarViewEvent.kt
1
896
package com.github.kittinunf.reactiveandroid.widget import android.widget.CalendarView import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription import io.reactivex.Observable //================================================================================ // Events //================================================================================ data class DateChangeListener(val view: CalendarView, val year: Int, val month: Int, val dayOfMonth: Int) fun CalendarView.rx_dateChange(): Observable<DateChangeListener> { return Observable.create { subscriber -> setOnDateChangeListener { view, year, month, dayOfMonth -> subscriber.onNext(DateChangeListener(view, year, month, dayOfMonth)) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnDateChangeListener(null) }) } }
mit
ccf8762226e899bf626b85575396f26b
37.956522
105
0.604911
5.933775
false
false
false
false
Geobert/Efficio
app/src/androidTest/kotlin/fr/geobert/efficio/EfficioWidgetTest.kt
1
6896
package fr.geobert.efficio import android.content.Intent import android.graphics.Point import android.support.test.InstrumentationRegistry import android.support.test.espresso.Espresso import android.support.test.espresso.action.ViewActions import android.support.test.espresso.matcher.ViewMatchers import android.support.test.filters.LargeTest import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.support.test.uiautomator.By import android.support.test.uiautomator.UiDevice import android.support.test.uiautomator.Until import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlin.properties.Delegates /** * Test the widget behavior, */ @RunWith(AndroidJUnit4::class) @LargeTest class EfficioWidgetTest { private var mDevice: UiDevice by Delegates.notNull() @Rule @JvmField var activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java) private val EFFICIO_PACKAGE = "fr.geobert.efficio" private val LAUNCH_TIMEOUT: Long = 5000 val screenSize: Point by lazy { Point(mDevice.displayWidth, mDevice.displayHeight) } val screenCenter: Point by lazy { Point(screenSize.x / 2, screenSize.y / 2) } fun backToHome() { // back to home mDevice.pressHome() val launcherPackage = mDevice.launcherPackageName!! mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT) pauseTest(800) } fun deleteWidgetOnHome() { backToHome() val widget = Point(screenCenter.x - 100, screenCenter.y) mDevice.swipe(arrayOf(widget, widget, Point(screenCenter.x, 200)), 100) } fun scrollWidgetListToTop() { var w = mDevice.findObject(By.text("Nova Launcher")) while (w == null) { mDevice.swipe(screenCenter.x, 80, screenCenter.x, screenCenter.y, 20) w = mDevice.findObject(By.text("Nova Launcher")) } } val STEPS = 80 fun setWidgetOnHome() { backToHome() // long press on home to bring up widgets menu entry mDevice.swipe(arrayOf(screenCenter, screenCenter), 150) pauseTest(1500) // look for widgets button, with different case val tab = mDevice.findObject(By.text("Widgets")) if (tab != null) tab.click() else mDevice.findObject(By.text("WIDGETS")).click() mDevice.waitForIdle() // look for efficio's widget in a vertical list var widget = mDevice.findObject(By.text("Efficio")) var additionalSwipe = 0 var retry = 10 scrollWidgetListToTop() while ((widget == null || additionalSwipe > 0) && retry > 0) { mDevice.swipe(screenCenter.x, screenSize.y - 100, screenCenter.x, 0, STEPS) mDevice.waitForIdle() if (widget == null) { widget = mDevice.findObject(By.text("Efficio")) retry-- } else { additionalSwipe-- } } if (widget == null) { // nothing found, swipe the other way retry = 10 while ((widget == null || additionalSwipe > 0) && retry > 0) { mDevice.swipe(screenCenter.x, 80, screenCenter.x, screenCenter.y, STEPS) mDevice.waitForIdle() if (widget == null) { widget = mDevice.findObject(By.text("Efficio")) retry-- } else { additionalSwipe-- } } } var b = widget.visibleBounds if (b.centerY() > (screenSize.y - 150)) mDevice.swipe(screenCenter.x, screenCenter.y, screenCenter.x, 0, STEPS) if (b.centerY() < 50) mDevice.swipe(screenCenter.x, 80, screenCenter.x, 200, STEPS) b = widget.visibleBounds // long press on the widget's pic val c = Point(b.left + 100, b.bottom + 50) // click on the widget image mDevice.swipe(arrayOf(c, c, screenCenter), 150) // keep default list and click ok mDevice.findObject(By.desc("OK")).click() // only test the presence of the widget, not the list Assert.assertNotNull(mDevice.findObject(By.text("Store"))) } fun launchApp() { val ctx = InstrumentationRegistry.getInstrumentation().context val intent = ctx.packageManager.getLaunchIntentForPackage(EFFICIO_PACKAGE) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) ctx.startActivity(intent) mDevice.wait(Until.hasObject(By.pkg(EFFICIO_PACKAGE).depth(0)), 5000) } fun assertItemsOrder(items: Array<String>) { val max = items.size if (max > 1) { var i = 0 do { val a = mDevice.findObject(By.text(items[i])) val b = mDevice.findObject(By.text(items[i + 1])) i++ Assert.assertTrue(a.visibleCenter.y < b.visibleCenter.y) } while (i < items.size - 2) } } @Before fun setup() { mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) MainActivity.TEST_MODE = true launchApp() // clear DB MainActivity.TEST_MODE = false deleteWidgetOnHome() setWidgetOnHome() } @Test fun testWidget() { // test add item launchApp() addItem(ITEM_A, DEP_A) backToHome() Assert.assertNotNull(mDevice.findObject(By.text(ITEM_A))) // test add another item launchApp() addItem(ITEM_B, DEP_B) backToHome() Assert.assertNotNull(mDevice.findObject(By.text(ITEM_A))) Assert.assertNotNull(mDevice.findObject(By.text(ITEM_B))) // test check item launchApp() clickTickOfTaskAt(0) backToHome() Assert.assertNull(mDevice.findObject(By.text(ITEM_A))) Assert.assertNotNull(mDevice.findObject(By.text(ITEM_B))) // test uncheck item launchApp() clickTickOfTaskAt(2) backToHome() Assert.assertNotNull(mDevice.findObject(By.text(ITEM_A))) Assert.assertNotNull(mDevice.findObject(By.text(ITEM_B))) // test order assertItemsOrder(arrayOf(ITEM_A, ITEM_B)) launchApp() dragTask(1, Direction.UP) backToHome() assertItemsOrder(arrayOf(ITEM_B, ITEM_A)) // test delete item launchApp() clickOnTask(1) Espresso.onView(ViewMatchers.withId(R.id.delete_task_btn)).perform(ViewActions.click()) Espresso.onView(ViewMatchers.withText("OK")).perform(ViewActions.click()) backToHome() Assert.assertNull(mDevice.findObject(By.text(ITEM_A))) Assert.assertNotNull(mDevice.findObject(By.text(ITEM_B))) } }
gpl-2.0
e3a56c7a3a414849ef39340816dfe72e
33.143564
95
0.62413
4.18955
false
true
false
false
kittinunf/ReactiveAndroid
reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/view/ViewPagerEvent.kt
1
2823
package com.github.kittinunf.reactiveandroid.support.v4.view import android.support.v4.view.ViewPager import com.github.kittinunf.reactiveandroid.ExtensionFieldDelegate import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription import io.reactivex.Observable //================================================================================ // Events //================================================================================ fun ViewPager.rx_pageScrollStateChanged(): Observable<Int> { return Observable.create { subscriber -> _pageChange.onPageScrollStateChanged { subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { removeOnPageChangeListener(_pageChange) }) } } data class PageScrolledListener(val position: Int, val positionOffset: Float, val positionOffsetPixels: Int) fun ViewPager.rx_pageScrolled(): Observable<PageScrolledListener> { return Observable.create { subscriber -> _pageChange.onPageScrolled { position, positionOffset, positionOffsetPixels -> subscriber.onNext(PageScrolledListener(position, positionOffset, positionOffsetPixels)) } subscriber.setDisposable(AndroidMainThreadSubscription { removeOnPageChangeListener(_pageChange) }) } } fun ViewPager.rx_pageSelected(): Observable<Int> { return Observable.create { subscriber -> _pageChange.onPageSelected { subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { removeOnPageChangeListener(_pageChange) }) } } private val ViewPager._pageChange: _ViewPager_OnPageChangeListener by ExtensionFieldDelegate({ _ViewPager_OnPageChangeListener() }, { addOnPageChangeListener(it) }) private class _ViewPager_OnPageChangeListener : ViewPager.OnPageChangeListener { private var onPageScrollStateChanged: ((Int) -> Unit)? = null private var onPageScrolled: ((Int, Float, Int) -> Unit)? = null private var onPageSelected: ((Int) -> Unit)? = null fun onPageScrollStateChanged(listener: (Int) -> Unit) { onPageScrollStateChanged = listener } override fun onPageScrollStateChanged(state: Int) { onPageScrollStateChanged?.invoke(state) } fun onPageScrolled(listener: (Int, Float, Int) -> Unit) { onPageScrolled = listener } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { onPageScrolled?.invoke(position, positionOffset, positionOffsetPixels) } fun onPageSelected(listener: (Int) -> Unit) { onPageSelected = listener } override fun onPageSelected(position: Int) { onPageSelected?.invoke(position) } }
mit
1ee9a5cd48ba8a27dc69bb4597314f68
32.211765
108
0.671626
5.568047
false
false
false
false
signed/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/lValueUtil.kt
1
1865
/* * 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. */ @file:JvmName("GroovyLValueUtil") package org.jetbrains.plugins.groovy.lang.psi.util import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrTupleExpression /** * The expression is a rValue when it is in rValue position or it's a lValue of operator assignment. */ fun GrExpression.isRValue(): Boolean { val (parent, lastParent) = skipParentsOfType(GrParenthesizedExpression::class.java, GrTupleExpression::class.java) ?: return true return parent !is GrAssignmentExpression || lastParent != parent.lValue || parent.operationTokenType != GroovyTokenTypes.mASSIGN } /** * The expression is a lValue when it's on the left of whatever assignment. */ fun GrExpression.isLValue(): Boolean { val (parent, lastParent) = skipParentsOfType(GrParenthesizedExpression::class.java, GrTupleExpression::class.java) ?: return true return parent is GrAssignmentExpression && lastParent == parent.lValue }
apache-2.0
00fde23ac9f0630d7cf54e6d9e16ba19
45.625
131
0.786059
4.277523
false
false
false
false
Nagarajj/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteExecutionHandlerSpec.kt
1
7145
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.events.ExecutionComplete import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.spek.shouldEqual import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher object CompleteExecutionHandlerSpec : SubjectSpek<CompleteExecutionHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val publisher: ApplicationEventPublisher = mock() subject { CompleteExecutionHandler(queue, repository, publisher) } fun resetMocks() = reset(queue, repository, publisher) setOf(SUCCEEDED, TERMINAL, CANCELED).forEach { stageStatus -> describe("when an execution completes and has a single stage with $stageStatus status") { val pipeline = pipeline { application = "foo" stage { refId = "1" status = stageStatus } } val message = CompleteExecution(pipeline) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the execution") { verify(repository).updateStatus(message.executionId, stageStatus) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionComplete> { it.executionType shouldEqual pipeline.javaClass it.executionId shouldEqual pipeline.id it.status shouldEqual stageStatus }) } it("does not queue any other commands") { verifyZeroInteractions(queue) } } } describe("an execution appears to complete but other branches are still running") { val pipeline = pipeline { application = "foo" stage { refId = "1" status = SUCCEEDED } stage { refId = "2" status = RUNNING } } val message = CompleteExecution(pipeline) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("waits for the other branch(es)") { verify(repository, never()).updateStatus(eq(pipeline.id), any()) } it("does not publish any events") { verifyZeroInteractions(publisher) } it("does not queue any other commands") { verifyZeroInteractions(queue) } } setOf(TERMINAL, CANCELED).forEach { stageStatus -> describe("a stage signals branch completion with $stageStatus but other branches are still running") { val pipeline = pipeline { application = "foo" stage { refId = "1" status = stageStatus } stage { refId = "2" status = RUNNING } stage { refId = "3" status = RUNNING } } val message = CompleteExecution(pipeline) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the pipeline status") { verify(repository).updateStatus(pipeline.id, stageStatus) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionComplete> { it.executionType shouldEqual pipeline.javaClass it.executionId shouldEqual pipeline.id it.status shouldEqual stageStatus }) } it("cancels other stages") { verify(queue).push(CancelStage(pipeline.stageByRef("2"))) verify(queue).push(CancelStage(pipeline.stageByRef("3"))) verifyNoMoreInteractions(queue) } } } describe("when a stage status was STOPPED but should fail the pipeline at the end") { val pipeline = pipeline { application = "foo" stage { refId = "1a" status = STOPPED context["completeOtherBranchesThenFail"] = true } stage { refId = "1b" requisiteStageRefIds = setOf("1a") status = NOT_STARTED } stage { refId = "2" status = SUCCEEDED } } val message = CompleteExecution(pipeline) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the execution") { verify(repository).updateStatus(message.executionId, TERMINAL) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionComplete> { it.executionType shouldEqual pipeline.javaClass it.executionId shouldEqual pipeline.id it.status shouldEqual TERMINAL }) } it("does not queue any other commands") { verifyZeroInteractions(queue) } } describe("when a stage status was STOPPED and should not fail the pipeline at the end") { val pipeline = pipeline { application = "foo" stage { refId = "1a" status = STOPPED context["completeOtherBranchesThenFail"] = false } stage { refId = "1b" requisiteStageRefIds = setOf("1a") status = NOT_STARTED } stage { refId = "2" status = SUCCEEDED } } val message = CompleteExecution(pipeline) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the execution") { verify(repository).updateStatus(message.executionId, SUCCEEDED) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionComplete> { it.executionType shouldEqual pipeline.javaClass it.executionId shouldEqual pipeline.id it.status shouldEqual SUCCEEDED }) } it("does not queue any other commands") { verifyZeroInteractions(queue) } } })
apache-2.0
9d3c36f2c1ad3a1903757457e40251c4
26.480769
106
0.649265
4.821188
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/utils/RecyclerViewExt.kt
1
2949
package be.digitalia.fosdem.utils import android.view.MotionEvent import androidx.core.view.get import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener import androidx.viewpager2.widget.ViewPager2 import kotlin.math.abs val ViewPager2.recyclerView: RecyclerView get() { return this[0] as RecyclerView } fun RecyclerView.enforceSingleScrollDirection() { val enforcer = SingleScrollDirectionEnforcer() addOnItemTouchListener(enforcer) addOnScrollListener(enforcer) } private class SingleScrollDirectionEnforcer : RecyclerView.OnScrollListener(), OnItemTouchListener { private var scrollState = RecyclerView.SCROLL_STATE_IDLE private var scrollPointerId = -1 private var initialTouchX = 0 private var initialTouchY = 0 private var dx = 0 private var dy = 0 override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { when (e.actionMasked) { MotionEvent.ACTION_DOWN -> { scrollPointerId = e.getPointerId(0) initialTouchX = (e.x + 0.5f).toInt() initialTouchY = (e.y + 0.5f).toInt() } MotionEvent.ACTION_POINTER_DOWN -> { val actionIndex = e.actionIndex scrollPointerId = e.getPointerId(actionIndex) initialTouchX = (e.getX(actionIndex) + 0.5f).toInt() initialTouchY = (e.getY(actionIndex) + 0.5f).toInt() } MotionEvent.ACTION_MOVE -> { val index = e.findPointerIndex(scrollPointerId) if (index >= 0 && scrollState != RecyclerView.SCROLL_STATE_DRAGGING) { val x = (e.getX(index) + 0.5f).toInt() val y = (e.getY(index) + 0.5f).toInt() dx = x - initialTouchX dy = y - initialTouchY } } } return false } override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {} override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {} override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { val oldState = scrollState scrollState = newState if (oldState == RecyclerView.SCROLL_STATE_IDLE && newState == RecyclerView.SCROLL_STATE_DRAGGING) { recyclerView.layoutManager?.let { layoutManager -> val canScrollHorizontally = layoutManager.canScrollHorizontally() val canScrollVertically = layoutManager.canScrollVertically() if (canScrollHorizontally != canScrollVertically) { if ((canScrollHorizontally && abs(dy) > abs(dx)) || (canScrollVertically && abs(dx) > abs(dy))) { recyclerView.stopScroll() } } } } } }
apache-2.0
97c6bb6b22bca999eaa8c0a93237c24a
37.815789
107
0.615124
5.093264
false
false
false
false
eugeis/ee
ee-lang_item/src/main/kotlin/ee/lang/ItemUtils.kt
1
9450
package ee.lang import ee.common.ext.buildLabel import ee.common.ext.ifElse import org.slf4j.LoggerFactory import java.util.* private val log = LoggerFactory.getLogger("ItemUtils") val IGNORE = "ignore" data class InitChain<T>(val initFunctions: List<T.() -> Unit>) : Function1<T, Unit> { override fun invoke(p1: T) { initFunctions.forEach { it.invoke(p1) } } } fun <T> inits(vararg initFunctions: T.() -> Unit) = InitChain(initFunctions.toList()) fun ItemI<*>.findDerivedOrThis() = if (derivedFrom().isEMPTY()) this else derivedFrom() fun ItemI<*>.isOrDerived(item: ItemI<*>) = this == item || derivedFrom() == item fun <T : ItemI<*>> List<T>.extend(code: T.() -> Unit = {}) { forEach { it.extend(code) } } fun <T : ItemI<*>> T.extend(code: T.() -> Unit = {}) { code() init() if (this is MultiHolderI<*, *>) { fillSupportsItems() } } fun <B : ItemI<*>> B.doc(comment: String): B = apply { val ret = Comment() ret.name(comment) doc(ret) } fun <B : ItemI<B>> List<B>.derive(adapt: B.() -> Unit = {}): List<B> { return map { it.derive(adapt) } } fun <T : ItemI<*>> ItemI<*>.findThisOrParentUnsafe(clazz: Class<*>): T? { @Suppress("UNCHECKED_CAST") return if (clazz.isInstance(this)) this as T else findParentUnsafe(clazz) } fun <T : ItemI<*>> ItemI<*>.findThisOrParent(clazz: Class<T>): T? { return if (clazz.isInstance(this)) this as T else findParent(clazz) } fun <T : ItemI<*>> ItemI<*>.findParent(clazz: Class<T>): T? { val parent = parent() return when { parent.isEMPTY() -> null clazz.isInstance(parent) -> @Suppress("UNCHECKED_CAST") parent as T else -> parent.findParent(clazz) } } fun <T : ItemI<*>> ItemI<*>.findParentUnsafe(clazz: Class<*>): T? { val parent = parent() return when { parent.isEMPTY() -> null clazz.isInstance(parent) -> @Suppress("UNCHECKED_CAST") parent as T else -> parent.findParentUnsafe(clazz) } } fun <T : ItemI<*>> ItemI<*>.findParentMust(clazz: Class<T>): T { val parent = parent() return when { parent.isEMPTY() -> throw IllegalStateException("There is no parent for $clazz in ${this.name()}") clazz.isInstance(parent) -> @Suppress("UNCHECKED_CAST") parent as T else -> parent.findParentMust(clazz) } } fun <T : ItemI<*>> ItemI<*>.findParentNonInternal(): T? { val parent = parent() if (parent.isEMPTY()) { return null } else if (!parent.isInternal()) { @Suppress("UNCHECKED_CAST") return parent as T } else { return parent.findParentNonInternal() } } fun <T> MultiHolderI<*, *>.findAllByType(type: Class<T>): List<T> { return items().filterIsInstance(type) } fun <T> ItemI<*>.findUpByType( type: Class<T>, destination: MutableList<T> = mutableListOf(), alreadyHandled: MutableSet<ItemI<*>> = hashSetOf(), stopSteppingUpIfFound: Boolean = true ): List<T> = findAcrossByType(type, destination, alreadyHandled, stopSteppingUpIfFound) { listOf(parent()) } fun <T> ItemI<*>.findAcrossByType( type: Class<T>, destination: MutableList<T> = mutableListOf(), alreadyHandled: MutableSet<ItemI<*>> = HashSet(), stopSteppingAcrossIfFound: Boolean = true, acrossSelector: ItemI<*>.() -> Collection<ItemI<*>> ): List<T> = findAcross({ @Suppress("UNCHECKED_CAST") if (type.isInstance(this)) this as T else null }, destination, alreadyHandled, stopSteppingAcrossIfFound, acrossSelector) @Suppress("UNCHECKED_CAST") fun <T> MultiHolderI<*, *>.findDownByType( type: Class<T>, destination: MutableList<T> = mutableListOf(), alreadyHandled: MutableSet<ItemI<*>> = hashSetOf(), stopSteppingDownIfFound: Boolean = true ): List<T> = findAcrossByType(type, destination, alreadyHandled, stopSteppingDownIfFound) { val ret = if (this is MultiHolderI<*, *> && supportsItemType(ItemI::class.java)) { (items() as Collection<ItemI<*>>).filter { !it.name().startsWith("__") } } else { emptyList() } ret } @Suppress("UNCHECKED_CAST") fun <T> ItemI<*>.findDown( select: ItemI<*>.() -> T?, destination: MutableList<T> = mutableListOf(), alreadyHandled: MutableSet<ItemI<*>> = HashSet(), stopSteppingAcrossIfFound: Boolean = true ): List<T> = findAcross(select, destination, alreadyHandled, stopSteppingAcrossIfFound) { if (this is MultiHolderI<*, *> && supportsItemType(ItemI::class.java)) { (items() as Collection<ItemI<*>>).filter { !it.name().startsWith("__") } } else { emptyList() } } fun <T> ItemI<*>.findAcross( select: ItemI<*>.() -> T?, destination: MutableList<T> = mutableListOf(), alreadyHandled: MutableSet<ItemI<*>> = HashSet(), stopSteppingAcrossIfFound: Boolean = true, acrossSelector: ItemI<*>.() -> Collection<ItemI<*>> ): List<T> { val items = acrossSelector() items.forEach { acrossItem -> if (!alreadyHandled.contains(acrossItem)) { alreadyHandled.add(acrossItem) val selected = acrossItem.select() if (selected != null && !destination.contains(selected)) { destination.add(selected) if (!stopSteppingAcrossIfFound) { acrossItem.findAcross( select, destination, alreadyHandled, stopSteppingAcrossIfFound, acrossSelector ) } } else { acrossItem.findAcross(select, destination, alreadyHandled, stopSteppingAcrossIfFound, acrossSelector) } } } return destination } fun <B : MultiHolderI<I, *>, I> B.initObjectTree( deriveNamespace: ItemI<*>.() -> String = { parent().namespace() } ): B { initIfNotInitialized() if (name().isBlank()) { name(buildLabel().name) } if (namespace().isBlank()) namespace(deriveNamespace()) for (f in javaClass.declaredFields) { try { val name = f.name val getter = javaClass.declaredMethods.find { it.name == "get${name.capitalize()}" || //isXy getters it.name == name } if (getter != null) { val child = getter.invoke(this) if (child is ItemI<*>) { child.initIfNotInitialized() if (child.name().isBlank() && name != IGNORE) child.name(name) //set the parent, parent shall be the DSL model parent and not some isInternal object or reference object child.parent(this) if (!containsItem(child as I)) { addItem(child) } if (child.namespace().isBlank()) { child.namespace(child.deriveNamespace()) } } } } catch (e: Exception) { log.info("$f $e") } } javaClass.declaredClasses.forEach { val child = it.findInstance() if (child != null && child is ItemI<*>) { if (!child.isInitialized()) child.init() if (child.name().isBlank()) child.name(child.buildLabel().name) //initObjectTree recursively if the parent is not set //set the parent, parent shall be the DSL model parent and not some isInternal object or reference object child.parent(this) if (!containsItem(child as I)) { addItem(child) if (child is MultiHolderI<*, *>) (child as B).initObjectTree<B, I>(deriveNamespace) } } } fillSupportsItems() return this } fun <T> Class<T>.findInstance(): Any? = try { //val field = declaredFields.find { "INSTANCE" == name } //return field?.get(null) getField("INSTANCE").get(null) } catch (e: Exception) { null } fun MultiHolderI<*, *>.initBlackNames() { findDown({ if (this.name().isBlank()) this else null }).forEach { it.initBlackName() } } fun ItemI<*>.initBlackName() { if (name().isBlank()) { if (derivedFrom().isNotEMPTY() && derivedFrom().name().isNotBlank()) { name(derivedFrom().name()) } else if (parent().isNotEMPTY() && parent().name().isNotBlank()) { name(parent().name()) } else { log.info("can't resolve name of $this") } } } fun ItemI<*>.initIfNotInitialized() { if (!isInitialized()) init() } fun Boolean?.notNullValueOrTrue(): Boolean = notNullValueElse(false) fun Boolean?.notNullValueOrFalse(): Boolean = notNullValueElse(false) fun Boolean?.notNullValueElse(valueIfNull: () -> Boolean): Boolean = if (this == null) valueIfNull() else this fun Boolean?.notNullValueElse(valueIfNull: Boolean): Boolean = if (this == null) valueIfNull else this fun ItemI<*>.deriveNamespace(name: String) = (namespace().endsWith(name)).ifElse(namespace()) { "${namespace()}.$name" } fun ItemI<*>.deriveNamespaceShared(name: String) = (namespace().endsWith(name) || "shared".equals(name, true)).ifElse( namespace() ) { "${namespace()}.$name" }
apache-2.0
f3fa67f215a59afae3b242cf36853707
31.8125
125
0.579048
4.054054
false
false
false
false
vanniktech/Emoji
emoji-google-compat/src/commonMain/kotlin/com/vanniktech/emoji/googlecompat/category/SmileysAndPeopleCategoryChunk3.kt
1
78283
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.googlecompat.category import com.vanniktech.emoji.googlecompat.GoogleCompatEmoji internal object SmileysAndPeopleCategoryChunk3 { internal val EMOJIS: List<GoogleCompatEmoji> = listOf( GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F37C), 0, 3), listOf("man_feeding_baby"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F37C), 0, 3), listOf("person_feeding_baby"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F47C), 0, 1), listOf("angel"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F47C, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F47C, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F47C, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F47C, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F47C, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F385), 0, 1), listOf("santa"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F385, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F385, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F385, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F385, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F385, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F936), 0, 1), listOf("mrs_claus", "mother_christmas"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F936, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F936, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F936, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F936, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F936, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F384), 0, 3), listOf("mx_claus"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F384), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F384), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F384), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F384), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F384), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B8), 0, 1), listOf("superhero"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B8, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_superhero"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B8, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_superhero"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B8, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B9), 0, 1), listOf("supervillain"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B9, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_supervillain"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B9, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_supervillain"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B9, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D9), 0, 1), listOf("mage"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D9, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_mage"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D9, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_mage"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D9, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DA), 0, 1), listOf("fairy"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DA, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_fairy"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DA, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_fairy"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DA, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DB), 0, 1), listOf("vampire"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DB, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_vampire"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DB, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_vampire"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DB, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DC), 0, 1), listOf("merperson"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DC, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("merman"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DC, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("mermaid"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DC, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DD), 0, 1), listOf("elf"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DD, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_elf"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9DD, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_elf"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DD, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x1F9DE), 0, 1), listOf("genie"), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DE, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_genie"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DE, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_genie"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DF), 0, 1), listOf("zombie"), true), GoogleCompatEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_zombie"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_zombie"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CC), 0, 1), listOf("troll"), false), GoogleCompatEmoji( String(intArrayOf(0x1F486), 0, 1), listOf("massage"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F486, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-massage"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F486, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-massage"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F487), 0, 1), listOf("haircut"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F487, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-haircut"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F487, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-haircut"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B6), 0, 1), listOf("walking"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-walking"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-walking"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9CD), 0, 1), listOf("standing_person"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9CD, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_standing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9CD, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_standing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9CE), 0, 1), listOf("kneeling_person"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9CE, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_kneeling"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9CE, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_kneeling"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9AF), 0, 3), listOf("person_with_probing_cane"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9AF), 0, 3), listOf("man_with_probing_cane"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9AF), 0, 3), listOf("woman_with_probing_cane"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BC), 0, 3), listOf("person_in_motorized_wheelchair"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9BC), 0, 3), listOf("man_in_motorized_wheelchair"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9BC), 0, 3), listOf("woman_in_motorized_wheelchair"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BD), 0, 3), listOf("person_in_manual_wheelchair"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9BD), 0, 3), listOf("man_in_manual_wheelchair"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9BD), 0, 3), listOf("woman_in_manual_wheelchair"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3C3), 0, 1), listOf("runner", "running"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3C3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-running"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3C3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-running"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F483), 0, 1), listOf("dancer"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F483, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F483, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F483, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F483, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F483, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F57A), 0, 1), listOf("man_dancing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F57A, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F57A, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F57A, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F57A, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F57A, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F574, 0xFE0F), 0, 2), listOf("man_in_business_suit_levitating"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F574, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F574, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F574, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F574, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F574, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x1F46F), 0, 1), listOf("dancers"), true), GoogleCompatEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("men-with-bunny-ears-partying", "man-with-bunny-ears-partying"), false), GoogleCompatEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("women-with-bunny-ears-partying", "woman-with-bunny-ears-partying"), false), GoogleCompatEmoji( String(intArrayOf(0x1F9D6), 0, 1), listOf("person_in_steamy_room"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_steamy_room"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_steamy_room"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D7), 0, 1), listOf("person_climbing"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D7, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_climbing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D7, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_climbing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x1F93A), 0, 1), listOf("fencer"), false), GoogleCompatEmoji( String(intArrayOf(0x1F3C7), 0, 1), listOf("horse_racing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C7, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C7, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C7, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C7, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C7, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x26F7, 0xFE0F), 0, 2), listOf("skier"), false), GoogleCompatEmoji( String(intArrayOf(0x1F3C2), 0, 1), listOf("snowboarder"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C2, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C2, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C2, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C2, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C2, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CC, 0xFE0F), 0, 2), listOf("golfer"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CC, 0xFE0F, 0x200D, 0x2642, 0xFE0F), 0, 5), listOf("man-golfing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CC, 0xFE0F, 0x200D, 0x2640, 0xFE0F), 0, 5), listOf("woman-golfing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3C4), 0, 1), listOf("surfer"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3C4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-surfing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3C4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-surfing"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6A3), 0, 1), listOf("rowboat"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6A3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-rowing-boat"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6A3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-rowing-boat"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CA), 0, 1), listOf("swimmer"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CA, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-swimming"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CA, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-swimming"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x26F9, 0xFE0F), 0, 2), listOf("person_with_ball"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x26F9, 0xFE0F, 0x200D, 0x2642, 0xFE0F), 0, 5), listOf("man-bouncing-ball"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x26F9, 0xFE0F, 0x200D, 0x2640, 0xFE0F), 0, 5), listOf("woman-bouncing-ball"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x26F9, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CB, 0xFE0F), 0, 2), listOf("weight_lifter"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CB, 0xFE0F, 0x200D, 0x2642, 0xFE0F), 0, 5), listOf("man-lifting-weights"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F3CB, 0xFE0F, 0x200D, 0x2640, 0xFE0F), 0, 5), listOf("woman-lifting-weights"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B4), 0, 1), listOf("bicyclist"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-biking"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-biking"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B5), 0, 1), listOf("mountain_bicyclist"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B5, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-mountain-biking"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6B5, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-mountain-biking"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F938), 0, 1), listOf("person_doing_cartwheel"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F938, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-cartwheeling"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F938, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-cartwheeling"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x1F93C), 0, 1), listOf("wrestlers"), true), GoogleCompatEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-wrestling"), false), GoogleCompatEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-wrestling"), false), GoogleCompatEmoji( String(intArrayOf(0x1F93D), 0, 1), listOf("water_polo"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F93D, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-water-polo"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F93D, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-water-polo"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F93E), 0, 1), listOf("handball"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F93E, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-handball"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F93E, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-handball"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F939), 0, 1), listOf("juggling"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F939, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-juggling"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F939, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-juggling"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D8), 0, 1), listOf("person_in_lotus_position"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE), 0, 2), emptyList<String>(), true), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF), 0, 2), emptyList<String>(), true), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D8, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_lotus_position"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D8, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_lotus_position"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F6C0), 0, 1), listOf("bath"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F6C0, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6C0, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6C0, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6C0, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F6C0, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), ) }
apache-2.0
9fb95ac738d56ef43fc2e325e686d650
70.883379
164
0.682541
2.796549
false
false
false
false
edsilfer/presence-control
app/src/main/java/br/com/edsilfer/android/presence_control/user/presentation/view/LoginView.kt
1
2864
package br.com.edsilfer.android.presence_control.user.presentation.view import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import br.com.edsilfer.android.presence_control.R import br.com.edsilfer.android.presence_control.core.di.Injector import br.com.edsilfer.android.presence_control.core.presentation.BaseActivity import br.com.edsilfer.android.presence_control.databinding.LoginViewBinding import br.com.edsilfer.android.presence_control.user.presentation.presenter.ILoginPresenter import com.facebook.CallbackManager import com.facebook.FacebookCallback import com.facebook.FacebookException import com.facebook.login.LoginResult import kotlinx.android.synthetic.main.login_view.* import timber.log.Timber import javax.inject.Inject /** * A login screen that offers login via email/password/facebook. */ class LoginView : BaseActivity(), ILoginView { companion object { private val ARG_FACEBOOK_PERMISSIONS = mutableListOf("public_profile", "email", "user_birthday") fun getIntent(context: Context): Intent { return Intent(context, LoginView::class.java) } } @Inject lateinit var mPresenter: ILoginPresenter lateinit var mFacebookCallback: CallbackManager override fun getPresenter() = mPresenter override fun getViewContext() = this override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.login_view) Injector.getInstance().inject(this) initDataBinding() assembleFacebookLogin() } private fun assembleFacebookLogin() { mFacebookCallback = CallbackManager.Factory.create() button_facebookLogin.setReadPermissions(ARG_FACEBOOK_PERMISSIONS) button_facebookLogin.registerCallback(mFacebookCallback, object : FacebookCallback<LoginResult> { override fun onCancel() { Timber.w("Facebook login was canceled") } override fun onError(error: FacebookException?) { mPresenter.onFacebookLoginError(error) } override fun onSuccess(result: LoginResult?) { mPresenter.onFacebookLoginSuccess(result) } }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) mFacebookCallback.onActivityResult(requestCode, resultCode, data); } private fun initDataBinding() { val binding: LoginViewBinding = DataBindingUtil.setContentView(this, R.layout.login_view) binding.presenter = mPresenter } override fun getCredentials(): Pair<String, String> { return Pair(username.text.toString(), password.text.toString()) } }
apache-2.0
4a37f86c91fd81b19e504022aff24247
35.253165
105
0.724511
4.895726
false
false
false
false
jitsi/jitsi-videobridge
rtp/src/main/kotlin/org/jitsi/rtp/rtcp/rtcpfb/transport_layer_fb/RtcpFbNackPacket.kt
1
6470
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.rtp.rtcp.rtcpfb.transport_layer_fb import org.jitsi.rtp.extensions.bytearray.getShort import org.jitsi.rtp.extensions.bytearray.putShort import org.jitsi.rtp.extensions.unsigned.toPositiveInt import org.jitsi.rtp.rtcp.RtcpHeaderBuilder import org.jitsi.rtp.rtcp.rtcpfb.RtcpFbPacket import org.jitsi.rtp.util.BufferPool import org.jitsi.rtp.util.RtpUtils import java.util.SortedSet /** * https://tools.ietf.org/html/rfc4585#section-6.2.1 * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |V=2|P| FMT | PT | length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | SSRC of packet sender | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | SSRC of media source | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | PID | BLP | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | (optional) PID | BLP | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ class RtcpFbNackPacket( buffer: ByteArray, offset: Int, length: Int ) : TransportLayerRtcpFbPacket(buffer, offset, length) { private val numNackBlocks: Int = (packetLength - HEADER_SIZE) / NackBlock.SIZE_BYTES val missingSeqNums: SortedSet<Int> by lazy { (0 until numNackBlocks) .map { NackBlock.getMissingSeqNums(buffer, offset + NACK_BLOCK_OFFSET + it * NackBlock.SIZE_BYTES) } .flatten() .toSortedSet() } override fun clone(): RtcpFbNackPacket = RtcpFbNackPacket(cloneBuffer(0), 0, length) companion object { const val FMT = 1 const val NACK_BLOCK_OFFSET = HEADER_SIZE } } class RtcpFbNackPacketBuilder( val rtcpHeader: RtcpHeaderBuilder = RtcpHeaderBuilder(), var mediaSourceSsrc: Long = -1, val missingSeqNums: SortedSet<Int> = sortedSetOf() ) { private val nackBlocks: List<NackBlock> = missingSeqNums.toList().chunkMaxDifference(16) .map(List<Int>::toSortedSet) .map(::NackBlock) .toList() private val sizeBytes: Int = RtcpFbPacket.HEADER_SIZE + nackBlocks.size * NackBlock.SIZE_BYTES fun build(): RtcpFbNackPacket { val buf = BufferPool.getArray(sizeBytes) writeTo(buf, 0) return RtcpFbNackPacket(buf, 0, sizeBytes) } fun writeTo(buf: ByteArray, offset: Int) { rtcpHeader.apply { packetType = TransportLayerRtcpFbPacket.PT reportCount = RtcpFbNackPacket.FMT length = RtpUtils.calculateRtcpLengthFieldValue(sizeBytes) } rtcpHeader.writeTo(buf, offset) RtcpFbPacket.setMediaSourceSsrc(buf, offset, mediaSourceSsrc) nackBlocks.forEachIndexed { index, nackBlock -> nackBlock.writeTo(buf, offset + RtcpFbNackPacket.NACK_BLOCK_OFFSET + index * NackBlock.SIZE_BYTES) } } } /** * Return a List of Lists, where sub-list is made up of an ordered list * of values pulled from [this], such that the difference between the * first element and the last element is not more than [maxDifference] */ private fun List<Int>.chunkMaxDifference(maxDifference: Int): List<List<Int>> { val chunks = mutableListOf<List<Int>>() if (this.isEmpty()) { return chunks } var currentChunk = mutableListOf(first()) chunks.add(currentChunk) // Ignore the first value which we already put in the current chunk drop(1).forEach { if (it - currentChunk.first() > maxDifference) { currentChunk = mutableListOf(it) chunks.add(currentChunk) } else { currentChunk.add(it) } } return chunks } /** * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | PID | BLP | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ private class NackBlock( val missingSeqNums: SortedSet<Int> = sortedSetOf() ) { fun writeTo(buf: ByteArray, offset: Int) { putMissingSeqNums(buf, offset, missingSeqNums) } companion object { const val SIZE_BYTES = 4 fun getMissingSeqNums(buf: ByteArray, offset: Int): List<Int> { val packetId = buf.getShort(offset + 0).toPositiveInt() val blp = buf.getShort(offset + 2).toPositiveInt() val missingSeqNums = mutableListOf(packetId) for (shiftAmount in 0..15) { if (((blp ushr shiftAmount) and 0x1) == 1) { missingSeqNums.add((packetId + shiftAmount + 1) and 0xffff) } } return missingSeqNums } /** * [missingSeqNums].last() - [missingSeqNums].first() MUST be <= 16 * [offset] should point to the start of where this NackBlock will go */ fun putMissingSeqNums(buf: ByteArray, offset: Int, missingSeqNums: SortedSet<Int>) { val packetId = missingSeqNums.first() buf.putShort(offset, packetId.toShort()) var blpField = 0 for (bitPos in 16 downTo 1) { if ((bitPos + packetId) in missingSeqNums) { blpField = blpField or 1 } // Don't shift the last time if (bitPos != 1) { blpField = blpField shl 1 } } buf.putShort(offset + 2, blpField.toShort()) } } }
apache-2.0
58e05c3e663b39c9ff31fd8e69ebb22a
35.553672
110
0.54204
4.220483
false
false
false
false
andrei-heidelbacher/algostorm
algostorm-core/src/main/kotlin/com/andreihh/algostorm/core/drivers/graphics2d/Color.kt
1
2176
/* * Copyright 2017 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andreihh.algostorm.core.drivers.graphics2d /** * A color in the `ARGB8888` format. * * @property color the `ARGB8888` encoded color */ data class Color(val color: Int) { /** * Builds an `ARGB8888` encoded color from a color `code`. * * @param code the color code * @throws IllegalArgumentException if the given `code` doesn't conform to * the `#AARRGGBB` or `#RRGGBB` format (base `16`, case insensitive) */ constructor(code: String) : this (code.let { require((code.length == 7 || code.length == 9) && code[0] == '#') { "Color '$code' has invalid format!" } val argbCode = code.drop(1) require(argbCode.none { Character.digit(it, 16) == -1 }) { "Color '$code' contains invalid characters!" } val argb = argbCode.toLong(16).toInt() if (code.length == 9) argb else argb or (0xFF shl 24) }) /** The alpha component of this color (a value between `0` and `255). */ val a: Int get() = color shr 24 and 0xFF /** The red component of this color (a value between `0` and `255`). */ val r: Int get() = color shr 16 and 0xFF /** The green component of this color (a value between `0` and `255`). */ val g: Int get() = color shr 8 and 0xFF /** The blue component of this color (a value between `0` and `255`). */ val b: Int get() = color and 0xFF /** Returns the color in `#AARRGGBB` format. */ override fun toString(): String = "#${String.format("%08x", color)}" }
apache-2.0
468dcae1c645e3962d7b31eed2ff4311
36.517241
78
0.638327
3.858156
false
false
false
false
JetBrains/resharper-unity
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/configurations/UnityAttachToEditorFormLayout.kt
1
6695
package com.jetbrains.rider.plugins.unity.run.configurations import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.uiDesigner.core.GridConstraints import com.intellij.uiDesigner.core.GridLayoutManager import com.intellij.uiDesigner.core.Spacer import com.intellij.util.ui.JBUI import com.jetbrains.rider.plugins.unity.UnityBundle import java.awt.Dimension import java.awt.Insets import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JTextField open class UnityAttachToEditorFormLayout() { protected var rootPanel: JPanel? = null protected var commentLabel: JLabel? = null protected lateinit var editorInstanceJsonError: JLabel protected lateinit var processIdInfo: JLabel protected lateinit var editorInstanceJsonErrorPanel: JPanel protected lateinit var processesList: ProcessesPanel protected lateinit var editorInstanceJsonInfoPanel: JPanel protected lateinit var textField1: JTextField val panel: JPanel get() = (rootPanel)!! private fun createUIComponents() { commentLabel = ComponentPanelBuilder.createCommentComponent( UnityBundle.message("comment.label.text.editorinstance.json.file.required.to.automatically.configure.run.configuration"), true) commentLabel!!.border = JBUI.Borders.emptyLeft(18) } init { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! `$$$setupUI$$$`() } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private fun `$$$setupUI$$$`() { createUIComponents() rootPanel = JPanel() rootPanel!!.layout = GridLayoutManager(6, 1, Insets(0, 0, 0, 0), -1, -1) editorInstanceJsonErrorPanel = JPanel() editorInstanceJsonErrorPanel!!.layout = GridLayoutManager(3, 1, Insets(0, 0, 0, 0), -1, -1) rootPanel!!.add(editorInstanceJsonErrorPanel, GridConstraints(0, 0, 3, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)) editorInstanceJsonError = JLabel() editorInstanceJsonError!!.text = UnityBundle.message("editorinstance.error") editorInstanceJsonErrorPanel!!.add(editorInstanceJsonError, GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)) editorInstanceJsonErrorPanel!!.add(commentLabel, GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)) val spacer1 = Spacer() editorInstanceJsonErrorPanel!!.add(spacer1, GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, Dimension(-1, 25), Dimension(-1, 25), Dimension(-1, 25), 1, false)) processesList = ProcessesPanel() rootPanel!!.add(processesList, GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)) editorInstanceJsonInfoPanel = JPanel() editorInstanceJsonInfoPanel!!.layout = GridLayoutManager(2, 1, Insets(0, 0, 0, 0), -1, -1) rootPanel!!.add(editorInstanceJsonInfoPanel, GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)) processIdInfo = JLabel() processIdInfo!!.text = UnityBundle.message("using.process") editorInstanceJsonInfoPanel!!.add(processIdInfo, GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)) val spacer2 = Spacer() editorInstanceJsonInfoPanel!!.add(spacer2, GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, Dimension(-1, 25), Dimension(-1, 25), Dimension(-1, 25), 0, false)) textField1 = JTextField() textField1!!.isEnabled = false textField1!!.isVisible = false rootPanel!!.add(textField1, GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, Dimension(150, -1), null, 0, false)) } /** * @noinspection ALL */ fun `$$$getRootComponent$$$`(): JComponent? { return rootPanel } }
apache-2.0
516c86a17700d2415dba06203f927f06
60.431193
147
0.572218
5.351719
false
false
false
false
spark/photon-tinker-android
meshui/src/main/java/io/particle/mesh/ui/controlpanel/ControlPanelEthernetOptionsFragment.kt
1
2086
package io.particle.mesh.ui.controlpanel import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentActivity import io.particle.mesh.setup.flow.FlowRunnerUiListener import io.particle.mesh.setup.flow.Scopes import io.particle.mesh.setup.utils.runOnMainThread import io.particle.mesh.setup.utils.safeToast import io.particle.mesh.ui.R import io.particle.mesh.ui.TitleBarOptions import io.particle.mesh.ui.inflateFragment import kotlinx.android.synthetic.main.fragment_control_panel_ethernet_options.* import kotlinx.coroutines.GlobalScope import mu.KotlinLogging class ControlPanelEthernetOptionsFragment : BaseControlPanelFragment() { override val titleBarOptions = TitleBarOptions( R.string.p_cp_ethernet, showBackButton = true ) private val log = KotlinLogging.logger {} override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return container?.inflateFragment(R.layout.fragment_control_panel_ethernet_options) } override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) { super.onFragmentReady(activity, flowUiListener) val checked = flowUiListener.deviceData.isEthernetEnabled p_controlpanel_ethernet_options_toggle_pins_switch.isChecked = checked p_controlpanel_ethernet_options_toggle_pins_switch.setOnClickListener { toggleEthernetPins(p_controlpanel_ethernet_options_toggle_pins_switch.isChecked) } val statusText = if (flowUiListener.deviceData.isEthernetEnabled) "Active" else "Inactive" p_controlpanel_ethernet_options_current_pins_status.text = statusText } private fun toggleEthernetPins(shouldEnable: Boolean) { Scopes().onMain { startFlowWithBarcode { device, barcode -> flowRunner.startControlPanelToggleEthernetPinsFlow(device, barcode, shouldEnable) } } } }
apache-2.0
c8ee70f79dcb8a37c22d8c7075091fdc
36.25
100
0.751678
4.615044
false
false
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/ExperimentalCardClip.kt
1
4131
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.kotlin.widget import android.content.Context import android.graphics.Color import com.facebook.litho.MeasureScope import com.facebook.litho.MountableComponent import com.facebook.litho.MountableComponentScope import com.facebook.litho.MountableRenderResult import com.facebook.litho.SimpleMountable import com.facebook.litho.Style import com.facebook.litho.widget.CardClipDrawable import com.facebook.litho.widget.CardClipDrawable.BOTTOM_LEFT import com.facebook.litho.widget.CardClipDrawable.BOTTOM_RIGHT import com.facebook.litho.widget.CardClipDrawable.NONE import com.facebook.litho.widget.CardClipDrawable.TOP_LEFT import com.facebook.litho.widget.CardClipDrawable.TOP_RIGHT import com.facebook.rendercore.MeasureResult /** * A component that paints rounded edges to mimic a clipping operation on the component being * rendered below it. Used in {@link CardSpec}. * * @param clippingColor Color for corner clipping. * @param cornerRadius Radius for corner clipping. * @param disableClipTopLeft If set, opt out of clipping the top-left corner * @param disableClipTopRight If set, opt out of clipping the top-right corner * @param disableClipBottomLeft If set, opt out of clipping the bottom-left corner * @param disableClipBottomRight If set, opt out of clipping the bottom-right corner */ class ExperimentalCardClip( private val clippingColor: Int = Color.WHITE, private val cornerRadius: Float? = null, private val disableClipTopLeft: Boolean = false, private val disableClipTopRight: Boolean = false, private val disableClipBottomLeft: Boolean = false, private val disableClipBottomRight: Boolean = false, private val style: Style? = null ) : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult = MountableRenderResult( CardClipMountable( clippingColor = clippingColor, cornerRadius = cornerRadius, disableClipTopLeft = disableClipTopLeft, disableClipTopRight = disableClipTopRight, disableClipBottomLeft = disableClipBottomLeft, disableClipBottomRight = disableClipBottomRight), style) } internal class CardClipMountable( private val clippingColor: Int, private val cornerRadius: Float? = null, private val disableClipTopLeft: Boolean, private val disableClipTopRight: Boolean, private val disableClipBottomLeft: Boolean, private val disableClipBottomRight: Boolean, ) : SimpleMountable<CardClipDrawable>(RenderType.DRAWABLE) { override fun createContent(context: Context): CardClipDrawable = CardClipDrawable() override fun MeasureScope.measure(widthSpec: Int, heightSpec: Int): MeasureResult = fromSpecs(widthSpec, heightSpec) override fun mount(c: Context, content: CardClipDrawable, layoutData: Any?) { clippingColor?.let { content.setClippingColor(clippingColor) } cornerRadius?.let { content.setCornerRadius(cornerRadius) } val clipEdge = ((if (disableClipTopLeft) TOP_LEFT else NONE) or (if (disableClipTopRight) TOP_RIGHT else NONE) or (if (disableClipBottomLeft) BOTTOM_LEFT else NONE) or if (disableClipBottomRight) BOTTOM_RIGHT else NONE) content.setDisableClip(clipEdge) } override fun unmount(c: Context, content: CardClipDrawable, layoutData: Any?) { content.setCornerRadius(0f) content.setClippingColor(Color.WHITE) content.setDisableClip(NONE) } }
apache-2.0
f8233a477404c4f956e0812a82cb7aa7
41.153061
93
0.757928
4.699659
false
false
false
false
google-developer-training/android-demos
DonutTracker/NestedGraphs_Include/app/src/main/java/com/android/samples/donuttracker/setup/SelectionFragment.kt
3
2355
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.samples.donuttracker.setup import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.findNavController import com.android.samples.donuttracker.UserPreferencesRepository import com.android.samples.donuttracker.databinding.FragmentSelectionBinding /** * This Fragment enables/disables coffee tracking feature. */ class SelectionFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return FragmentSelectionBinding.inflate(inflater, container, false).root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = FragmentSelectionBinding.bind(view) val selectionViewModel: SelectionViewModel by viewModels { SelectionViewModelFactory(UserPreferencesRepository.getInstance(requireContext())) } selectionViewModel.checkCoffeeTrackerEnabled().observe(viewLifecycleOwner) { selection -> if (selection == UserPreferencesRepository.Selection.DONUT_AND_COFFEE) { binding.checkBox.isChecked = true } } binding.button.setOnClickListener { button -> val coffeeSelected = binding.checkBox.isChecked selectionViewModel.saveCoffeeTrackerSelection(coffeeSelected) button.findNavController().navigate( SelectionFragmentDirections.actionSelectionFragmentToDonutList() ) } } }
apache-2.0
843b2379243c1c998ed49bb770b49fe0
35.796875
97
0.728238
5.086393
false
false
false
false
googlemaps/android-on-demand-rides-deliveries-samples
kotlin/kotlin-driver/src/main/kotlin/com/google/mapsplatform/transportation/sample/kotlindriver/provider/response/Waypoint.kt
1
1858
/* 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 * * 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.mapsplatform.transportation.sample.kotlindriver.provider.response import com.google.gson.annotations.SerializedName /** * Waypoint given by the sample provider * * <p>Sample JSON structure { "location": { "point": { "latitude": 3.456, "longitude": 4.567 } }, * "waypointType: "DROP_OFF_WAYPOINT_TYPE", "tripId": "trip" } */ class Waypoint( /** Trip ID the waypoint belongs to. */ @SerializedName("tripId") val tripId: String = "", /** Returns the waypoint location. */ @SerializedName("location") val location: Location? = null, /** Returns the type of waypoint, pickup, dropoff, or intermediateDestination. */ @SerializedName("waypointType") val waypointType: String = "", ) { /** Represents a location consisting of a single point. */ class Location( /** Returns the point that defines the location. */ @SerializedName(value = "point") val point: Point? = null ) /** Represents a point which is latitude and longitude coordinates. */ class Point( /** Returns the latitude component of the point. */ @SerializedName(value = "latitude") val latitude: Double = 0.0, /** Returns the longitude component of the point. */ @SerializedName(value = "longitude") val longitude: Double = 0.0, ) }
apache-2.0
e4cbd51eb0181d18c20231b75ae4a3bd
36.918367
97
0.705597
4.138085
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/fragment/FilesFragment.kt
2
7328
package com.commit451.gitlab.fragment import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.activity.BaseActivity import com.commit451.gitlab.activity.ProjectActivity import com.commit451.gitlab.adapter.BreadcrumbAdapter import com.commit451.gitlab.adapter.DividerItemDecoration import com.commit451.gitlab.adapter.FileAdapter import com.commit451.gitlab.event.ProjectReloadEvent import com.commit451.gitlab.extension.getUrl import com.commit451.gitlab.extension.with import com.commit451.gitlab.model.api.Project import com.commit451.gitlab.model.api.RepositoryTreeObject import com.commit451.gitlab.navigation.Navigator import com.commit451.gitlab.util.IntentUtil import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.fragment_files.* import org.greenrobot.eventbus.Subscribe import timber.log.Timber import java.util.* class FilesFragment : BaseFragment() { companion object { private const val CURRENT_PATH = "current_path" fun newInstance(): FilesFragment { return FilesFragment() } } private lateinit var adapterFiles: FileAdapter private lateinit var adapterBreadcrumb: BreadcrumbAdapter private var project: Project? = null private var ref: String? = null private var currentPath = "" private val filesAdapterListener = object : FileAdapter.Listener { override fun onFolderClicked(treeItem: RepositoryTreeObject) { loadData(currentPath + treeItem.name + "/") } override fun onFileClicked(treeItem: RepositoryTreeObject) { val path = currentPath + treeItem.name Navigator.navigateToFile(baseActivty, project!!, path, ref!!) } override fun onCopyClicked(treeItem: RepositoryTreeObject) { val clipboard = baseActivty.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager // Creates a new text clip to put on the clipboard val clip = ClipData.newPlainText(treeItem.name, treeItem.getUrl(project!!, ref!!, currentPath).toString()) clipboard.setPrimaryClip(clip) Snackbar.make(root, R.string.copied_to_clipboard, Snackbar.LENGTH_SHORT) .show() } override fun onShareClicked(treeItem: RepositoryTreeObject) { IntentUtil.share(view!!, treeItem.getUrl(project!!, ref!!, currentPath)) } override fun onOpenInBrowserClicked(treeItem: RepositoryTreeObject) { IntentUtil.openPage(activity as BaseActivity, treeItem.getUrl(project!!, ref!!, currentPath).toString(), App.get().currentAccount) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_files, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adapterFiles = FileAdapter(filesAdapterListener) list.layoutManager = LinearLayoutManager(activity) list.addItemDecoration(DividerItemDecoration(baseActivty)) list.adapter = adapterFiles adapterBreadcrumb = BreadcrumbAdapter() listBreadcrumbs.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false) listBreadcrumbs.adapter = adapterBreadcrumb swipeRefreshLayout.setOnRefreshListener { loadData() } val path = savedInstanceState?.getString(CURRENT_PATH) ?: "" if (activity is ProjectActivity) { project = (activity as ProjectActivity).project ref = (activity as ProjectActivity).getRefRef() loadData(path) } else { throw IllegalStateException("Incorrect parent activity") } App.bus().register(this) } override fun onSaveInstanceState(outState: Bundle) { outState.putString(CURRENT_PATH, currentPath) super.onSaveInstanceState(outState) } override fun onBackPressed(): Boolean { if (adapterBreadcrumb.itemCount > 1) { val breadcrumb = adapterBreadcrumb.getValueAt(adapterBreadcrumb.itemCount - 2) if (breadcrumb != null) { breadcrumb.listener.onClick() return true } } return false } override fun onDestroyView() { App.bus().unregister(this) super.onDestroyView() } override fun loadData() { loadData(currentPath) } fun loadData(newPath: String) { if (project == null || ref.isNullOrEmpty()) { swipeRefreshLayout.isRefreshing = false return } swipeRefreshLayout.isRefreshing = true App.get().gitLab.getTree(project!!.id, ref, newPath) .with(this) .subscribe({ swipeRefreshLayout.isRefreshing = false if (it.isNotEmpty()) { textMessage.visibility = View.GONE } else { Timber.d("No files found") textMessage.visibility = View.VISIBLE textMessage.setText(R.string.no_files_found) } adapterFiles.setData(it) list.scrollToPosition(0) currentPath = newPath updateBreadcrumbs() }, { Timber.e(it) swipeRefreshLayout.isRefreshing = false textMessage.visibility = View.VISIBLE textMessage.setText(R.string.connection_error_files) adapterFiles.setData(null) currentPath = newPath updateBreadcrumbs() }) } fun updateBreadcrumbs() { val breadcrumbs = ArrayList<BreadcrumbAdapter.Breadcrumb>() breadcrumbs.add(BreadcrumbAdapter.Breadcrumb(getString(R.string.root), object : BreadcrumbAdapter.Listener { override fun onClick() { loadData("") } })) var newPath = "" val segments = currentPath.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (segment in segments) { if (segment.isEmpty()) { continue } newPath += "$segment/" val finalPath = newPath breadcrumbs.add(BreadcrumbAdapter.Breadcrumb(segment, object : BreadcrumbAdapter.Listener { override fun onClick() { loadData(finalPath) } })) } adapterBreadcrumb.setData(breadcrumbs) listBreadcrumbs.scrollToPosition(adapterBreadcrumb.itemCount - 1) } @Suppress("unused") @Subscribe fun onProjectReload(event: ProjectReloadEvent) { project = event.project ref = event.branchName loadData("") } }
apache-2.0
2541b390bdf23059792b59045a9fb98d
33.729858
142
0.642604
5.260589
false
false
false
false