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
sreich/ore-infinium
core/src/com/ore/infinium/systems/server/LiquidSimulationSystem.kt
1
12117
/** MIT License Copyright (c) 2016 Shaun Reich <[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 com.ore.infinium.systems.server import com.artemis.BaseSystem import com.artemis.annotations.Wire import com.badlogic.gdx.math.RandomXS128 import com.badlogic.gdx.math.Rectangle import com.ore.infinium.OreWorld import com.ore.infinium.components.PlayerComponent import com.ore.infinium.systems.PlayerSystem import com.ore.infinium.util.* @Wire class LiquidSimulationSystem(private val oreWorld: OreWorld) : BaseSystem() { private val mPlayer by mapper<PlayerComponent>() private val serverNetworkSystem by system<ServerNetworkSystem>() private val playerSystem by system<PlayerSystem>() override fun initialize() { } companion object { /** * values 1 through 16. */ const val MAX_LIQUID_LEVEL: Byte = 16 } override fun processSystem() { for (player in oreWorld.players()) { val cPlayer = mPlayer.get(player) val rect = cPlayer.loadedViewport.rect simulateFluidsInRegion(rect, player) } } //probably want something better. like a region that self expands //when modifications are done outside of it. private var dirty = false private var dirtyRegion = Rectangle() private fun simulateFluidsInRegion(rect: Rectangle, player: Int) { val startX = oreWorld.blockXSafe(rect.lefti) val startY = oreWorld.blockYSafe(rect.topi) val endX = oreWorld.blockXSafe(rect.righti) val endY = oreWorld.blockYSafe(rect.bottomi) for (y in endY downTo startY) { for (x in startX until endX) { if (oreWorld.isWater(x, y)) { processLiquidTile(x, y) } } } if (dirty) { playerSystem.sendPlayerBlockRegion(player) // serverNetworkSystem.sendBlockRegionInterestedPlayers(oreWorld.blockXSafe(dirtyRegion.lefti), // oreWorld.blockYSafe(dirtyRegion.topi), // oreWorld.blockXSafe(dirtyRegion.righti - 1), // oreWorld.blockYSafe(dirtyRegion.bottomi - 1)) dirty = false } } fun processLiquidRange(left: Int, right: Int, top: Int, bottom: Int) { val leftSafe = oreWorld.blockXSafe(left) val rightSafe = oreWorld.blockXSafe(right) val topSafe = oreWorld.blockYSafe(top) val bottomSafe = oreWorld.blockYSafe(bottom) for (y in bottomSafe downTo topSafe) { for (x in leftSafe..rightSafe) { if (oreWorld.isWater(x, y)) { processLiquidTile(x, y) } } } } private fun isLiquidFull(level: Byte) = level == MAX_LIQUID_LEVEL enum class LeftRight { Left, Right } fun processLiquidTile(x: Int, y: Int) { val sourceAmount = oreWorld.liquidLevel(x, y) if (sourceAmount <= 0) { print("zero") error("zero?") } val bottomSafeY = oreWorld.blockYSafe(y + 1) val bottomSolid = oreWorld.isBlockSolid(x, bottomSafeY) var newSourceAmount = sourceAmount.toInt() if (!bottomSolid) { val bottomLiquid = oreWorld.liquidLevel(x, bottomSafeY) if (/*bottomLiquid < sourceAmount && */!isLiquidFull(bottomLiquid)) { newSourceAmount = moveLiquidToBottom(sourceX = x, sourceY = y, sourceAmount = sourceAmount, bottomLiquid = bottomLiquid) } } //none left to disperse if (newSourceAmount == 0) { return } //now try other 2 sides (left/right, or both) val leftSafeX = oreWorld.blockXSafe(x - 1) val leftSolid = oreWorld.isBlockSolid(leftSafeX, y) val leftLiquid = oreWorld.liquidLevel(leftSafeX, y) val rightSafeX = oreWorld.blockXSafe(x + 1) val rightSolid = oreWorld.isBlockSolid(rightSafeX, y) val rightLiquid = oreWorld.liquidLevel(rightSafeX, y) // ensure sourceAmount > 1 so we don't move around a single block of water forever val moveLeft = !leftSolid && leftLiquid < sourceAmount && sourceAmount > 1 val moveRight = !rightSolid && rightLiquid < sourceAmount && sourceAmount > 1 when { moveLeft && moveRight -> { moveLiquidLeftRight(sourceX = x, sourceY = y, sourceAmount = sourceAmount, leftLiquid = leftLiquid, rightLiquid = rightLiquid) } moveLeft -> { moveLiquidLeft(sourceX = x, sourceY = y, sourceAmount = sourceAmount, leftLiquid = leftLiquid) } moveRight -> { moveLiquidRight(sourceX = x, sourceY = y, sourceAmount = sourceAmount, rightLiquid = rightLiquid) } } } private fun moveLiquidRight(sourceX: Int, sourceY: Int, sourceAmount: Byte, rightLiquid: Byte) { val rightSafeX = oreWorld.blockXSafe(sourceX + 1) val amountToSplit = (sourceAmount + rightLiquid) / 2 val remainder = (sourceAmount + rightLiquid) % 2 //println("moveLiquidRight amountToSplit: $amountToSplit, remainder: $remainder, sourceAmount: $sourceAmount rightliquid: $rightLiquid, newRight: ${amountToSplit + remainder}") //empty current as much as possible (there still may be some left here, the source) oreWorld.setLiquidLevelClearIfEmpty(sourceX, sourceY, amountToSplit.toByte()) //fill right oreWorld.setLiquidLevelWaterNotEmpty(rightSafeX, sourceY, (amountToSplit + remainder).toByte()) updateDirtyRegion(sourceX, sourceY) } private fun moveLiquidLeft(sourceX: Int, sourceY: Int, sourceAmount: Byte, leftLiquid: Byte) { val leftSafeX = oreWorld.blockXSafe(sourceX - 1) val amountToSpread = (sourceAmount + leftLiquid) / 2 val remainder = (sourceAmount + leftLiquid) % 2 //empty current as much as possible (there still may be some left here, the source) oreWorld.setLiquidLevelClearIfEmpty(sourceX, sourceY, amountToSpread.toByte()) //fill left oreWorld.setLiquidLevelWaterNotEmpty(leftSafeX, sourceY, (amountToSpread + remainder).toByte()) updateDirtyRegion(sourceX, sourceY) } private val rand = RandomXS128() private fun moveLiquidLeftRight(sourceX: Int, sourceY: Int, sourceAmount: Byte, leftLiquid: Byte, rightLiquid: Byte) { val leftSafeX = oreWorld.blockXSafe(sourceX - 1) val rightSafeX = oreWorld.blockXSafe(sourceX + 1) var amountToSpread = (sourceAmount + leftLiquid + rightLiquid) / 3 var remainder = (sourceAmount + leftLiquid + rightLiquid) % 3 if (remainder > 0) { //here we have a sourceAmount == 2, nothing on either side leaves //a remainder of 2, but we should instead only move 1 unit of water //otherwise we're pushing *everything* in this cell to another cell //instead of evenly dispersing if (sourceAmount == 2.toByte() && remainder == 2) { remainder = 1 amountToSpread = 1 } //pick one or the other randomly?? //hack val randomDirection = 1//rand.nextInt(0, 1) assert(amountToSpread > 0) { "amount to spread impossibly 0. sourceAmount: $sourceAmount, left: $leftLiquid, right: $rightLiquid" } when (randomDirection) { 0 -> { //give more to the left oreWorld.setLiquidLevelWaterNotEmpty(leftSafeX, sourceY, (amountToSpread + remainder).toByte()) oreWorld.setLiquidLevelWaterNotEmpty(rightSafeX, sourceY, (amountToSpread).toByte()) } 1 -> { //give more to the right oreWorld.setLiquidLevelWaterNotEmpty(rightSafeX, sourceY, (amountToSpread + remainder).toByte()) oreWorld.setLiquidLevelWaterNotEmpty(leftSafeX, sourceY, amountToSpread.toByte()) } else -> error("invalid random direction") } } else { //it's spread evenly //fill left, right assert(amountToSpread > 0) oreWorld.setLiquidLevelWaterNotEmpty(leftSafeX, sourceY, amountToSpread.toByte()) oreWorld.setLiquidLevelWaterNotEmpty(rightSafeX, sourceY, amountToSpread.toByte()) } //empty current as much as possible (there still may be some left here, the source) oreWorld.setLiquidLevelClearIfEmpty(sourceX, sourceY, amountToSpread.toByte()) updateDirtyRegion(sourceX, sourceY) } /** * @return the new source amount. */ private fun moveLiquidToBottom(sourceX: Int, sourceY: Int, sourceAmount: Byte, bottomLiquid: Byte): Int { val bottomSafeY = oreWorld.blockYSafe(sourceY + 1) val freeSpace = MAX_LIQUID_LEVEL - bottomLiquid //hack val amountToMove = freeSpace.coerceAtMost(sourceAmount.toInt()) val newSourceAmount = (sourceAmount - amountToMove) //println("amounttospread: $amountToSpread, remainder: $remainder") //println("moveLiquidToBottom amounttomove: $amountToMove, remainder: $newSourceAmount, newSourceAmount: $newSourceAmount new bottom: ${amountToMove + bottomLiquid}") //empty current as much as possible (there still may be some left here, the source) oreWorld.setLiquidLevelClearIfEmpty(sourceX, sourceY, newSourceAmount.toByte()) assert(amountToMove + bottomLiquid > 0) //fill bottom oreWorld.setLiquidLevelWaterNotEmpty(sourceX, bottomSafeY, (amountToMove + bottomLiquid).toByte()) updateDirtyRegion(sourceX, sourceY) return newSourceAmount } private fun updateDirtyRegion(x: Int, y: Int) { //hack if (!dirty) { dirtyRegion = Rectangle(oreWorld.posXSafe(x - 1).toFloat(), oreWorld.posYSafe(y - 1).toFloat(), 1f, 1f) dirty = true } else { dirtyRegion.merge(oreWorld.posXSafe(x), oreWorld.posYSafe(y)) val a = 2 } } }
mit
c217cdc899452b29df5609bbd662557e
38.990099
184
0.59825
4.582829
false
false
false
false
Leanplum/Leanplum-Android-SDK
AndroidSDKCore/src/main/java/com/leanplum/actions/internal/ActionManagerDefinition.kt
1
4078
/* * Copyright 2022, Leanplum, Inc. All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.leanplum.actions.internal import com.leanplum.ActionArgs import com.leanplum.callbacks.ActionCallback import com.leanplum.internal.ActionManager import com.leanplum.internal.VarCache data class ActionDefinition( val name: String, val kind: Int, val args: ActionArgs, val options: Map<String, Any>?, var presentHandler: ActionCallback?, var dismissHandler: ActionCallback? ) { val definitionMap: MutableMap<String, Any?> init { val values: Map<String, Any> = HashMap() val kinds: Map<String, String> = HashMap() val order: MutableList<String> = ArrayList() for (arg in args.value) { VarCache.updateValues( arg.name(), VarCache.getNameComponents(arg.name()), arg.defaultValue(), arg.kind(), values, kinds ) order.add(arg.name()) } definitionMap = HashMap() definitionMap["kind"] = kind definitionMap["values"] = values definitionMap["kinds"] = kinds definitionMap["order"] = order definitionMap["options"] = options } } data class Definitions( val actionDefinitions: MutableList<ActionDefinition> = mutableListOf(), var devModeActionDefinitionsFromServer: Map<String, Any?>? = null ) { fun findDefinition(definitionName: String?): ActionDefinition? { return actionDefinitions.firstOrNull { it.name == definitionName } } } fun ActionManager.getActionDefinitionMap(actionName: String?): Map<String, Any?>? { val defMap = definitions.findDefinition(actionName)?.definitionMap return defMap } fun ActionManager.getActionDefinitionMaps(): Map<String, Any?> { val result: MutableMap<String, Map<String, Any?>> = mutableMapOf() definitions.actionDefinitions.forEach { result.put(it.name, it.definitionMap) } return result } fun ActionManager.defineAction(definition: ActionDefinition) { with (definitions.actionDefinitions) { firstOrNull { it.name == definition.name }?.also { remove(it) } add(definition) } } fun ActionManager.setDevModeActionDefinitionsFromServer(serverDefs: Map<String, Any?>?) { definitions.devModeActionDefinitionsFromServer = serverDefs } fun ActionManager.areLocalAndServerDefinitionsEqual(): Boolean { val localDefinitions = getActionDefinitionMaps() val serverDefinitions = definitions.devModeActionDefinitionsFromServer return areActionDefinitionsEqual(localDefinitions, serverDefinitions) } private fun areActionDefinitionsEqual(a: Map<String, Any?>?, b: Map<String, Any?>?): Boolean { if (a == null || b == null || a.size != b.size) { return false } for ((key, value) in a) { if (value == null || b[key] == null) { return false } val aItem = value as Map<*, *> val bItem = b[key] as Map<*, *> val aKind = aItem["kind"] val aValues = aItem["values"] val aKinds = aItem["kinds"] val aOptions = aItem["options"] if ((aKind != null && aKind != bItem["kind"]) || (aValues != null && aValues != bItem["values"]) || (aKinds != null && aKinds != bItem["kinds"]) || ((aOptions == null) != (bItem["options"] == null)) || (aOptions != null && aOptions == bItem["options"])) { return false } } return true }
apache-2.0
a6e1f4565f72d25c0dea75924c3fcd1f
31.110236
94
0.694949
4.025666
false
false
false
false
cxpqwvtj/himawari
web/src/main/kotlin/app/himawari/controller/api/v1/ApiController.kt
1
2149
package app.himawari.controller.api.v1 import app.himawari.dto.json.Api0002Request import app.himawari.dto.json.Api0002Response import app.himawari.dto.json.Api1001Response import app.himawari.model.HimawariUser import app.himawari.service.api.ApiService import org.slf4j.LoggerFactory import org.springframework.http.MediaType import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.* import java.time.LocalDate import java.time.format.DateTimeFormatter import javax.servlet.http.HttpServletRequest /** * APIリクエスト用コントローラ * Created by masahiro on 2016/10/15. */ @RestController @RequestMapping("/api/v1") class ApiController( val service: ApiService ) { private val logger = LoggerFactory.getLogger(this.javaClass) @RequestMapping(path = arrayOf("/**"), method = arrayOf(RequestMethod.GET, RequestMethod.POST)) fun root(request: HttpServletRequest) { logger.debug(request.requestURL.toString()) } @GetMapping(path = arrayOf("/timecards/{year_month}")) fun userTimecard(@AuthenticationPrincipal user: HimawariUser, @PathVariable("year_month") yearMonth: String): Api1001Response { val pattern = DateTimeFormatter.ofPattern("yyyyMMdd") val localDate = LocalDate.parse("${yearMonth}01", pattern) return service.selectMonthlyInOutData(user.username, localDate) } @GetMapping(path = arrayOf("/users/{user_id}/timecards/{year_month}")) fun adminTimecard(@PathVariable("user_id") userId: String, @PathVariable("year_month") yearMonth: String): Api1001Response { val pattern = DateTimeFormatter.ofPattern("yyyyMMdd") val localDate = LocalDate.parse("${yearMonth}01", pattern) return service.selectMonthlyInOutData(userId, localDate) } @PostMapping(path = arrayOf("/user/days"), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun createStartEnd(@AuthenticationPrincipal user: HimawariUser, @RequestBody startEndDatetimes: Api0002Request): Api0002Response { return service.createDailyStartEndHistory(user, startEndDatetimes) } }
mit
16fcb09e30aca1778c88249bc42d161e
41.52
134
0.760941
4.047619
false
false
false
false
kurtyan/fanfou4j
src/main/java/com/github/kurtyan/fanfou4j/core/FanfouClient.kt
1
1178
package com.github.kurtyan.fanfou4j.core import com.fasterxml.jackson.core.type.TypeReference import com.github.kurtyan.fanfou4j.http.SimpleHttpClient import java.io.Reader import java.lang.reflect.Type /** * Created by yanke on 2016/12/1. */ class FanfouClient(val profile: FanfouProfile) { val client = SimpleHttpClient(authenticator = profile.authenticator) private fun <T> createJsonParser(request: AbstractRequest<T>): (Reader) -> T = { JsonMapperFactory.jsonMapper().readValue(it, object : TypeReference<T>() { override fun getType(): Type { return request.getResponseType() } }) } fun <T> execute(request: AbstractRequest<T>): T { val responseParser = createJsonParser(request) return when (request.httpMethod) { HttpMethod.GET -> client.get(profile.getRequestUrl(request.action), request.getParameter(), responseParser) HttpMethod.POST -> client.post(profile.getRequestUrl(request.action), request.getParameter(), responseParser) else -> throw UnsupportedOperationException("Method=${request.httpMethod} not supported") } } }
mit
17579ddf005e3cbf154b576ecc6b64f3
34.727273
121
0.690153
4.445283
false
false
false
false
google/intellij-community
java/java-features-trainer/src/com/intellij/java/ift/lesson/essential/JavaOnboardingTourLesson.kt
2
26713
// 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.java.ift.lesson.essential import com.intellij.codeInsight.daemon.impl.analysis.HighlightingFeature import com.intellij.execution.RunManager import com.intellij.execution.ui.UIExperiment import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI import com.intellij.ide.ui.UISettings import com.intellij.ide.util.PropertiesComponent import com.intellij.ide.util.gotoByName.GotoActionModel import com.intellij.idea.ActionsBundle import com.intellij.java.ift.JavaLessonsBundle import com.intellij.java.ift.JavaProjectUtil import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.actions.ToggleCaseAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.LanguageLevelUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.SdkType import com.intellij.openapi.roots.ui.configuration.SdkDetector import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ex.MultiLineLabel import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.WindowStateService import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.FocusManagerImpl import com.intellij.toolWindow.StripeButton import com.intellij.ui.UIBundle import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.tree.TreeVisitor import com.intellij.util.PlatformUtils import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.xdebugger.XDebuggerManager import com.siyeh.InspectionGadgetsBundle import com.siyeh.IntentionPowerPackBundle import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.put import org.jetbrains.annotations.Nls import training.FeaturesTrainerIcons import training.dsl.* import training.dsl.LessonUtil.adjustSearchEverywherePosition import training.dsl.LessonUtil.checkEditorModification import training.dsl.LessonUtil.restoreIfModified import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.LessonUtil.restorePopupPosition import training.learn.LearnBundle import training.learn.LessonsBundle import training.learn.course.KLesson import training.learn.course.LessonProperties import training.learn.lesson.LessonManager import training.learn.lesson.general.run.clearBreakpoints import training.learn.lesson.general.run.toggleBreakpointTask import training.project.ProjectUtils import training.ui.LearningUiHighlightingManager import training.ui.LearningUiManager import training.ui.getFeedbackProposedPropertyName import training.util.* import java.awt.Point import java.awt.event.KeyEvent import java.util.concurrent.CompletableFuture import javax.swing.JTree import javax.swing.JWindow import javax.swing.tree.TreePath class JavaOnboardingTourLesson : KLesson("java.onboarding", JavaLessonsBundle.message("java.onboarding.lesson.name")) { private lateinit var openLearnTaskId: TaskContext.TaskId private var useDelay: Boolean = false private val demoConfigurationName: String = "Welcome" private val demoFileDirectory: String = "src" private val demoFileName: String = "$demoConfigurationName.java" private val uiSettings get() = UISettings.getInstance() override val properties = LessonProperties( canStartInDumbMode = true, openFileAtStart = false ) override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) private var backupPopupLocation: Point? = null private var hideToolStripesPreference = false private var showNavigationBarPreference = true @NlsSafe private var jdkAtStart: String = "undefined" val sample: LessonSample = parseLessonSample(""" import java.util.Arrays; import java.util.List; class Welcome { public static void main(String[] args) { int[] array = {5, 6, 7, 8}; System.out.println("AVERAGE of array " + Arrays.toString(array) + " is " + findAverage(array)); } private static double findAverage(int[] values) { double result = 0; <caret id=3/>for (int i = 0; i < values.length; i++) { result += values[i]; } <caret>return result<caret id=2/>; } } """.trimIndent()) override val lessonContent: LessonContext.() -> Unit = { prepareRuntimeTask { jdkAtStart = getCurrentJdkVersionString(project) useDelay = true invokeActionForFocusContext(getActionById("Stop")) configurations().forEach { runManager().removeConfiguration(it) } val root = ProjectUtils.getCurrentLearningProjectRoot() val srcDir = root.findChild(demoFileDirectory) ?: error("'src' directory not found.") if (srcDir.findChild(demoFileName) == null) invokeLater { runWriteAction { srcDir.createChildData(this, demoFileName) // todo: This file shows with .java extension in the Project view and this extension disappears when user open it // (because we fill the file after the user open it) Fill the file immediately in this place? } } } clearBreakpoints() checkUiSettings() projectTasks() prepareSample(sample, checkSdkConfiguration = false) openLearnToolwindow() sdkConfigurationTasks() waitIndexingTasks() runTasks() debugTasks() completionSteps() waitBeforeContinue(500) contextActions() waitBeforeContinue(500) searchEverywhereTasks() task { text(JavaLessonsBundle.message("java.onboarding.epilog", getCallBackActionId("CloseProject"), LessonUtil.returnToWelcomeScreenRemark(), LearningUiManager.addCallback { LearningUiManager.resetModulesView() })) } } override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) { prepareFeedbackData(project, lessonEndInfo) restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupPopupLocation) backupPopupLocation = null uiSettings.hideToolStripes = hideToolStripesPreference uiSettings.showNavigationBar = showNavigationBarPreference uiSettings.fireUISettingsChanged() if (!lessonEndInfo.lessonPassed) { LessonUtil.showFeedbackNotification(this, project) return } val dataContextPromise = DataManager.getInstance().dataContextFromFocusAsync invokeLater { val result = MessageDialogBuilder.yesNoCancel(JavaLessonsBundle.message("java.onboarding.finish.title"), JavaLessonsBundle.message("java.onboarding.finish.text", LessonUtil.returnToWelcomeScreenRemark())) .yesText(JavaLessonsBundle.message("java.onboarding.finish.exit")) .noText(JavaLessonsBundle.message("java.onboarding.finish.modules")) .icon(FeaturesTrainerIcons.PluginIcon) .show(project) when (result) { Messages.YES -> invokeLater { LessonManager.instance.stopLesson() val closeAction = getActionById("CloseProject") dataContextPromise.onSuccess { context -> invokeLater { val event = AnActionEvent.createFromAnAction(closeAction, null, ActionPlaces.LEARN_TOOLWINDOW, context) ActionUtil.performActionDumbAwareWithCallbacks(closeAction, event) } } } Messages.NO -> invokeLater { LearningUiManager.resetModulesView() } } if (result != Messages.YES) { LessonUtil.showFeedbackNotification(this, project) } } } private fun prepareFeedbackData(project: Project, lessonEndInfo: LessonEndInfo) { val primaryLanguage = module.primaryLanguage if (primaryLanguage == null) { thisLogger().error("Onboarding lesson has no language support for some magical reason") return } val configPropertyName = getFeedbackProposedPropertyName(primaryLanguage) if (PropertiesComponent.getInstance().getBoolean(configPropertyName, false)) { return } val jdkVersionsFuture = CompletableFuture<List<String>>() runBackgroundableTask(ProjectBundle.message("progress.title.detecting.sdks"), project, false) { indicator -> val jdkVersions = mutableListOf<String>() SdkDetector.getInstance().detectSdks(JavaSdk.getInstance(), indicator, object : SdkDetector.DetectedSdkListener { override fun onSdkDetected(type: SdkType, version: String, home: String) { jdkVersions.add(version) } override fun onSearchCompleted() { jdkVersionsFuture.complete(jdkVersions) } }) } @Suppress("HardCodedStringLiteral") val currentJdkVersion: @NlsSafe String = getCurrentJdkVersionString(project) val module = ModuleManager.getInstance(project).modules.first() @Suppress("HardCodedStringLiteral") val currentLanguageLevel: @NlsSafe String = LanguageLevelUtil.getEffectiveLanguageLevel(module).name primaryLanguage.onboardingFeedbackData = object : OnboardingFeedbackData("IDEA Onboarding Tour Feedback", lessonEndInfo) { override val feedbackReportId = "idea_onboarding_tour" override val additionalFeedbackFormatVersion: Int = 1 private val jdkVersions: List<String>? by lazy { if (jdkVersionsFuture.isDone) jdkVersionsFuture.get() else null } override val addAdditionalSystemData: JsonObjectBuilder.() -> Unit = { put("jdk_at_start", jdkAtStart) put("current_jdk", currentJdkVersion) put("language_level", currentLanguageLevel) put("found_jdk", buildJsonArray { for (version in jdkVersions ?: emptyList()) { add(JsonPrimitive(version)) } }) } override val addRowsForUserAgreement: Panel.() -> Unit = { row(JavaLessonsBundle.message("java.onboarding.feedback.system.found.jdks")) { val versions: @NlsSafe String = jdkVersions?.joinToString("\n") ?: "none" cell(MultiLineLabel(versions)) } row(JavaLessonsBundle.message("java.onboarding.feedback.system.jdk.at.start")) { label(jdkAtStart) } row(JavaLessonsBundle.message("java.onboarding.feedback.system.current.jdk")) { label(currentJdkVersion) } row(JavaLessonsBundle.message("java.onboarding.feedback.system.lang.level")) { label(currentLanguageLevel) } } override fun feedbackHasBeenProposed() { PropertiesComponent.getInstance().setValue(configPropertyName, true, false) } } } private fun getCurrentJdkVersionString(project: Project): String { return JavaProjectUtil.getEffectiveJdk(project)?.let { JavaSdk.getInstance().getVersionString(it) } ?: "none" } private fun getCallBackActionId(@Suppress("SameParameterValue") actionId: String): Int { val action = getActionById(actionId) return LearningUiManager.addCallback { invokeActionForFocusContext(action) } } private fun LessonContext.debugTasks() { clearBreakpoints() var logicalPosition = LogicalPosition(0, 0) prepareRuntimeTask { logicalPosition = editor.offsetToLogicalPosition(sample.startOffset) } caret(sample.startOffset) toggleBreakpointTask(sample, { logicalPosition }, checkLine = false) { text(JavaLessonsBundle.message("java.onboarding.balloon.click.here"), LearningBalloonConfig(Balloon.Position.below, width = 0, duplicateMessage = false)) text(JavaLessonsBundle.message("java.onboarding.toggle.breakpoint.1", code("6.5"), code("findAverage"), code("26"))) text(JavaLessonsBundle.message("java.onboarding.toggle.breakpoint.2")) } highlightButtonById("Debug", highlightInside = false, usePulsation = false) actionTask("Debug") { showBalloonOnHighlightingComponent(JavaLessonsBundle.message("java.onboarding.balloon.start.debugging")) restoreState { lineWithBreakpoints() != setOf(logicalPosition.line) } restoreIfModified(sample) JavaLessonsBundle.message("java.onboarding.start.debugging", icon(AllIcons.Actions.StartDebugger)) } highlightDebugActionsToolbar(highlightInside = false, usePulsation = false) task { rehighlightPreviousUi = true gotItStep(Balloon.Position.above, 400, JavaLessonsBundle.message("java.onboarding.balloon.about.debug.panel", strong(UIBundle.message("tool.window.name.debug")), if (UIExperiment.isNewDebuggerUIEnabled()) 0 else 1, strong(LessonsBundle.message("debug.workflow.lesson.name")))) restoreIfModified(sample) } highlightButtonById("Stop", highlightInside = false, usePulsation = false) task { val position = if (UIExperiment.isNewDebuggerUIEnabled()) Balloon.Position.above else Balloon.Position.atRight showBalloonOnHighlightingComponent(JavaLessonsBundle.message("java.onboarding.balloon.stop.debugging"), position) { list -> list.maxByOrNull { it.locationOnScreen.y } } text(JavaLessonsBundle.message("java.onboarding.stop.debugging", icon(AllIcons.Actions.Suspend))) restoreIfModified(sample) stateCheck { XDebuggerManager.getInstance(project).currentSession == null } } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } private fun LessonContext.waitIndexingTasks() { task { triggerAndBorderHighlight().component { progress: NonOpaquePanel -> progress.javaClass.name.contains("InlineProgressPanel") } } task { text(JavaLessonsBundle.message("java.onboarding.indexing.description")) text(JavaLessonsBundle.message("java.onboarding.wait.indexing"), LearningBalloonConfig(Balloon.Position.above, 0)) waitSmartModeStep() } waitBeforeContinue(300) prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } private fun LessonContext.runTasks() { highlightRunToolbar(highlightInside = false, usePulsation = false) task { triggerUI { clearPreviousHighlights = false }.component { ui: ActionButton -> ActionManager.getInstance().getId(ui.action) == "Run" } } task { val runOptionsText = if (PlatformUtils.isIdeaUltimate()) { JavaLessonsBundle.message("java.onboarding.run.options.ultimate", icon(AllIcons.Actions.Execute), icon(AllIcons.Actions.StartDebugger), icon(AllIcons.Actions.Profile), icon(AllIcons.General.RunWithCoverage)) } else { JavaLessonsBundle.message("java.onboarding.run.options.community", icon(AllIcons.Actions.Execute), icon(AllIcons.Actions.StartDebugger), icon(AllIcons.General.RunWithCoverage)) } text(JavaLessonsBundle.message("java.onboarding.temporary.configuration.description") + " $runOptionsText") text(JavaLessonsBundle.message("java.onboarding.run.sample", icon(AllIcons.Actions.Execute), action("Run"))) text(JavaLessonsBundle.message("java.onboarding.run.sample.balloon", icon(AllIcons.Actions.Execute), action("Run")), LearningBalloonConfig(Balloon.Position.below, 0)) checkToolWindowState("Run", true) restoreIfModified(sample) } } private fun LessonContext.openLearnToolwindow() { task { triggerAndBorderHighlight().component { stripe: StripeButton -> stripe.windowInfo.id == "Learn" } } task { openLearnTaskId = taskId text(JavaLessonsBundle.message("java.onboarding.balloon.open.learn.toolbar", strong(LearnBundle.message("toolwindow.stripe.Learn"))), LearningBalloonConfig(Balloon.Position.atRight, width = 0, duplicateMessage = true)) stateCheck { ToolWindowManager.getInstance(project).getToolWindow("Learn")?.isVisible == true } restoreIfModified(sample) } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() requestEditorFocus() } } private fun LessonContext.checkUiSettings() { hideToolStripesPreference = uiSettings.hideToolStripes showNavigationBarPreference = uiSettings.showNavigationBar showInvalidDebugLayoutWarning() if (!hideToolStripesPreference && (showNavigationBarPreference || uiSettings.showMainToolbar)) { // a small hack to have same tasks count. It is needed to track statistics result. task { } task { } return } task { text(JavaLessonsBundle.message("java.onboarding.change.ui.settings")) proceedLink() } prepareRuntimeTask { uiSettings.hideToolStripes = false uiSettings.showNavigationBar = true uiSettings.fireUISettingsChanged() } } private fun LessonContext.projectTasks() { prepareRuntimeTask { LessonUtil.hideStandardToolwindows(project) } task { triggerAndBorderHighlight().component { stripe: StripeButton -> stripe.windowInfo.id == "Project" } } lateinit var openProjectViewTask: TaskContext.TaskId task { openProjectViewTask = taskId var projectDirExpanded = false text(JavaLessonsBundle.message("java.onboarding.project.view.description", action("ActivateProjectToolWindow"))) text(JavaLessonsBundle.message("java.onboarding.balloon.project.view"), LearningBalloonConfig(Balloon.Position.atRight, width = 0)) triggerUI().treeItem { tree: JTree, path: TreePath -> val result = path.pathCount >= 2 && path.getPathComponent(1).isToStringContains("IdeaLearningProject") if (result) { if (!projectDirExpanded) { invokeLater { tree.expandPath(path) } } projectDirExpanded = true } result } } task { var srcDirCollapsed = false triggerAndBorderHighlight().treeItem { tree: JTree, path: TreePath -> val result = path.pathCount >= 3 && path.getPathComponent(1).isToStringContains("IdeaLearningProject") && path.getPathComponent(2).isToStringContains(demoFileDirectory) if (result) { if (!srcDirCollapsed) { invokeLater { tree.collapsePath(path) } } srcDirCollapsed = true } result } } fun isDemoFilePath(path: TreePath) = path.pathCount >= 4 && path.getPathComponent(3).isToStringContains(demoConfigurationName) task { text(JavaLessonsBundle.message("java.onboarding.balloon.source.directory", strong(demoFileDirectory)), LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0)) triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> isDemoFilePath(path) } restoreByUi(openProjectViewTask) } task { text(JavaLessonsBundle.message("java.onboarding.balloon.open.file", strong(demoFileName)), LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0)) stateCheck l@{ if (FileEditorManager.getInstance(project).selectedTextEditor == null) return@l false virtualFile.name == demoFileName } restoreState { (previous.ui as? JTree)?.takeIf { tree -> TreeUtil.visitVisibleRows(tree, TreeVisitor { path -> if (isDemoFilePath(path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }) != null }?.isShowing?.not() ?: true } } } private fun LessonContext.completionSteps() { prepareRuntimeTask { setSample(sample.insertAtPosition(2, " / values<caret>")) FocusManagerImpl.getInstance(project).requestFocusInProject(editor.contentComponent, project) } task { text(JavaLessonsBundle.message("java.onboarding.type.division", code(" / values"))) text(JavaLessonsBundle.message("java.onboarding.invoke.completion")) triggerAndBorderHighlight().listItem { // no highlighting it.isToStringContains("length") } proposeRestoreForInvalidText(".") } task { text(JavaLessonsBundle.message("java.onboarding.choose.values.item", code("length"), action("EditorChooseLookupItem"))) text(JavaLessonsBundle.message("java.onboarding.invoke.completion.tip", action("CodeCompletion"))) stateCheck { checkEditorModification(sample, modificationPositionId = 2, needChange = "/values.length") } } } private fun LessonContext.contextActions() { val quickFixMessage = InspectionGadgetsBundle.message("foreach.replace.quickfix") caret(sample.getPosition(3)) task("ShowIntentionActions") { text(JavaLessonsBundle.message("java.onboarding.invoke.intention.for.warning.1")) text(JavaLessonsBundle.message("java.onboarding.invoke.intention.for.warning.2", action(it))) triggerAndBorderHighlight().listItem { item -> item.isToStringContains(quickFixMessage) } restoreIfModifiedOrMoved() } task { text(JavaLessonsBundle.message("java.onboarding.select.fix", strong(quickFixMessage))) stateCheck { editor.document.text.contains("for (int value : values)") } restoreByUi(delayMillis = defaultRestoreDelay) } fun getIntentionMessage(project: Project): @Nls String { val module = ModuleManager.getInstance(project).modules.firstOrNull() ?: error("Not found modules in project '${project.name}'") val langLevel = LanguageLevelUtil.getEffectiveLanguageLevel(module) val messageKey = if (langLevel.isAtLeast(HighlightingFeature.TEXT_BLOCKS.level)) { "replace.concatenation.with.format.string.intention.name.formatted" } else "replace.concatenation.with.format.string.intention.name" return IntentionPowerPackBundle.message(messageKey) } caret("RAGE") task("ShowIntentionActions") { text(JavaLessonsBundle.message("java.onboarding.invoke.intention.for.code", action(it))) val intentionMessage = getIntentionMessage(project) triggerAndBorderHighlight().listItem { item -> item.isToStringContains(intentionMessage) } restoreIfModifiedOrMoved() } task { text(JavaLessonsBundle.message("java.onboarding.apply.intention", strong(getIntentionMessage(project)), LessonUtil.rawEnter())) stateCheck { val text = editor.document.text text.contains("System.out.printf") || text.contains("MessageFormat.format") } restoreByUi(delayMillis = defaultRestoreDelay) } } private fun LessonContext.searchEverywhereTasks() { val toggleCase = ActionsBundle.message("action.EditorToggleCase.text") caret("AVERAGE", select = true) task("SearchEverywhere") { text(JavaLessonsBundle.message("java.onboarding.invoke.search.everywhere.1", strong(toggleCase), code("AVERAGE"))) text(JavaLessonsBundle.message("java.onboarding.invoke.search.everywhere.2", LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT), LessonUtil.actionName(it))) triggerAndBorderHighlight().component { ui: ExtendableTextField -> UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null } restoreIfModifiedOrMoved() } task { transparentRestore = true before { if (backupPopupLocation != null) return@before val ui = previous.ui ?: return@before val popupWindow = UIUtil.getParentOfType(JWindow::class.java, ui) ?: return@before val oldPopupLocation = WindowStateService.getInstance(project).getLocation(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY) if (adjustSearchEverywherePosition(popupWindow, "of array ") || LessonUtil.adjustPopupPosition(project, popupWindow)) { backupPopupLocation = oldPopupLocation } } text(JavaLessonsBundle.message("java.onboarding.search.everywhere.description", strong("AVERAGE"), strong(JavaLessonsBundle.message("toggle.case.part")))) triggerAndBorderHighlight().listItem { item -> val value = (item as? GotoActionModel.MatchedValue)?.value (value as? GotoActionModel.ActionWrapper)?.action is ToggleCaseAction } restoreByUi() restoreIfModifiedOrMoved() } task { text(JavaLessonsBundle.message("java.onboarding.apply.action", strong(toggleCase), LessonUtil.rawEnter())) stateCheck { editor.document.text.contains("\"average") } restoreByUi(delayMillis = defaultRestoreDelay) } text(JavaLessonsBundle.message("java.onboarding.case.changed")) } private fun TaskRuntimeContext.runManager() = RunManager.getInstance(project) private fun TaskRuntimeContext.configurations() = runManager().allSettings.filter { it.name.contains(demoConfigurationName) } }
apache-2.0
6ccd2107b9cd9d7d7b1efb564432209f
38.752976
139
0.701494
5.136128
false
false
false
false
google/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/GroovyMacroRegistryServiceImpl.kt
3
5520
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.dgm import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.openapi.Disposable import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.* import com.intellij.util.castSafelyTo import com.intellij.util.containers.addIfNotNull import com.intellij.workspaceModel.ide.WorkspaceModelTopics import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrTuple import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames import org.jetbrains.plugins.groovy.transformations.macro.GroovyMacroRegistryService import java.util.concurrent.ConcurrentHashMap class GroovyMacroRegistryServiceImpl(val project: Project) : GroovyMacroRegistryService, Disposable { private val availableModules: MutableMap<Module, CachedValue<Set<SmartPsiElementPointer<PsiMethod>>>> = ConcurrentHashMap() init { val connection = project.messageBus.connect() val listener = GroovyMacroModuleListener() WorkspaceModelTopics.getInstance(project).subscribeImmediately(connection, listener) } override fun resolveAsMacro(call: GrMethodCall): PsiMethod? { val module = ModuleUtilCore.findModuleForPsiElement(call) ?: return null val invokedName = call.invokedExpression.castSafelyTo<GrReferenceExpression>()?.referenceName ?: return null val candidates = getModuleRegistry(module).filter { it.element?.name == invokedName } return candidates.find { it.element?.canBeAppliedTo(call) == true }?.element } override fun getAllKnownMacros(context: PsiElement): List<PsiMethod> { val module = ModuleUtilCore.findModuleForPsiElement(context) ?: return emptyList() return getModuleRegistry(module).mapNotNull { it.element } } fun refreshModule(module: Module) { availableModules.remove(module) } private fun getModuleRegistry(module: Module) : Set<SmartPsiElementPointer<PsiMethod>> { return availableModules.computeIfAbsent(module) { val moduleRegistry: CachedValue<Set<SmartPsiElementPointer<PsiMethod>>> = CachedValuesManager.getManager(module.project).createCachedValue { val scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) val extensionFiles = FileTypeIndex.getFiles(DGMFileType, scope) if (extensionFiles.isEmpty()) { return@createCachedValue CachedValueProvider.Result(emptySet(), PsiModificationTracker.MODIFICATION_COUNT) } val macroRegistry = mutableSetOf<PsiMethod>() val extensionClassFiles = mutableListOf<VirtualFile>() for (extensionVirtualFile in extensionFiles) { val psi = PsiUtilBase.getPsiFile(module.project, extensionVirtualFile) val inst = psi.castSafelyTo<PropertiesFile>()?.findPropertyByKey("extensionClasses") val extensionClassName = inst?.value ?: continue val extensionClass = JavaPsiFacade.getInstance(module.project).findClass(extensionClassName, scope) ?: continue extensionClassFiles.addIfNotNull(extensionClass.containingFile.virtualFile) val macroMethods = extensionClass.methods.filter { it.hasAnnotation(GroovyCommonClassNames.ORG_CODEHAUS_GROOVY_MACRO_RUNTIME_MACRO) && it.parameterList.parameters[0].typeElement != null && it.parameterList.parameters[0].type.equalsToText("org.codehaus.groovy.macro.runtime.MacroContext") } macroRegistry.addAll(macroMethods) } CachedValueProvider.Result(macroRegistry.mapTo(HashSet()) { SmartPointerManager.createPointer(it) }, *extensionFiles.toTypedArray(), *extensionClassFiles.toTypedArray()) } moduleRegistry }.value } override fun dispose() { availableModules.clear() } } private fun PsiMethod.canBeAppliedTo(call: GrMethodCall): Boolean { val methodParameters = parameterList.parameters.drop(1) for ((argument, parameter) in (call.expressionArguments + call.closureArguments).zip(methodParameters)) { val type = parameter.typeElement?.type ?: return false when { type.equalsToText("org.codehaus.groovy.ast.expr.ClosureExpression") && argument !is GrClosableBlock -> return false type.equalsToText("org.codehaus.groovy.ast.expr.ListExpression") && argument.castSafelyTo<GrListOrMap>()?.isMap != false -> return false type.equalsToText("org.codehaus.groovy.ast.expr.MapExpression") && argument.castSafelyTo<GrListOrMap>()?.isMap != true -> return false type.equalsToText("org.codehaus.groovy.ast.expr.TupleExpression") && argument !is GrTuple -> return false type.equalsToText("org.codehaus.groovy.ast.expr.MethodCallExpression") && argument !is GrMethodCallExpression -> return false } } return true }
apache-2.0
2d32053d2de3dd02fda9c46f5721e2d2
53.663366
177
0.775725
4.842105
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/KeyHandler.kt
1
1186
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Method2 import org.runestar.client.updater.mapper.mark import java.awt.event.KeyListener class KeyHandler : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.interfaces.contains(KeyListener::class.type) } @MethodParameters("keyEvent") class keyPressed : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.mark == KeyListener::keyPressed.mark } } @MethodParameters("keyEvent") class keyReleased : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.mark == KeyListener::keyReleased.mark } } @MethodParameters("keyEvent") class keyTyped : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.mark == KeyListener::keyTyped.mark } } }
mit
195ebe827a01fbb0fdfeef5a8675a9df
39.931034
100
0.764755
4.425373
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/RemapIDsVisitor.kt
7
3922
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.visitors import com.intellij.diagnostic.hprof.classstore.HProfMetadata import com.intellij.diagnostic.hprof.parser.* import com.intellij.diagnostic.hprof.util.FileBackedHashMap import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.util.function.LongUnaryOperator internal abstract class RemapIDsVisitor : HProfVisitor() { private var currentID = 0 override fun preVisit() { disableAll() enable(HeapDumpRecordType.ClassDump) enable(HeapDumpRecordType.InstanceDump) enable(HeapDumpRecordType.PrimitiveArrayDump) enable(HeapDumpRecordType.ObjectArrayDump) currentID = 1 } override fun visitPrimitiveArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type, primitiveArrayData: ByteBuffer) { addMapping(arrayObjectId, currentID++) } override fun visitClassDump(classId: Long, stackTraceSerialNumber: Long, superClassId: Long, classloaderClassId: Long, instanceSize: Long, constants: Array<ConstantPoolEntry>, staticFields: Array<StaticFieldEntry>, instanceFields: Array<InstanceFieldEntry>) { addMapping(classId, currentID++) } override fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) { addMapping(arrayObjectId, currentID++) } override fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) { addMapping(objectId, currentID++) } abstract fun addMapping(oldId: Long, newId: Int) abstract fun getRemappingFunction(): LongUnaryOperator companion object { fun createMemoryBased(): RemapIDsVisitor { val map = Long2IntOpenHashMap() map.put(0, 0) return object : RemapIDsVisitor() { override fun addMapping(oldId: Long, newId: Int) { map.put(oldId, newId) } override fun getRemappingFunction(): LongUnaryOperator { return LongUnaryOperator { map.get(it).toLong() } } } } fun createFileBased(channel: FileChannel, maxInstanceCount: Long): RemapIDsVisitor { val remapIDsMap = FileBackedHashMap.createEmpty( channel, maxInstanceCount, KEY_SIZE, VALUE_SIZE) return object : RemapIDsVisitor() { override fun addMapping(oldId: Long, newId: Int) { remapIDsMap.put(oldId).putInt(newId) } override fun getRemappingFunction(): LongUnaryOperator { return LongUnaryOperator { operand -> if (operand == 0L) 0L else { if (remapIDsMap.containsKey(operand)) remapIDsMap[operand]!!.int.toLong() else throw HProfMetadata.RemapException() } } } } } fun isSupported(instanceCount: Long): Boolean { return FileBackedHashMap.isSupported(instanceCount, KEY_SIZE, VALUE_SIZE) } private const val KEY_SIZE = 8 private const val VALUE_SIZE = 4 } }
apache-2.0
7e65851e9b055886727539c1bab72b10
34.342342
166
0.674911
4.731001
false
false
false
false
nicolaiparlog/energy-model
src/main/kotlin/org/codefx/demo/bingen/math/Fibonacci.kt
4
286
package org.codefx.demo.bingen.math fun fib(n: Int): Int { // return 0 for negative n's if (n <= 0) return 0 if (n == 1) return 1 var a = 0 var b = 1 for (i in 2..n) { val new = a + b a = b b = new } return b }
cc0-1.0
5edacfd34db5cda9398b3ee258a64f25
14.052632
35
0.433566
3.042553
false
false
false
false
square/okhttp
samples/guide/src/main/java/okhttp3/recipes/kt/CancelCall.kt
7
1931
/* * Copyright (C) 2014 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.recipes.kt import java.io.IOException import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import okhttp3.OkHttpClient import okhttp3.Request class CancelCall { private val executor = Executors.newScheduledThreadPool(1) private val client = OkHttpClient() fun run() { val request = Request.Builder() .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build() val startNanos = System.nanoTime() val call = client.newCall(request) // Schedule a job to cancel the call in 1 second. executor.schedule({ System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f) call.cancel() System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f) }, 1, TimeUnit.SECONDS) System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f) try { call.execute().use { response -> System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response) } } catch (e: IOException) { System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e) } } } fun main() { CancelCall().run() }
apache-2.0
e66bd9ae4b5d21bc7a553a8543ede90e
32.293103
90
0.675298
3.778865
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/connector/impl/SeasonConnectorImpl.kt
1
4148
package com.github.vhromada.catalog.web.connector.impl import com.github.vhromada.catalog.common.entity.Page import com.github.vhromada.catalog.common.filter.PagingFilter import com.github.vhromada.catalog.web.connector.SeasonConnector import com.github.vhromada.catalog.web.connector.common.ConnectorConfig import com.github.vhromada.catalog.web.connector.common.RestConnector import com.github.vhromada.catalog.web.connector.common.RestLoggingInterceptor import com.github.vhromada.catalog.web.connector.common.RestRequest import com.github.vhromada.catalog.web.connector.common.UserInterceptor import com.github.vhromada.catalog.web.connector.common.error.ResponseErrorHandler import com.github.vhromada.catalog.web.connector.entity.ChangeSeasonRequest import com.github.vhromada.catalog.web.connector.entity.Season import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpMethod import org.springframework.stereotype.Component import org.springframework.web.util.UriComponentsBuilder /** * A class represents implementation of connector for seasons. * * @author Vladimir Hromada */ @Component("seasonConnector") class SeasonConnectorImpl( /** * Configuration for connector */ connectorConfig: ConnectorConfig, /** * Error handler */ errorHandler: ResponseErrorHandler, /** * Interceptor for logging */ loggingInterceptor: RestLoggingInterceptor, /** * Interceptor for processing header X-User */ userInterceptor: UserInterceptor ) : RestConnector( system = "CatalogWebSpring", config = connectorConfig, errorHandler = errorHandler, loggingInterceptor = loggingInterceptor, userInterceptor = userInterceptor ), SeasonConnector { override fun search(show: String, filter: PagingFilter): Page<Season> { val url = UriComponentsBuilder.fromUriString(getUrl(show = show)) filter.createUrl(builder = url) return exchange(request = RestRequest(method = HttpMethod.GET, url = url.build().toUriString(), parameterizedType = object : ParameterizedTypeReference<Page<Season>>() {})) .throwExceptionIfAny() .get() } override fun get(show: String, uuid: String): Season { return exchange(request = RestRequest(method = HttpMethod.GET, url = getUrl(show = show, uuid = uuid), responseType = Season::class.java)) .throwExceptionIfAny() .get() } override fun add(show: String, request: ChangeSeasonRequest): Season { return exchange(request = RestRequest(method = HttpMethod.PUT, url = getUrl(show = show), entity = request, responseType = Season::class.java)) .throwExceptionIfAny() .get() } override fun update(show: String, uuid: String, request: ChangeSeasonRequest): Season { return exchange(request = RestRequest(method = HttpMethod.POST, url = getUrl(show = show, uuid = uuid), entity = request, responseType = Season::class.java)) .throwExceptionIfAny() .get() } override fun remove(show: String, uuid: String) { exchange(request = RestRequest(method = HttpMethod.DELETE, url = getUrl(show = show, uuid = uuid), responseType = Unit::class.java)) .throwExceptionIfAny() } override fun duplicate(show: String, uuid: String): Season { return exchange(request = RestRequest(method = HttpMethod.POST, url = "${getUrl(show = show, uuid = uuid)}/duplicate", responseType = Season::class.java)) .throwExceptionIfAny() .get() } /** * Returns URL for show's UUID. * * @param show show's UUID * @return URL for show's UUID */ private fun getUrl(show: String): String { return "${getUrl()}/rest/shows/${show}/seasons" } /** * Returns URL for show's UUID and season's UUID. * * @param show show's UUID * @param uuid season's UUID * @return URL for show's UUID and season's UUID */ private fun getUrl(show: String, uuid: String): String { return "${getUrl(show = show)}/${uuid}" } }
mit
8f0aec2fbfa227cd29246cba58b15fac
37.407407
180
0.695998
4.528384
false
true
false
false
JetBrains/intellij-community
plugins/settings-repository/src/upstreamEditor.kt
1
4519
// 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.settingsRepository import com.intellij.diagnostic.dumpCoroutines import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ModalTaskOwner import com.intellij.openapi.progress.runBlockingModal import com.intellij.openapi.project.Project import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.ui.components.DialogManager import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.text.nullize import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.jetbrains.annotations.VisibleForTesting import org.jetbrains.settingsRepository.actions.NOTIFICATION_GROUP import java.awt.Component import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JTextField @NlsContexts.DialogMessage internal fun validateUrl(url: String?, project: Project?): String? { return if (url == null) IcsBundle.message("dialog.error.message.url.empty") else icsManager.repositoryService.checkUrl(url, project) } internal fun createMergeActions(project: Project?, urlTextField: TextFieldWithBrowseButton, dialogManager: DialogManager): List<Action> { var syncTypes = SyncType.values() if (SystemInfo.isMac) { syncTypes = syncTypes.reversedArray() } // TextFieldWithBrowseButton not painted correctly if specified as validation info component, so, use textField directly return syncTypes.map { SyncAction(it, urlTextField.textField, project, dialogManager) } } private class SyncAction(private val syncType: SyncType, private val urlTextField: JTextField, private val project: Project?, private val dialogManager: DialogManager) : AbstractAction(icsMessage(syncType.messageKey)) { override fun actionPerformed(event: ActionEvent) { dialogManager.performAction { val owner = project?.let(ModalTaskOwner::project) ?: (event.source as? Component)?.let(ModalTaskOwner::component) ?: ModalTaskOwner.guess() val url = urlTextField.text.nullize(true) val error = validateUrl(url, project) ?: doSync(icsManager = icsManager, project = project, syncType = syncType, url = url!!, owner = owner) error?.let { listOf(ValidationInfo(error, urlTextField)) } } } } @RequiresEdt @VisibleForTesting fun doSync(icsManager: IcsManager, project: Project?, syncType: SyncType, url: String, owner: ModalTaskOwner): String? { IcsActionsLogger.logSettingsSync(project, syncType) val isRepositoryWillBeCreated = !icsManager.repositoryManager.isRepositoryExists() var upstreamSet = false try { val repositoryManager = icsManager.repositoryManager repositoryManager.createRepositoryIfNeeded() repositoryManager.setUpstream(url, null) icsManager.isRepositoryActive = repositoryManager.isRepositoryExists() upstreamSet = true if (isRepositoryWillBeCreated) { icsManager.setApplicationLevelStreamProvider() } @Suppress("DialogTitleCapitalization") runBlockingModal(owner, icsMessage("task.sync.title")) { if (isRepositoryWillBeCreated && syncType != SyncType.OVERWRITE_LOCAL) { com.intellij.configurationStore.saveSettings(componentManager = ApplicationManager.getApplication(), forceSavingAllSettings = false) icsManager.sync(syncType = syncType, project = project) { copyLocalConfig() } } else { icsManager.sync(syncType = syncType, project = project, localRepositoryInitializer = null) } } } catch (e: Throwable) { if (isRepositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } LOG.warn(e) if (!upstreamSet || e is NoRemoteRepositoryException) { return e.message?.let { icsMessage("set.upstream.failed.message", it) } ?: icsMessage("set.upstream.failed.message.without.details") } else { return e.message ?: IcsBundle.message("sync.internal.error") } } NOTIFICATION_GROUP.createNotification(icsMessage("sync.done.message"), NotificationType.INFORMATION).notify(project) return null }
apache-2.0
065b774d207b3bbc73bb300a660f2061
41.242991
140
0.75437
4.833155
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/index/model/AemComponentDefinition.kt
1
4637
package com.aemtools.index.model import com.aemtools.common.constant.const.JCR_DESCRIPTION import com.aemtools.common.constant.const.JCR_TITLE import com.aemtools.common.constant.const.SLING_RESOURCE_SUPER_TYPE import com.aemtools.common.constant.const.aem_component_declaration.COMPONENT_GROUP import com.aemtools.common.constant.const.aem_component_declaration.CQ_ICON import com.aemtools.common.constant.const.aem_component_declaration.IS_CONTAINER import com.aemtools.common.util.toStringBuilder import com.aemtools.common.util.normalizeToJcrRoot import com.aemtools.lang.htl.icons.HtlIcons import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.xml.XmlTag import org.apache.commons.lang.BooleanUtils import java.io.Serializable /** * Represents content of AEM component descriptor * (`.content.xml`). * * @author Dmytro Troynikov */ data class AemComponentDefinition( /** * Represents the `jcr:title` attribute. */ val title: String?, /** * Represents the `jcr:description` attribute. */ val description: String?, /** * Full path of current component on file system. */ val fullPath: String, /** * Represents the `sling:resourceSuperType` attribute. */ val resourceSuperType: String?, /** * Represents the `componentGroup` attribute. */ val componentGroup: String?, /** * Represents the `cq:isContainer` attribute. * * Default: *false* */ val isContainer: Boolean = false, /** * Represents the `cq:icon` attribute. */ val cqIcon: String? = null ) : Serializable { /** * Resource type of current component. * * @see [normalizeToJcrRoot] * @return resource type */ fun resourceType(): String = fullPath.normalizeToJcrRoot().substringBeforeLast("/") /** * Get component name. * * `/apps/components/mycomponent/.content.xml -> mycomponent` * * @return component's name */ fun componentName(): String = fullPath .substringBeforeLast("/") .substringAfterLast("/") companion object { @JvmStatic val serialVersionUID: Long = 1L /** * Extract [AemComponentDefinition] from given [XmlTag]. * * Note: if component doesn't have `jcr:title` or `componentGroup` *null* will be returned. * * @param tag the tag * @param fullPath path to component * @return aem component definition */ fun fromTag(tag: XmlTag, fullPath: String): AemComponentDefinition? { val title = tag.getAttributeValue(JCR_TITLE) ?: return null val group = tag.getAttributeValue(COMPONENT_GROUP) ?: return null return AemComponentDefinition( title = title, description = tag.getAttributeValue(JCR_DESCRIPTION), fullPath = fullPath, resourceSuperType = tag.getAttributeValue(SLING_RESOURCE_SUPER_TYPE), componentGroup = group, isContainer = BooleanUtils.toBoolean( tag.getAttributeValue(IS_CONTAINER) ), cqIcon = tag.getAttributeValue(CQ_ICON) ) } /** * Convert current [AemComponentDefinition] to [LookupElement]. * * @receiver [AemComponentDefinition] * @return lookup element */ fun AemComponentDefinition.toLookupElement(): LookupElement = LookupElementBuilder.create(resourceType()) .withTypeText("AEM Component") .withPresentableText(title ?: componentName()) .withIcon(HtlIcons.AEM_COMPONENT) .let { if (title != null) { it.withTailText("(${componentName()})", true) } else { it } } /** * Create IDEA doc compliable string from current [AemComponentDefinition]. * * @receiver [AemComponentDefinition] * @return documentation string */ fun AemComponentDefinition.generateDoc(): String { val result = """AEM Component:<br/>""".toStringBuilder() with(result) { append("<b>Name</b>: ${componentName()}<br/>") append("<b>Group</b>: $componentGroup<br/>") title?.let { append("<b>jcr:title</b>: $it<br/>") } description?.let { append("<b>jcr:description</b>: $it<br/>") } resourceSuperType?.let { append("<b>sling:resourceSuperType</b>: $it<br/>") } append("<b>Container</b>: $isContainer<br/>") cqIcon?.let { append("<b>cq:icon</b>: $it") } } return result.toString() } } }
gpl-3.0
289667b2c82443b397e9dc12c5cb0434
27.98125
95
0.636834
4.399431
false
false
false
false
JuliusKunze/kotlin-native
runtime/src/main/kotlin/kotlin/Lazy.kt
2
8865
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin import kotlin.reflect.KProperty /** * Represents a value with lazy initialization. * * To create an instance of [Lazy] use the [lazy] function. */ public interface Lazy<out T> { /** * Gets the lazily initialized value of the current Lazy instance. * Once the value was initialized it must not change during the rest of lifetime of this Lazy instance. */ public val value: T /** * Returns `true` if a value for this Lazy instance has been already initialized, and `false` otherwise. * Once this function has returned `true` it stays `true` for the rest of lifetime of this Lazy instance. */ public fun isInitialized(): Boolean } /** * Creates a new instance of the [Lazy] that is already initialized with the specified [value]. */ public fun <T> lazyOf(value: T): Lazy<T> = InitializedLazyImpl(value) /** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on * the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future. */ @FixmeConcurrency public fun <T> lazy(initializer: () -> T): Lazy<T> = UnsafeLazyImpl(initializer)//SynchronizedLazyImpl(initializer) /** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and thread-safety [mode]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that when the [LazyThreadSafetyMode.SYNCHRONIZED] mode is specified the returned instance uses itself * to synchronize on. Do not synchronize from external code on the returned instance as it may cause accidental deadlock. * Also this behavior can be changed in the future. */ @FixmeConcurrency public fun <T> lazy(mode: LazyThreadSafetyMode, initializer: () -> T): Lazy<T> = when (mode) { LazyThreadSafetyMode.SYNCHRONIZED -> TODO()//SynchronizedLazyImpl(initializer) LazyThreadSafetyMode.PUBLICATION -> TODO()//SafePublicationLazyImpl(initializer) LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer) } /** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * The returned instance uses the specified [lock] object to synchronize on. * When the [lock] is not specified the instance uses itself to synchronize on, * in this case do not synchronize from external code on the returned instance as it may cause accidental deadlock. * Also this behavior can be changed in the future. */ @FixmeConcurrency @Suppress("UNUSED_PARAMETER") public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> = TODO()//SynchronizedLazyImpl(initializer, lock) /** * An extension to delegate a read-only property of type [T] to an instance of [Lazy]. * * This extension allows to use instances of Lazy for property delegation: * `val property: String by lazy { initializer }` */ @kotlin.internal.InlineOnly public inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value /** * Specifies how a [Lazy] instance synchronizes access among multiple threads. */ public enum class LazyThreadSafetyMode { /** * Locks are used to ensure that only a single thread can initialize the [Lazy] instance. */ SYNCHRONIZED, /** * Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value, * but only first returned value will be used as the value of [Lazy] instance. */ PUBLICATION, /** * No locks are used to synchronize the access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined. * * This mode should be used only when high performance is crucial and the [Lazy] instance is guaranteed never to be initialized from more than one thread. */ NONE, } private object UNINITIALIZED_VALUE //private class SynchronizedLazyImpl<out T>(initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable { // private var initializer: (() -> T)? = initializer // @Volatile private var _value: Any? = UNINITIALIZED_VALUE // // final field is required to enable safe publication of constructed instance // private val lock = lock ?: this // // override val value: T // get() { // val _v1 = _value // if (_v1 !== UNINITIALIZED_VALUE) { // @Suppress("UNCHECKED_CAST") // return _v1 as T // } // // return synchronized(lock) { // val _v2 = _value // if (_v2 !== UNINITIALIZED_VALUE) { // @Suppress("UNCHECKED_CAST") (_v2 as T) // } // else { // val typedValue = initializer!!() // _value = typedValue // initializer = null // typedValue // } // } // } // // override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE // // override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." // // private fun writeReplace(): Any = InitializedLazyImpl(value) //} internal class UnsafeLazyImpl<out T>(initializer: () -> T) : Lazy<T>/*, Serializable*/ { private var initializer: (() -> T)? = initializer private var _value: Any? = UNINITIALIZED_VALUE override val value: T get() { if (_value === UNINITIALIZED_VALUE) { _value = initializer!!() initializer = null } @Suppress("UNCHECKED_CAST") return _value as T } override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." private fun writeReplace(): Any = InitializedLazyImpl(value) } private class InitializedLazyImpl<out T>(override val value: T) : Lazy<T>/*, Serializable*/ { override fun isInitialized(): Boolean = true override fun toString(): String = value.toString() } //private class SafePublicationLazyImpl<out T>(initializer: () -> T) : Lazy<T>, Serializable { // private var initializer: (() -> T)? = initializer // @Volatile private var _value: Any? = UNINITIALIZED_VALUE // // this final field is required to enable safe publication of constructed instance // private val final: Any = UNINITIALIZED_VALUE // // override val value: T // get() { // if (_value === UNINITIALIZED_VALUE) { // val initializerValue = initializer // // if we see null in initializer here, it means that the value is already set by another thread // if (initializerValue != null) { // val newValue = initializerValue() // if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) { // initializer = null // } // } // } // @Suppress("UNCHECKED_CAST") // return _value as T // } // // override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE // // override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." // // private fun writeReplace(): Any = InitializedLazyImpl(value) // // companion object { // private val valueUpdater = java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater( // SafePublicationLazyImpl::class.java, // Any::class.java, // "_value") // } //}
apache-2.0
5a14e450341676e20d5dc4dad997bbf6
38.757848
158
0.657755
4.441383
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reified/approximateCapturedTypes.kt
2
683
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // Basically this test checks that no captured type used as argument for signature mapping class SwOperator<T>: Operator<List<T>, T> interface Operator<R, T> open class Inv<T> class Obs<Y> { inline fun <reified X> lift(lift: Operator<out X, in Y>) = object : Inv<X>() {} } fun box(): String { val o: Obs<CharSequence> = Obs() val inv = o.lift(SwOperator()) val signature = inv.javaClass.genericSuperclass.toString() if (signature != "Inv<java.util.List<? extends java.lang.CharSequence>>") return "fail 1: $signature" return "OK" }
apache-2.0
0f7ff227896ba91415e883df7433c4d1
26.32
105
0.685212
3.467005
false
false
false
false
AndroidX/androidx
wear/watchface/watchface-complications-data/src/main/java/android/support/wearable/complications/ComplicationData.kt
3
96526
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ComplicationExperimental::class) package android.support.wearable.complications import android.annotation.SuppressLint import android.app.PendingIntent import android.content.ComponentName import android.graphics.drawable.Icon import android.os.BadParcelableException import android.os.Build import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.util.Log import androidx.annotation.ColorInt import androidx.annotation.IntDef import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.wear.watchface.complications.data.ComplicationDisplayPolicies import androidx.wear.watchface.complications.data.ComplicationDisplayPolicy import androidx.wear.watchface.complications.data.ComplicationExperimental import androidx.wear.watchface.complications.data.ComplicationPersistencePolicies import androidx.wear.watchface.complications.data.ComplicationPersistencePolicy import androidx.wear.watchface.complications.data.FloatExpression import androidx.wear.watchface.complications.data.toFloatExpression import java.io.IOException import java.io.InvalidObjectException import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.Serializable /** * Container for complication data of all types. * * A [androidx.wear.watchface.complications.ComplicationProviderService] should create * instances of * this class using [ComplicationData.Builder] and send them to the complication system in * response to * [androidx.wear.watchface.complications.ComplicationProviderService.onComplicationRequest]. * Depending on the type of complication data, some fields will be required and some will be * optional - see the documentation for each type, and for the builder's set methods, for details. * * A watch face will receive instances of this class as long as providers are configured. * * When rendering the complication data for a given time, the watch face should first call * [isActiveAt] to determine whether the data is valid at that time. See the documentation for each * of the complication types below for details of which fields are expected to be displayed. * * @hide */ @SuppressLint("BanParcelableUsage") @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class ComplicationData : Parcelable, Serializable { /** @hide */ @IntDef( TYPE_EMPTY, TYPE_NOT_CONFIGURED, TYPE_SHORT_TEXT, TYPE_LONG_TEXT, TYPE_RANGED_VALUE, TYPE_ICON, TYPE_SMALL_IMAGE, TYPE_LARGE_IMAGE, TYPE_NO_PERMISSION, TYPE_NO_DATA, TYPE_GOAL_PROGRESS, TYPE_WEIGHTED_ELEMENTS, EXP_TYPE_PROTO_LAYOUT, EXP_TYPE_LIST ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Retention(AnnotationRetention.SOURCE) annotation class ComplicationType /** @hide */ @IntDef(IMAGE_STYLE_PHOTO, IMAGE_STYLE_ICON) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Retention(AnnotationRetention.SOURCE) annotation class ImageStyle /** Returns the type of this complication data. */ @ComplicationType val type: Int private val fields: Bundle internal constructor(builder: Builder) { type = builder.type fields = builder.fields } internal constructor(type: Int, fields: Bundle) { this.type = type this.fields = fields this.fields.classLoader = javaClass.classLoader } internal constructor(input: Parcel) { type = input.readInt() fields = input.readBundle(javaClass.classLoader) ?: run { Log.w(TAG, "ComplicationData parcel input has null bundle.") Bundle() } } @RequiresApi(api = Build.VERSION_CODES.P) private class SerializedForm @JvmOverloads constructor( private var complicationData: ComplicationData? = null ) : Serializable { @Throws(IOException::class) private fun writeObject(oos: ObjectOutputStream) { // Get a copy because it could technically change to null in another thread. val complicationData = this.complicationData!! oos.writeInt(VERSION_NUMBER) val type = complicationData.type oos.writeInt(type) oos.writeInt(complicationData.persistencePolicy) oos.writeInt(complicationData.displayPolicy) if (isFieldValidForType(FIELD_LONG_TEXT, type)) { oos.writeObject(complicationData.longText) } if (isFieldValidForType(FIELD_LONG_TITLE, type)) { oos.writeObject(complicationData.longTitle) } if (isFieldValidForType(FIELD_SHORT_TEXT, type)) { oos.writeObject(complicationData.shortText) } if (isFieldValidForType(FIELD_SHORT_TITLE, type)) { oos.writeObject(complicationData.shortTitle) } if (isFieldValidForType(FIELD_CONTENT_DESCRIPTION, type)) { oos.writeObject(complicationData.contentDescription) } if (isFieldValidForType(FIELD_ICON, type)) { oos.writeObject(IconSerializableHelper.create(complicationData.icon)) } if (isFieldValidForType(FIELD_ICON_BURN_IN_PROTECTION, type)) { oos.writeObject( IconSerializableHelper.create(complicationData.burnInProtectionIcon) ) } if (isFieldValidForType(FIELD_SMALL_IMAGE, type)) { oos.writeObject(IconSerializableHelper.create(complicationData.smallImage)) } if (isFieldValidForType(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, type)) { oos.writeObject( IconSerializableHelper.create( complicationData.burnInProtectionSmallImage ) ) } if (isFieldValidForType(FIELD_IMAGE_STYLE, type)) { oos.writeInt(complicationData.smallImageStyle) } if (isFieldValidForType(FIELD_LARGE_IMAGE, type)) { oos.writeObject(IconSerializableHelper.create(complicationData.largeImage)) } if (isFieldValidForType(FIELD_VALUE, type)) { oos.writeFloat(complicationData.rangedValue) } if (isFieldValidForType(FIELD_VALUE_EXPRESSION, type)) { oos.writeNullable(complicationData.rangedValueExpression) { oos.writeByteArray(it.asByteArray()) } } if (isFieldValidForType(FIELD_VALUE_TYPE, type)) { oos.writeInt(complicationData.rangedValueType) } if (isFieldValidForType(FIELD_MIN_VALUE, type)) { oos.writeFloat(complicationData.rangedMinValue) } if (isFieldValidForType(FIELD_MAX_VALUE, type)) { oos.writeFloat(complicationData.rangedMaxValue) } if (isFieldValidForType(FIELD_TARGET_VALUE, type)) { oos.writeFloat(complicationData.targetValue) } if (isFieldValidForType(FIELD_COLOR_RAMP, type)) { oos.writeNullable(complicationData.colorRamp, oos::writeIntArray) } if (isFieldValidForType(FIELD_COLOR_RAMP_INTERPOLATED, type)) { oos.writeNullable(complicationData.isColorRampInterpolated, oos::writeBoolean) } if (isFieldValidForType(FIELD_ELEMENT_WEIGHTS, type)) { oos.writeNullable(complicationData.elementWeights, oos::writeFloatArray) } if (isFieldValidForType(FIELD_ELEMENT_COLORS, type)) { oos.writeNullable(complicationData.elementColors, oos::writeIntArray) } if (isFieldValidForType(FIELD_ELEMENT_BACKGROUND_COLOR, type)) { oos.writeInt(complicationData.elementBackgroundColor) } if (isFieldValidForType(FIELD_START_TIME, type)) { oos.writeLong(complicationData.startDateTimeMillis) } if (isFieldValidForType(FIELD_END_TIME, type)) { oos.writeLong(complicationData.endDateTimeMillis) } oos.writeInt(complicationData.fields.getInt(EXP_FIELD_LIST_ENTRY_TYPE)) if (isFieldValidForType(EXP_FIELD_LIST_STYLE_HINT, type)) { oos.writeInt(complicationData.listStyleHint) } if (isFieldValidForType(EXP_FIELD_PROTO_LAYOUT_INTERACTIVE, type)) { oos.writeByteArray(complicationData.interactiveLayout ?: byteArrayOf()) } if (isFieldValidForType(EXP_FIELD_PROTO_LAYOUT_AMBIENT, type)) { oos.writeByteArray(complicationData.ambientLayout ?: byteArrayOf()) } if (isFieldValidForType(EXP_FIELD_PROTO_LAYOUT_RESOURCES, type)) { oos.writeByteArray(complicationData.layoutResources ?: byteArrayOf()) } if (isFieldValidForType(FIELD_DATA_SOURCE, type)) { val componentName = complicationData.dataSource if (componentName == null) { oos.writeUTF("") } else { oos.writeUTF(componentName.flattenToString()) } } // TapAction unfortunately can't be serialized, instead we record if we've lost it. oos.writeBoolean( complicationData.hasTapAction() || complicationData.tapActionLostDueToSerialization ) val start = complicationData.fields.getLong(FIELD_TIMELINE_START_TIME, -1) oos.writeLong(start) val end = complicationData.fields.getLong(FIELD_TIMELINE_END_TIME, -1) oos.writeLong(end) oos.writeInt(complicationData.fields.getInt(FIELD_TIMELINE_ENTRY_TYPE)) oos.writeList(complicationData.listEntries ?: listOf()) { SerializedForm(it).writeObject(oos) } if (isFieldValidForType(FIELD_PLACEHOLDER_FIELDS, type)) { oos.writeNullable(complicationData.placeholder) { SerializedForm(it).writeObject(oos) } } // This has to be last, since it's recursive. oos.writeList(complicationData.timelineEntries ?: listOf()) { SerializedForm(it).writeObject(oos) } } @Throws(IOException::class, ClassNotFoundException::class) private fun readObject(ois: ObjectInputStream) { val versionNumber = ois.readInt() if (versionNumber != VERSION_NUMBER) { // Give up if there's a version skew. throw IOException("Unsupported serialization version number $versionNumber") } val type = ois.readInt() val fields = Bundle() fields.putInt(FIELD_PERSISTENCE_POLICY, ois.readInt()) fields.putInt(FIELD_DISPLAY_POLICY, ois.readInt()) if (isFieldValidForType(FIELD_LONG_TEXT, type)) { putIfNotNull(fields, FIELD_LONG_TEXT, ois.readObject() as ComplicationText?) } if (isFieldValidForType(FIELD_LONG_TITLE, type)) { putIfNotNull(fields, FIELD_LONG_TITLE, ois.readObject() as ComplicationText?) } if (isFieldValidForType(FIELD_SHORT_TEXT, type)) { putIfNotNull(fields, FIELD_SHORT_TEXT, ois.readObject() as ComplicationText?) } if (isFieldValidForType(FIELD_SHORT_TITLE, type)) { putIfNotNull(fields, FIELD_SHORT_TITLE, ois.readObject() as ComplicationText?) } if (isFieldValidForType(FIELD_CONTENT_DESCRIPTION, type)) { putIfNotNull( fields, FIELD_CONTENT_DESCRIPTION, ois.readObject() as ComplicationText? ) } if (isFieldValidForType(FIELD_ICON, type)) { putIfNotNull(fields, FIELD_ICON, IconSerializableHelper.read(ois)) } if (isFieldValidForType(FIELD_ICON_BURN_IN_PROTECTION, type)) { putIfNotNull( fields, FIELD_ICON_BURN_IN_PROTECTION, IconSerializableHelper.read(ois) ) } if (isFieldValidForType(FIELD_SMALL_IMAGE, type)) { putIfNotNull(fields, FIELD_SMALL_IMAGE, IconSerializableHelper.read(ois)) } if (isFieldValidForType(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, type)) { putIfNotNull( fields, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, IconSerializableHelper.read(ois) ) } if (isFieldValidForType(FIELD_IMAGE_STYLE, type)) { fields.putInt(FIELD_IMAGE_STYLE, ois.readInt()) } if (isFieldValidForType(FIELD_LARGE_IMAGE, type)) { fields.putParcelable(FIELD_LARGE_IMAGE, IconSerializableHelper.read(ois)) } if (isFieldValidForType(FIELD_VALUE, type)) { fields.putFloat(FIELD_VALUE, ois.readFloat()) } if (isFieldValidForType(FIELD_VALUE_EXPRESSION, type)) { ois.readNullable { ois.readByteArray() }?.let { fields.putByteArray(FIELD_VALUE_EXPRESSION, it) } } if (isFieldValidForType(FIELD_VALUE_TYPE, type)) { fields.putInt(FIELD_VALUE_TYPE, ois.readInt()) } if (isFieldValidForType(FIELD_MIN_VALUE, type)) { fields.putFloat(FIELD_MIN_VALUE, ois.readFloat()) } if (isFieldValidForType(FIELD_MAX_VALUE, type)) { fields.putFloat(FIELD_MAX_VALUE, ois.readFloat()) } if (isFieldValidForType(FIELD_TARGET_VALUE, type)) { fields.putFloat(FIELD_TARGET_VALUE, ois.readFloat()) } if (isFieldValidForType(FIELD_COLOR_RAMP, type)) { ois.readNullable { ois.readIntArray() }?.let { fields.putIntArray(FIELD_COLOR_RAMP, it) } } if (isFieldValidForType(FIELD_COLOR_RAMP_INTERPOLATED, type)) { ois.readNullable { ois.readBoolean() }?.let { fields.putBoolean(FIELD_COLOR_RAMP_INTERPOLATED, it) } } if (isFieldValidForType(FIELD_ELEMENT_WEIGHTS, type)) { ois.readNullable { ois.readFloatArray() }?.let { fields.putFloatArray(FIELD_ELEMENT_WEIGHTS, it) } } if (isFieldValidForType(FIELD_ELEMENT_COLORS, type)) { ois.readNullable { ois.readIntArray() }?.let { fields.putIntArray(FIELD_ELEMENT_COLORS, it) } } if (isFieldValidForType(FIELD_ELEMENT_BACKGROUND_COLOR, type)) { fields.putInt(FIELD_ELEMENT_BACKGROUND_COLOR, ois.readInt()) } if (isFieldValidForType(FIELD_START_TIME, type)) { fields.putLong(FIELD_START_TIME, ois.readLong()) } if (isFieldValidForType(FIELD_END_TIME, type)) { fields.putLong(FIELD_END_TIME, ois.readLong()) } val listEntryType = ois.readInt() if (listEntryType != 0) { fields.putInt(EXP_FIELD_LIST_ENTRY_TYPE, listEntryType) } if (isFieldValidForType(EXP_FIELD_LIST_STYLE_HINT, type)) { fields.putInt(EXP_FIELD_LIST_STYLE_HINT, ois.readInt()) } if (isFieldValidForType(EXP_FIELD_PROTO_LAYOUT_INTERACTIVE, type)) { val length = ois.readInt() if (length > 0) { val protoLayout = ByteArray(length) ois.readFully(protoLayout) fields.putByteArray(EXP_FIELD_PROTO_LAYOUT_INTERACTIVE, protoLayout) } } if (isFieldValidForType(EXP_FIELD_PROTO_LAYOUT_AMBIENT, type)) { val length = ois.readInt() if (length > 0) { val ambientProtoLayout = ByteArray(length) ois.readFully(ambientProtoLayout) fields.putByteArray(EXP_FIELD_PROTO_LAYOUT_AMBIENT, ambientProtoLayout) } } if (isFieldValidForType(EXP_FIELD_PROTO_LAYOUT_RESOURCES, type)) { val length = ois.readInt() if (length > 0) { val protoLayoutResources = ByteArray(length) ois.readFully(protoLayoutResources) fields.putByteArray(EXP_FIELD_PROTO_LAYOUT_RESOURCES, protoLayoutResources) } } if (isFieldValidForType(FIELD_DATA_SOURCE, type)) { val componentName = ois.readUTF() if (componentName.isEmpty()) { fields.remove(FIELD_DATA_SOURCE) } else { fields.putParcelable( FIELD_DATA_SOURCE, ComponentName.unflattenFromString(componentName) ) } } if (ois.readBoolean()) { fields.putBoolean(FIELD_TAP_ACTION_LOST, true) } val start = ois.readLong() if (start != -1L) { fields.putLong(FIELD_TIMELINE_START_TIME, start) } val end = ois.readLong() if (end != -1L) { fields.putLong(FIELD_TIMELINE_END_TIME, end) } val timelineEntryType = ois.readInt() if (timelineEntryType != 0) { fields.putInt(FIELD_TIMELINE_ENTRY_TYPE, timelineEntryType) } ois.readList { SerializedForm().apply { readObject(ois) } } .map { it.complicationData!!.fields } .takeIf { it.isNotEmpty() } ?.let { fields.putParcelableArray(EXP_FIELD_LIST_ENTRIES, it.toTypedArray()) } if (isFieldValidForType(FIELD_PLACEHOLDER_FIELDS, type)) { ois.readNullable { SerializedForm().apply { readObject(ois) } }?.let { fields.putInt(FIELD_PLACEHOLDER_TYPE, it.complicationData!!.type) fields.putBundle(FIELD_PLACEHOLDER_FIELDS, it.complicationData!!.fields) } } ois.readList { SerializedForm().apply { readObject(ois) } } .map { it.complicationData!!.fields } .takeIf { it.isNotEmpty() } ?.let { fields.putParcelableArray(FIELD_TIMELINE_ENTRIES, it.toTypedArray()) } complicationData = ComplicationData(type, fields) } fun readResolve(): Any = complicationData!! companion object { private const val VERSION_NUMBER = 20 internal fun putIfNotNull(fields: Bundle, field: String, value: Parcelable?) { if (value != null) { fields.putParcelable(field, value) } } } } @RequiresApi(api = Build.VERSION_CODES.P) fun writeReplace(): Any = SerializedForm(this) @Throws(InvalidObjectException::class) private fun readObject(@Suppress("UNUSED_PARAMETER") stream: ObjectInputStream) { throw InvalidObjectException("Use SerializedForm") } override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(type) dest.writeBundle(fields) } /** * Returns true if the complication is active and should be displayed at the given time. If this * returns false, the complication should not be displayed. * * This must be checked for any time for which the complication will be displayed. */ fun isActiveAt(dateTimeMillis: Long) = (dateTimeMillis >= fields.getLong(FIELD_START_TIME, 0) && dateTimeMillis <= fields.getLong(FIELD_END_TIME, Long.MAX_VALUE)) /** * TapAction unfortunately can't be serialized. Returns true if tapAction has been lost due to * serialization (e.g. due to being read from the local cache). The next complication update * from the system would replace this with one with a tapAction. */ val tapActionLostDueToSerialization: Boolean get() = fields.getBoolean(FIELD_TAP_ACTION_LOST) /** * For timeline entries. The epoch second at which this timeline entry becomes * valid or `null` * if it's not set. */ var timelineStartEpochSecond: Long? get() { val expiresAt = fields.getLong(FIELD_TIMELINE_START_TIME, -1) return if (expiresAt == -1L) { null } else { expiresAt } } set(epochSecond) { if (epochSecond == null) { fields.remove(FIELD_TIMELINE_START_TIME) } else { fields.putLong(FIELD_TIMELINE_START_TIME, epochSecond) } } /** * For timeline entries. The epoch second at which this timeline entry becomes invalid or `null` * if it's not set. */ var timelineEndEpochSecond: Long? get() { val expiresAt = fields.getLong(FIELD_TIMELINE_END_TIME, -1) return if (expiresAt == -1L) { null } else { expiresAt } } set(epochSecond) { if (epochSecond == null) { fields.remove(FIELD_TIMELINE_END_TIME) } else { fields.putLong(FIELD_TIMELINE_END_TIME, epochSecond) } } /** The list of [ComplicationData] timeline entries. */ val timelineEntries: List<ComplicationData>? @Suppress("DEPRECATION") get() = fields.getParcelableArray(FIELD_TIMELINE_ENTRIES) ?.map { parcelable -> val bundle = parcelable as Bundle bundle.classLoader = javaClass.classLoader // Use the serialized FIELD_TIMELINE_ENTRY_TYPE or the outer type if it's not there. // Usually the timeline entry type will be the same as the outer type, unless an // entry contains NoDataComplicationData. val type = bundle.getInt(FIELD_TIMELINE_ENTRY_TYPE, type) ComplicationData(type, parcelable) } /** Sets the list of [ComplicationData] timeline entries. */ fun setTimelineEntryCollection(timelineEntries: Collection<ComplicationData>?) { if (timelineEntries == null) { fields.remove(FIELD_TIMELINE_ENTRIES) } else { fields.putParcelableArray( FIELD_TIMELINE_ENTRIES, timelineEntries.map { // This supports timeline entry of NoDataComplicationData. it.fields.putInt(FIELD_TIMELINE_ENTRY_TYPE, it.type) it.fields }.toTypedArray() ) } } /** The list of [ComplicationData] entries for a ListComplicationData. */ val listEntries: List<ComplicationData>? @Suppress("deprecation") get() = fields.getParcelableArray(EXP_FIELD_LIST_ENTRIES) ?.map { parcelable -> val bundle = parcelable as Bundle bundle.classLoader = javaClass.classLoader ComplicationData(bundle.getInt(EXP_FIELD_LIST_ENTRY_TYPE), bundle) } /** * The [ComponentName] of the ComplicationDataSourceService that provided this ComplicationData. */ var dataSource: ComponentName? // The safer alternative is not available on Wear OS yet. get() = getParcelableField(FIELD_DATA_SOURCE) set(provider) { fields.putParcelable(FIELD_DATA_SOURCE, provider) } /** * Returns true if the ComplicationData contains a ranged value. I.e. if [rangedValue] can * succeed. */ fun hasRangedValue(): Boolean = isFieldValidForType(FIELD_VALUE, type) /** * Returns the *value* field for this complication. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE] and * [TYPE_GOAL_PROGRESS], otherwise returns zero. */ val rangedValue: Float get() { checkFieldValidForTypeWithoutThrowingException(FIELD_VALUE, type) return fields.getFloat(FIELD_VALUE) } /** * Returns true if the ComplicationData contains a ranged value expression. I.e. if * [rangedValueExpression] can succeed. */ fun hasRangedValueExpression(): Boolean = isFieldValidForType(FIELD_VALUE_EXPRESSION, type) /** * Returns the *valueExpression* field for this complication. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE] and * [TYPE_GOAL_PROGRESS]. */ val rangedValueExpression: FloatExpression? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_VALUE_EXPRESSION, type) return fields.getByteArray(FIELD_VALUE_EXPRESSION)?.toFloatExpression() } /** * Returns true if the ComplicationData contains a ranged max type. I.e. if [rangedValueType] * can succeed. */ fun hasRangedValueType(): Boolean = isFieldValidForType(FIELD_VALUE_TYPE, type) /** * Returns the *value* field for this complication. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE], otherwise returns * zero. */ val rangedValueType: Int get() { checkFieldValidForTypeWithoutThrowingException(FIELD_VALUE_TYPE, type) return fields.getInt(FIELD_VALUE_TYPE) } /** * Returns true if the ComplicationData contains a ranged max value. I.e. if [rangedMinValue] * can succeed. */ fun hasRangedMinValue(): Boolean = isFieldValidForType(FIELD_MIN_VALUE, type) /** * Returns the *min value* field for this complication. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE], otherwise returns * zero. */ val rangedMinValue: Float get() { checkFieldValidForTypeWithoutThrowingException(FIELD_MIN_VALUE, type) return fields.getFloat(FIELD_MIN_VALUE) } /** * Returns true if the ComplicationData contains a ranged max value. I.e. if [rangedMaxValue] * can succeed. */ fun hasRangedMaxValue(): Boolean = isFieldValidForType(FIELD_MAX_VALUE, type) /** * Returns the *max value* field for this complication. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE], otherwise returns * zero. */ val rangedMaxValue: Float get() { checkFieldValidForTypeWithoutThrowingException(FIELD_MAX_VALUE, type) return fields.getFloat(FIELD_MAX_VALUE) } /** * Returns true if the ComplicationData contains a ranged max value. I.e. if [targetValue] can * succeed. */ fun hasTargetValue(): Boolean = isFieldValidForType(FIELD_TARGET_VALUE, type) /** * Returns the *value* field for this complication. * * Valid only if the type of this complication data is [TYPE_GOAL_PROGRESS], otherwise returns * zero. */ val targetValue: Float get() { checkFieldValidForTypeWithoutThrowingException(FIELD_TARGET_VALUE, type) return fields.getFloat(FIELD_TARGET_VALUE) } /** * Returns the colors for the progress bar. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE] or * [TYPE_GOAL_PROGRESS]. */ @get:ColorInt val colorRamp: IntArray? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_COLOR_RAMP, type) return if (fields.containsKey(FIELD_COLOR_RAMP)) { fields.getIntArray(FIELD_COLOR_RAMP) } else { null } } /** * Returns either a boolean where: true means the color ramp colors should be smoothly * interpolated; false means the color ramp should be rendered in equal sized blocks of * solid color; null means this value wasn't set, i.e. the complication is not of type * [TYPE_RANGED_VALUE] or [TYPE_GOAL_PROGRESS]. * * Valid only if the type of this complication data is [TYPE_RANGED_VALUE] or * [TYPE_GOAL_PROGRESS]. */ val isColorRampInterpolated: Boolean? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_COLOR_RAMP_INTERPOLATED, type) return if (fields.containsKey(FIELD_COLOR_RAMP_INTERPOLATED)) { fields.getBoolean(FIELD_COLOR_RAMP_INTERPOLATED) } else { null } } /** * Returns true if the ComplicationData contains a short title. I.e. if [shortTitle] * can succeed. */ fun hasShortTitle(): Boolean = isFieldValidForType(FIELD_SHORT_TITLE, type) && hasParcelableField(FIELD_SHORT_TITLE) /** * Returns the *short title* field for this complication, or `null` if no value was * provided for the field. * * The value is provided as a [ComplicationText] object, from which the text to display * can be obtained for a given point in time. * * The length of the text, including any time-dependent values at any valid time, is expected * to not exceed seven characters. When using this text, the watch face should be able to * display any string of up to seven characters (reducing the text size appropriately if the * string is very wide). Although not expected, it is possible that strings of more than seven * characters might be seen, in which case they may be truncated. * * Valid only if the type of this complication data is [TYPE_SHORT_TEXT], [TYPE_RANGED_VALUE], * or [TYPE_NO_PERMISSION], otherwise returns null. */ val shortTitle: ComplicationText? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_SHORT_TITLE, type) return getParcelableFieldOrWarn<ComplicationText>(FIELD_SHORT_TITLE) } /** * Returns true if the ComplicationData contains short text. I.e. if [shortText] can succeed. */ fun hasShortText(): Boolean = isFieldValidForType(FIELD_SHORT_TEXT, type) && hasParcelableField(FIELD_SHORT_TEXT) /** * Returns the *short text* field for this complication, or `null` if no value was * provided for the field. * * The value is provided as a [ComplicationText] object, from which the text to display * can be obtained for a given point in time. * * The length of the text, including any time-dependent values at any valid time, is expected * to not exceed seven characters. When using this text, the watch face should be able to * display any string of up to seven characters (reducing the text size appropriately if the * string is very wide). Although not expected, it is possible that strings of more than seven * characters might be seen, in which case they may be truncated. * * Valid only if the type of this complication data is [TYPE_SHORT_TEXT], [TYPE_RANGED_VALUE], * or [TYPE_NO_PERMISSION], otherwise returns null. */ val shortText: ComplicationText? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_SHORT_TEXT, type) return getParcelableFieldOrWarn<ComplicationText>(FIELD_SHORT_TEXT) } /** * Returns true if the ComplicationData contains a long title. I.e. if [longTitle] * can succeed. */ fun hasLongTitle(): Boolean = isFieldValidForType(FIELD_LONG_TITLE, type) && hasParcelableField(FIELD_LONG_TITLE) /** * Returns the *long title* field for this complication, or `null` if no value was * provided for the field. * * The value is provided as a [ComplicationText] object, from which the text to display * can be obtained for a given point in time. * * Valid only if the type of this complication data is [TYPE_LONG_TEXT], otherwise returns null. */ val longTitle: ComplicationText? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_LONG_TITLE, type) return getParcelableFieldOrWarn<ComplicationText>(FIELD_LONG_TITLE) } /** * Returns true if the ComplicationData contains long text. I.e. if [longText] can * succeed. */ fun hasLongText(): Boolean = isFieldValidForType(FIELD_LONG_TEXT, type) && hasParcelableField(FIELD_LONG_TEXT) /** * Returns the *long text* field for this complication. * * The value is provided as a [ComplicationText] object, from which the text to display * can be obtained for a given point in time. * * Valid only if the type of this complication data is [TYPE_LONG_TEXT], otherwise returns null. */ val longText: ComplicationText? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_LONG_TEXT, type) return getParcelableFieldOrWarn<ComplicationText>(FIELD_LONG_TEXT) } /** Returns true if the ComplicationData contains an Icon. I.e. if [icon] can succeed. */ fun hasIcon(): Boolean = isFieldValidForType(FIELD_ICON, type) && hasParcelableField(FIELD_ICON) /** * Returns the *icon* field for this complication, or `null` if no value was provided * for the field. The image returned is expected to be single-color and so may be tinted to * whatever color the watch face requires (but note that * [android.graphics.drawable.Drawable.mutate] should be called before drawables are tinted). * * If the device is in ambient mode, and utilises burn-in protection, then the result of * [burnInProtectionIcon] must be used instead of this. * * Valid for the types [TYPE_SHORT_TEXT], [TYPE_LONG_TEXT], [TYPE_RANGED_VALUE], [TYPE_ICON], or * [TYPE_NO_PERMISSION], otherwise returns null. */ val icon: Icon? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_ICON, type) return getParcelableFieldOrWarn<Icon>(FIELD_ICON) } /** * Returns true if the ComplicationData contains a burn in protection Icon. I.e. if * [burnInProtectionIcon] can succeed. */ fun hasBurnInProtectionIcon(): Boolean = isFieldValidForType(FIELD_ICON_BURN_IN_PROTECTION, type) && hasParcelableField(FIELD_ICON_BURN_IN_PROTECTION) /** * Returns the burn-in protection version of the *icon* field for this complication, or * `null` if no such icon was provided. The image returned is expected to be an outline * image suitable for use in ambient mode on screens with burn-in protection. The image is also * expected to be single-color and so may be tinted to whatever color the watch face requires * (but note that [android.graphics.drawable.Drawable.mutate] should be called before drawables * are tinted, and that the color used should be suitable for ambient mode with burn-in * protection). * * If the device is in ambient mode, and utilises burn-in protection, then the result of this * method must be used instead of the result of [icon]. * * Valid for the types [TYPE_SHORT_TEXT], [TYPE_LONG_TEXT], [TYPE_RANGED_VALUE], [TYPE_ICON], or * [TYPE_NO_PERMISSION], otherwise returns null. */ val burnInProtectionIcon: Icon? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_ICON_BURN_IN_PROTECTION, type) return getParcelableFieldOrWarn<Icon>(FIELD_ICON_BURN_IN_PROTECTION) } /** * Returns true if the ComplicationData contains a small image. I.e. if [smallImage] * can succeed. */ fun hasSmallImage(): Boolean = isFieldValidForType(FIELD_SMALL_IMAGE, type) && hasParcelableField(FIELD_SMALL_IMAGE) /** * Returns the *small image* field for this complication, or `null` if no value was * provided for the field. * * This may be either a [IMAGE_STYLE_PHOTO] image, which is expected to * fill the space available, or an [IMAGE_STYLE_ICON] image, which should be * drawn entirely within the space available. Use [smallImageStyle] to determine which * of these applies. * * As this may be any image, it is unlikely to be suitable for display in ambient mode when * burn-in protection is enabled, or in low-bit ambient mode, and should not be rendered under * these circumstances. * * Valid for the types [TYPE_LONG_TEXT] and [TYPE_SMALL_IMAGE]. * Otherwise returns null. */ val smallImage: Icon? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_SMALL_IMAGE, type) return getParcelableFieldOrWarn<Icon>(FIELD_SMALL_IMAGE) } /** * Returns true if the ComplicationData contains a burn in protection small image. I.e. if * [burnInProtectionSmallImage] can succeed. * * @throws IllegalStateException for invalid types */ fun hasBurnInProtectionSmallImage(): Boolean = isFieldValidForType(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, type) && hasParcelableField(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION) /** * Returns the burn-in protection version of the *small image* field for this complication, * or `null` if no such icon was provided. The image returned is expected to be an outline * image suitable for use in ambient mode on screens with burn-in protection. The image is also * expected to be single-color and so may be tinted to whatever color the watch face requires * (but note that [android.graphics.drawable.Drawable.mutate] should be called before drawables * are tinted, and that the color used should be suitable for ambient mode with burn-in * protection). * * If the device is in ambient mode, and utilises burn-in protection, then the result of this * method must be used instead of the result of [smallImage]. * * Valid for the types [TYPE_LONG_TEXT] and [TYPE_SMALL_IMAGE]. * Otherwise returns null. */ val burnInProtectionSmallImage: Icon? get() { checkFieldValidForTypeWithoutThrowingException( FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, type ) return getParcelableFieldOrWarn<Icon>(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION) } /** * Returns the *small image style* field for this complication. * * The result of this method should be taken in to account when drawing a small image * complication. * * Valid only for types that contain small images, i.e. [TYPE_SMALL_IMAGE] and [TYPE_LONG_TEXT]. * Otherwise returns zero. * * @see IMAGE_STYLE_PHOTO which can be cropped but not recolored. * @see IMAGE_STYLE_ICON which can be recolored but not cropped. */ @ImageStyle val smallImageStyle: Int get() { checkFieldValidForTypeWithoutThrowingException(FIELD_IMAGE_STYLE, type) return fields.getInt(FIELD_IMAGE_STYLE) } /** * Returns true if the ComplicationData contains a large image. I.e. if [largeImage] * can succeed. */ fun hasLargeImage(): Boolean = isFieldValidForType(FIELD_LARGE_IMAGE, type) && hasParcelableField(FIELD_LARGE_IMAGE) /** * Returns the *large image* field for this complication. This image is expected to be of a * suitable size to fill the screen of the watch. * * As this may be any image, it is unlikely to be suitable for display in ambient mode when * burn-in protection is enabled, or in low-bit ambient mode, and should not be rendered under * these circumstances. * * Valid only if the type of this complication data is [TYPE_LARGE_IMAGE]. * Otherwise returns null. */ val largeImage: Icon? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_LARGE_IMAGE, type) return getParcelableFieldOrWarn<Icon>(FIELD_LARGE_IMAGE) } /** * Returns true if the ComplicationData contains a tap action. I.e. if [tapAction] * can succeed. */ fun hasTapAction(): Boolean = isFieldValidForType(FIELD_TAP_ACTION, type) && hasParcelableField(FIELD_TAP_ACTION) /** * Returns the *tap action* field for this complication. The result is a [PendingIntent] that * should be fired if the complication is tapped on, assuming the complication is tappable, or * `null` if no tap action has been specified. * * Valid for all non-empty types, otherwise returns null. */ val tapAction: PendingIntent? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_TAP_ACTION, type) return getParcelableFieldOrWarn<PendingIntent>(FIELD_TAP_ACTION) } /** * Returns true if the ComplicationData contains a content description. I.e. if * [contentDescription] can succeed. */ fun hasContentDescription(): Boolean = isFieldValidForType(FIELD_CONTENT_DESCRIPTION, type) && hasParcelableField(FIELD_CONTENT_DESCRIPTION) /** * Returns the *content description * field for this complication, for screen readers. This * usually describes the image, but may also describe the overall complication. * * Valid for all non-empty types. */ val contentDescription: ComplicationText? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_CONTENT_DESCRIPTION, type) return getParcelableFieldOrWarn<ComplicationText>(FIELD_CONTENT_DESCRIPTION) } /** * Returns the element weights for this complication. * * Valid only if the type of this complication data is [TYPE_WEIGHTED_ELEMENTS]. * Otherwise returns null. */ val elementWeights: FloatArray? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_ELEMENT_WEIGHTS, type) return fields.getFloatArray(FIELD_ELEMENT_WEIGHTS) } /** * Returns the element colors for this complication. * * Valid only if the type of this complication data is [TYPE_WEIGHTED_ELEMENTS]. * Otherwise returns null. */ val elementColors: IntArray? get() { checkFieldValidForTypeWithoutThrowingException(FIELD_ELEMENT_COLORS, type) return fields.getIntArray(FIELD_ELEMENT_COLORS) } /** * Returns the background color to use between elements for this complication. * * Valid only if the type of this complication data is [TYPE_WEIGHTED_ELEMENTS]. * Otherwise returns 0. */ @get:ColorInt val elementBackgroundColor: Int get() { checkFieldValidForTypeWithoutThrowingException(FIELD_ELEMENT_BACKGROUND_COLOR, type) return fields.getInt(FIELD_ELEMENT_BACKGROUND_COLOR) } /** Returns the placeholder ComplicationData if there is one or `null`. */ val placeholder: ComplicationData? get() { checkFieldValidForType(FIELD_PLACEHOLDER_FIELDS, type) checkFieldValidForType(FIELD_PLACEHOLDER_TYPE, type) return if ( !fields.containsKey(FIELD_PLACEHOLDER_FIELDS) || !fields.containsKey(FIELD_PLACEHOLDER_TYPE) ) { null } else { ComplicationData( fields.getInt(FIELD_PLACEHOLDER_TYPE), fields.getBundle(FIELD_PLACEHOLDER_FIELDS)!! ) } } /** Returns the bytes of the proto layout. */ val interactiveLayout: ByteArray? get() = fields.getByteArray(EXP_FIELD_PROTO_LAYOUT_INTERACTIVE) /** * Returns the list style hint. * * Valid only if the type of this complication data is [EXP_TYPE_LIST]. Otherwise * returns zero. */ val listStyleHint: Int get() { checkFieldValidForType(EXP_FIELD_LIST_STYLE_HINT, type) return fields.getInt(EXP_FIELD_LIST_STYLE_HINT) } /** Returns the bytes of the ambient proto layout. */ val ambientLayout: ByteArray? get() = fields.getByteArray(EXP_FIELD_PROTO_LAYOUT_AMBIENT) /** Returns the bytes of the proto layout resources. */ val layoutResources: ByteArray? get() = fields.getByteArray(EXP_FIELD_PROTO_LAYOUT_RESOURCES) /** Return's the complication's [ComplicationPersistencePolicies]. */ @ComplicationPersistencePolicy val persistencePolicy: Int get() { checkFieldValidForTypeWithoutThrowingException(FIELD_PERSISTENCE_POLICY, type) return fields.getInt( FIELD_PERSISTENCE_POLICY, ComplicationPersistencePolicies.CACHING_ALLOWED ) } /** Return's the complication's [ComplicationDisplayPolicy]. */ @ComplicationDisplayPolicy val displayPolicy: Int get() { checkFieldValidForTypeWithoutThrowingException(FIELD_DISPLAY_POLICY, type) return fields.getInt(FIELD_DISPLAY_POLICY, ComplicationDisplayPolicies.ALWAYS_DISPLAY) } /** * Returns the start time for this complication data (i.e. the first time at which it should * be considered active and displayed), this may be 0. See also [isActiveAt]. */ val startDateTimeMillis: Long get() = fields.getLong(FIELD_START_TIME, 0) /** * Returns the end time for this complication data (i.e. the last time at which it should be * considered active and displayed), this may be [Long.MAX_VALUE]. See also [isActiveAt]. */ val endDateTimeMillis: Long get() = fields.getLong(FIELD_END_TIME, Long.MAX_VALUE) /** * Returns true if the complication data contains at least one text field with a value that may * change based on the current time. */ val isTimeDependent: Boolean get() = isTimeDependentField(FIELD_SHORT_TEXT) || isTimeDependentField(FIELD_SHORT_TITLE) || isTimeDependentField(FIELD_LONG_TEXT) || isTimeDependentField(FIELD_LONG_TITLE) private fun isTimeDependentField(field: String): Boolean { val text = getParcelableFieldOrWarn<ComplicationText>(field) return text != null && text.isTimeDependent } private fun <T : Parcelable?> getParcelableField(field: String): T? = try { @Suppress("deprecation") fields.getParcelable<T>(field) } catch (e: BadParcelableException) { null } private fun hasParcelableField(field: String) = getParcelableField<Parcelable>(field) != null private fun <T : Parcelable?> getParcelableFieldOrWarn(field: String): T? = try { @Suppress("deprecation") fields.getParcelable<T>(field) } catch (e: BadParcelableException) { Log.w( TAG, "Could not unparcel ComplicationData. Provider apps must exclude wearable " + "support complication classes from proguard.", e ) null } override fun toString() = if (shouldRedact()) { "ComplicationData{mType=$type, mFields=REDACTED}" } else { toStringNoRedaction() } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) fun toStringNoRedaction() = "ComplicationData{mType=$type, mFields=$fields}" /** Builder class for [ComplicationData]. */ class Builder { @ComplicationType internal val type: Int internal val fields: Bundle /** Creates a builder from given [ComplicationData], copying its type and data. */ constructor(data: ComplicationData) { type = data.type fields = data.fields.clone() as Bundle } constructor(@ComplicationType type: Int) { this.type = type fields = Bundle() if (type == TYPE_SMALL_IMAGE || type == TYPE_LONG_TEXT) { setSmallImageStyle(IMAGE_STYLE_PHOTO) } } /** Sets the complication's [ComplicationPersistencePolicy]. */ fun setPersistencePolicy(@ComplicationPersistencePolicy cachePolicy: Int) = apply { fields.putInt(FIELD_PERSISTENCE_POLICY, cachePolicy) } /** Sets the complication's [ComplicationDisplayPolicy]. */ fun setDisplayPolicy(@ComplicationDisplayPolicy displayPolicy: Int) = apply { fields.putInt(FIELD_DISPLAY_POLICY, displayPolicy) } /** * Sets the start time for this complication data. This is optional for any type. * * The complication data will be considered inactive (i.e. should not be displayed) if * the current time is less than the start time. If not specified, the data is considered * active for all time up to the end time (or always active if end time is also not * specified). * * Returns this Builder to allow chaining. */ fun setStartDateTimeMillis(startDateTimeMillis: Long) = apply { fields.putLong(FIELD_START_TIME, startDateTimeMillis) } /** * Removes the start time for this complication data. * * Returns this Builder to allow chaining. */ fun clearStartDateTime() = apply { fields.remove(FIELD_START_TIME) } /** * Sets the end time for this complication data. This is optional for any type. * * The complication data will be considered inactive (i.e. should not be displayed) if * the current time is greater than the end time. If not specified, the data is considered * active for all time after the start time (or always active if start time is also not * specified). * * Returns this Builder to allow chaining. */ fun setEndDateTimeMillis(endDateTimeMillis: Long) = apply { fields.putLong(FIELD_END_TIME, endDateTimeMillis) } /** * Removes the end time for this complication data. * * Returns this Builder to allow chaining. */ fun clearEndDateTime() = apply { fields.remove(FIELD_END_TIME) } /** * Sets the *value* field. This is required for the [TYPE_RANGED_VALUE] type, * and the [TYPE_GOAL_PROGRESS] type. For [TYPE_RANGED_VALUE] value must * be in the range [min .. max] for [TYPE_GOAL_PROGRESS] value must be >= and may * be greater than target value. * * Both the [TYPE_RANGED_VALUE] complication and the * [TYPE_GOAL_PROGRESS] complication visually present a single value, which is * usually a percentage. E.g. you have completed 70% of today's target of 10000 steps. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setRangedValue(value: Float?) = apply { putOrRemoveField(FIELD_VALUE, value) } /** * Sets the *valueExpression* field. It is evaluated to a value with the same limitations as * [setRangedValue]. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setRangedValueExpression(value: FloatExpression?) = apply { putOrRemoveField(FIELD_VALUE_EXPRESSION, value?.asByteArray()) } /** * Sets the *value type* field which provides meta data about the value. This is * optional for the [TYPE_RANGED_VALUE] type. */ fun setRangedValueType(valueType: Int) = apply { putIntField(FIELD_VALUE_TYPE, valueType) } /** * Sets the *min value* field. This is required for the [TYPE_RANGED_VALUE] * type, and is not valid for any other type. A [TYPE_RANGED_VALUE] complication * visually presents a single value, which is usually a percentage. E.g. you have * completed 70% of today's target of 10000 steps. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setRangedMinValue(minValue: Float) = apply { putFloatField(FIELD_MIN_VALUE, minValue) } /** * Sets the *max value* field. This is required for the [TYPE_RANGED_VALUE] * type, and is not valid for any other type. A [TYPE_RANGED_VALUE] complication * visually presents a single value, which is usually a percentage. E.g. you have * completed 70% of today's target of 10000 steps. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setRangedMaxValue(maxValue: Float) = apply { putFloatField(FIELD_MAX_VALUE, maxValue) } /** * Sets the *targetValue* field. This is required for the * [TYPE_GOAL_PROGRESS] type, and is not valid for any other type. A * [TYPE_GOAL_PROGRESS] complication visually presents a single value, which * is usually a percentage. E.g. you have completed 70% of today's target of 10000 steps. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setTargetValue(targetValue: Float) = apply { putFloatField(FIELD_TARGET_VALUE, targetValue) } /** * Sets the *long title* field. This is optional for the [TYPE_LONG_TEXT] type, * and is not valid for any other type. * * The value must be provided as a [ComplicationText] object, so that * time-dependent values may be included. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setLongTitle(longTitle: ComplicationText?) = apply { putOrRemoveField(FIELD_LONG_TITLE, longTitle) } /** * Sets the *long text* field. This is required for the [TYPE_LONG_TEXT] type, * and is not valid for any other type. * * The value must be provided as a [ComplicationText] object, so that * time-dependent values may be included. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setLongText(longText: ComplicationText?) = apply { putOrRemoveField(FIELD_LONG_TEXT, longText) } /** * Sets the *short title* field. This is valid for the [TYPE_SHORT_TEXT], * [TYPE_RANGED_VALUE], and [TYPE_NO_PERMISSION] types, and is not valid for any other type. * * The value must be provided as a [ComplicationText] object, so that * time-dependent values may be included. * * The length of the text, including any time-dependent values, should not exceed seven * characters. If it does, the text may be truncated by the watch face or might not fit in * the complication. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setShortTitle(shortTitle: ComplicationText?) = apply { putOrRemoveField(FIELD_SHORT_TITLE, shortTitle) } /** * Sets the *short text* field. This is required for the [TYPE_SHORT_TEXT] type, * is optional for the [TYPE_RANGED_VALUE] and [TYPE_NO_PERMISSION] types, and * is not valid for any other type. * * The value must be provided as a [ComplicationText] object, so that * time-dependent values may be included. * * The length of the text, including any time-dependent values, should not exceed seven * characters. If it does, the text may be truncated by the watch face or might not fit in * the complication. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setShortText(shortText: ComplicationText?) = apply { putOrRemoveField(FIELD_SHORT_TEXT, shortText) } /** * Sets the *icon* field. This is required for the [TYPE_ICON] type, and is * optional for the [TYPE_SHORT_TEXT], [TYPE_LONG_TEXT], [TYPE_RANGED_VALUE], and * [TYPE_NO_PERMISSION] types. * * The provided image must be single-color, so that watch faces can tint it as required. * * If the icon provided here is not suitable for display in ambient mode with burn-in * protection (e.g. if it includes solid blocks of pixels), then a burn-in safe version of * the icon must be provided via [setBurnInProtectionIcon]. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setIcon(icon: Icon?) = apply { putOrRemoveField(FIELD_ICON, icon) } /** * Sets the burn-in protection version of the *icon* field. This should be provided if * the *icon* field is provided, unless the main icon is already safe for use with * burn-in protection. This icon should have fewer lit pixels, and should use darker * colors to prevent LCD burn in issues. * * The provided image must be single-color, so that watch faces can tint it as required. * * The provided image must not contain solid blocks of pixels - it should instead be * composed of outlines or lines only. * * If this field is set, the *icon* field must also be set. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setBurnInProtectionIcon(icon: Icon?) = apply { putOrRemoveField(FIELD_ICON_BURN_IN_PROTECTION, icon) } /** * Sets the *small image* field. This is required for the [TYPE_SMALL_IMAGE] * type, and is optional for the [TYPE_LONG_TEXT] type. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setSmallImage(smallImage: Icon?) = apply { putOrRemoveField(FIELD_SMALL_IMAGE, smallImage) } /** * Sets the burn-in protection version of the *small image* field. This should be * provided if the *small image* field is provided, unless the main small image is * already safe for use with burn-in protection. * * The provided image must not contain solid blocks of pixels - it should instead be * composed of outlines or lines only. * * If this field is set, the *small image* field must also be set. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setBurnInProtectionSmallImage(smallImage: Icon?) = apply { putOrRemoveField(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, smallImage) } /** * Sets the display style for this complication data. This is valid only for types that * contain small images, i.e. [TYPE_SMALL_IMAGE] and [TYPE_LONG_TEXT]. * * This affects how watch faces will draw the image in the complication. * * If not specified, the default is [IMAGE_STYLE_PHOTO]. * * @throws IllegalStateException if this field is not valid for the complication type * @see .IMAGE_STYLE_PHOTO which can be cropped but not recolored. * * @see .IMAGE_STYLE_ICON which can be recolored but not cropped. */ fun setSmallImageStyle(@ImageStyle imageStyle: Int) = apply { putIntField(FIELD_IMAGE_STYLE, imageStyle) } /** * Sets the *large image* field. This is required for the [TYPE_LARGE_IMAGE] * type, and is not valid for any other type. * * The provided image should be suitably sized to fill the screen of the watch. * * Returns this Builder to allow chaining. * * @throws IllegalStateException if this field is not valid for the complication type */ fun setLargeImage(largeImage: Icon?) = apply { putOrRemoveField(FIELD_LARGE_IMAGE, largeImage) } /** * Sets the list style hint * * Valid only if the type of this complication data is [EXP_TYPE_LIST]. Otherwise * returns * zero. */ fun setListStyleHint(listStyleHint: Int) = apply { putIntField(EXP_FIELD_LIST_STYLE_HINT, listStyleHint) } /** * Sets the *tap action* field. This is optional for any non-empty type. * * The provided [PendingIntent] may be fired if the complication is tapped on. Note * that some complications might not be tappable, in which case this field will be ignored. * * Returns this Builder to allow chaining. */ fun setTapAction(pendingIntent: PendingIntent?) = apply { putOrRemoveField(FIELD_TAP_ACTION, pendingIntent) } /** * Sets the *content description* field for accessibility. This is optional for any * non-empty type. It is recommended to provide a content description whenever the * data includes an image. * * The provided text will be read aloud by a Text-to-speech converter for users who may * be vision-impaired. It will be read aloud in addition to any long, short, or range text * in the complication. * * If using to describe an image/icon that is purely stylistic and doesn't convey any * information to the user, you may set the image content description to an empty string * (""). * * Returns this Builder to allow chaining. */ fun setContentDescription(description: ComplicationText?) = apply { putOrRemoveField(FIELD_CONTENT_DESCRIPTION, description) } /** * Sets whether or not this ComplicationData has been serialized. * * Returns this Builder to allow chaining. */ fun setTapActionLostDueToSerialization(tapActionLostDueToSerialization: Boolean) = apply { if (tapActionLostDueToSerialization) { fields.putBoolean(FIELD_TAP_ACTION_LOST, tapActionLostDueToSerialization) } } /** * Sets the placeholder. * * Returns this Builder to allow chaining. */ fun setPlaceholder(placeholder: ComplicationData?) = apply { if (placeholder == null) { fields.remove(FIELD_PLACEHOLDER_FIELDS) fields.remove(FIELD_PLACEHOLDER_TYPE) } else { checkFieldValidForType(FIELD_PLACEHOLDER_FIELDS, type) fields.putBundle(FIELD_PLACEHOLDER_FIELDS, placeholder.fields) putIntField(FIELD_PLACEHOLDER_TYPE, placeholder.type) } } /** * Sets the [ComponentName] of the ComplicationDataSourceService that provided this * ComplicationData. Generally this field should be set and is only nullable for backwards * compatibility. * * Returns this Builder to allow chaining. */ fun setDataSource(provider: ComponentName?) = apply { putOrRemoveField(FIELD_DATA_SOURCE, provider) } /** * Sets the ambient proto layout associated with this complication. * * Returns this Builder to allow chaining. */ fun setAmbientLayout(ambientProtoLayout: ByteArray) = apply { putByteArrayField(EXP_FIELD_PROTO_LAYOUT_AMBIENT, ambientProtoLayout) } /** * Sets the proto layout associated with this complication. * * Returns this Builder to allow chaining. */ fun setInteractiveLayout(protoLayout: ByteArray) = apply { putByteArrayField(EXP_FIELD_PROTO_LAYOUT_INTERACTIVE, protoLayout) } /** * Sets the proto layout resources associated with this complication. * * Returns this Builder to allow chaining. */ fun setLayoutResources(resources: ByteArray) = apply { putByteArrayField(EXP_FIELD_PROTO_LAYOUT_RESOURCES, resources) } /** * Optional. Sets the color the color ramp should be drawn with. * * Returns this Builder to allow chaining. */ fun setColorRamp(colorRamp: IntArray?) = apply { putOrRemoveField(FIELD_COLOR_RAMP, colorRamp) } /** * Optional. Sets whether or not the color ramp should be smoothly shaded or drawn with * steps. * * Returns this Builder to allow chaining. */ fun setColorRampIsSmoothShaded(isSmoothShaded: Boolean?) = apply { putOrRemoveField(FIELD_COLOR_RAMP_INTERPOLATED, isSmoothShaded) } /** * Sets the list of [ComplicationData] timeline entries. * * Returns this Builder to allow chaining. */ fun setListEntryCollection( timelineEntries: Collection<ComplicationData>? ) = apply { if (timelineEntries == null) { fields.remove(EXP_FIELD_LIST_ENTRIES) } else { fields.putParcelableArray( EXP_FIELD_LIST_ENTRIES, timelineEntries.map { data -> data.fields.putInt(EXP_FIELD_LIST_ENTRY_TYPE, data.type) data.fields }.toTypedArray() ) } } /** * Sets the element weights for this complication. * * Returns this Builder to allow chaining. */ fun setElementWeights(elementWeights: FloatArray?) = apply { putOrRemoveField(FIELD_ELEMENT_WEIGHTS, elementWeights) } /** * Sets the element colors for this complication. * * Returns this Builder to allow chaining. */ fun setElementColors(elementColors: IntArray?) = apply { putOrRemoveField(FIELD_ELEMENT_COLORS, elementColors) } /** * Sets the background color to use between elements for this complication. * * Returns this Builder to allow chaining. */ fun setElementBackgroundColor(@ColorInt elementBackgroundColor: Int) = apply { putOrRemoveField(FIELD_ELEMENT_BACKGROUND_COLOR, elementBackgroundColor) } /** * Constructs and returns [ComplicationData] with the provided fields. All required * fields must be populated before this method is called. * * @throws IllegalStateException if the required fields have not been populated */ fun build(): ComplicationData { // Validate. for (requiredField in REQUIRED_FIELDS[type]!!) { check(fields.containsKey(requiredField)) { "Field $requiredField is required for type $type" } check( !(fields.containsKey(FIELD_ICON_BURN_IN_PROTECTION) && !fields.containsKey(FIELD_ICON)) ) { "Field ICON must be provided when field ICON_BURN_IN_PROTECTION is provided." } check( !(fields.containsKey(FIELD_SMALL_IMAGE_BURN_IN_PROTECTION) && !fields.containsKey(FIELD_SMALL_IMAGE)) ) { "Field SMALL_IMAGE must be provided when field SMALL_IMAGE_BURN_IN_PROTECTION" + " is provided." } } for (requiredOneOfFieldGroup in REQUIRED_ONE_OF_FIELDS[type]!!) { check(requiredOneOfFieldGroup.count { fields.containsKey(it) } >= 1) { "One of $requiredOneOfFieldGroup must be provided." } } return ComplicationData(this) } private fun putIntField(field: String, value: Int) { checkFieldValidForType(field, type) fields.putInt(field, value) } private fun putFloatField(field: String, value: Float) { checkFieldValidForType(field, type) fields.putFloat(field, value) } private fun putByteArrayField(field: String, value: ByteArray) { checkFieldValidForType(field, type) fields.putByteArray(field, value) } /** Sets the field with obj or removes it if null. */ private fun putOrRemoveField(field: String, obj: Any?) { checkFieldValidForType(field, type) if (obj == null) { fields.remove(field) return } when (obj) { is Boolean -> fields.putBoolean(field, obj) is Int -> fields.putInt(field, obj) is Float -> fields.putFloat(field, obj) is String -> fields.putString(field, obj) is Parcelable -> fields.putParcelable(field, obj) is ByteArray -> fields.putByteArray(field, obj) is IntArray -> fields.putIntArray(field, obj) is FloatArray -> fields.putFloatArray(field, obj) else -> throw IllegalArgumentException("Unexpected object type: " + obj.javaClass) } } } companion object { private const val TAG = "ComplicationData" const val PLACEHOLDER_STRING = "__placeholder__" /** * Type sent when a complication does not have a provider configured. The system will send * data of this type to watch faces when the user has not chosen a provider for an active * complication, and the watch face has not set a default provider. Providers cannot send * data of this type. * * No fields may be populated for complication data of this type. */ const val TYPE_NOT_CONFIGURED = 1 /** * Type sent when the user has specified that an active complication should have no * provider, i.e. when the user has chosen "Empty" in the provider chooser. Providers cannot * send data of this type. * * No fields may be populated for complication data of this type. */ const val TYPE_EMPTY = 2 /** * Type that can be sent by any provider, regardless of the configured type, when the * provider has no data to be displayed. Watch faces may choose whether to render this in * some way or leave the slot empty. * * No fields may be populated for complication data of this type. */ const val TYPE_NO_DATA = 10 /** * Type used for complications where the primary piece of data is a short piece of text * (expected to be no more than seven characters in length). The short text may be * accompanied by an icon or a short title (or both, but if both are provided then a watch * face may choose to display only one). * * The *short text* field is required for this type, and is expected to always be * displayed. * * The *icon* (and *burnInProtectionIcon*) and *short title* fields are * optional for this type. If only one of these is provided, it is expected that it will be * displayed. If both are provided, it is expected that one of these will be displayed. */ const val TYPE_SHORT_TEXT = 3 /** * Type used for complications where the primary piece of data is a piece of text. The text * may be accompanied by an icon and/or a title. * * The *long text* field is required for this type, and is expected to always be * displayed. * * The *long title* field is optional for this type. If provided, it is expected that * this field will be displayed. * * The *icon* (and *burnInProtectionIcon*) and *small image* fields are also * optional for this type. If provided, at least one of these should be displayed. */ const val TYPE_LONG_TEXT = 4 /** * Type used for complications including a numerical value within a range, such as a * percentage. The value may be accompanied by an icon and/or short text and title. * * The *value*, *min value*, and *max value* fields are required for this * type, and the value within the range is expected to always be displayed. * * The *icon* (and *burnInProtectionIcon*), *short title*, and *short * text* fields are optional for this type, but at least one must be defined. The watch face * may choose which of these fields to display, if any. */ const val TYPE_RANGED_VALUE = 5 /** * Type used for complications which consist only of a tintable icon. * * The *icon* field is required for this type, and is expected to always be displayed, * unless the device is in ambient mode with burn-in protection enabled, in which case the * *burnInProtectionIcon* field should be used instead. * * The contentDescription field is recommended for this type. Use it to describe what data * the icon represents. If the icon is purely stylistic, and does not convey any information * to the user, then enter the empty string as the contentDescription. * * No other fields are valid for this type. */ const val TYPE_ICON = 6 /** * Type used for complications which consist only of a small image. * * The *small image* field is required for this type, and is expected to always be * displayed, unless the device is in ambient mode, in which case either nothing or the * *burnInProtectionSmallImage* field may be used instead. * * The contentDescription field is recommended for this type. Use it to describe what data * the image represents. If the image is purely stylistic, and does not convey any * information to the user, then enter the empty string as the contentDescription. * * No other fields are valid for this type. */ const val TYPE_SMALL_IMAGE = 7 /** * Type used for complications which consist only of a large image. A large image here is * one that could be used to fill the watch face, for example as the background. * * The *large image* field is required for this type, and is expected to always be * displayed, unless the device is in ambient mode. * * The contentDescription field is recommended for this type. Use it to describe what data * the image represents. If the image is purely stylistic, and does not convey any * information to the user, then enter the empty string as the contentDescription. * * No other fields are valid for this type. */ const val TYPE_LARGE_IMAGE = 8 /** * Type sent by the system when the watch face does not have permission to receive * complication data. * * Fields will be populated to allow the data to be rendered as if it were of * [TYPE_SHORT_TEXT] or [TYPE_ICON] for consistency and convenience, but watch faces may * render this as they see fit. * * It is recommended that, where possible, tapping on the complication when in this state * should trigger a permission request. */ const val TYPE_NO_PERMISSION = 9 /** * Type used for complications which indicate progress towards a goal. The value may be * accompanied by an icon and/or short text and title. * * The *value*, and *target value* fields are required for this type, and the * value is expected to always be displayed. The value must be >= 0 and may be > target * value. E.g. 15000 out of a target of 10000 steps. * * The *icon* (and *burnInProtectionIcon*), *short title*, and *short * text* fields are optional for this type, but at least one must be defined. The watch face * may choose which of these fields to display, if any. */ const val TYPE_GOAL_PROGRESS = 13 /** * Type used for complications to display a series of weighted values e.g. in a pie chart. * The weighted values may be accompanied by an icon and/or short text and title. * * The *element weights* and *element colors* fields are required for this type, * and the value within the range is expected to always be displayed. * * The *icon* (and *burnInProtectionIcon*), *short title*, and *short * text* fields are optional for this type, but at least one must be defined. The watch face * may choose which of these fields to display, if any. */ const val TYPE_WEIGHTED_ELEMENTS = 14 // The following types are experimental, and they have negative IDs. /** Type that specifies a proto layout based complication. */ const val EXP_TYPE_PROTO_LAYOUT = -11 /** Type that specifies a list of complication values. E.g. to support linear 3. */ const val EXP_TYPE_LIST = -12 /** * Style for small images which are photos that are expected to fill the space available. * Images of this style may be cropped to fit the shape of the complication - in particular, * the image may be cropped to a circle. Photos my not be recolored. * * This is the default value. */ const val IMAGE_STYLE_PHOTO = 1 /** * Style for small images that have a transparent background and are expected to be drawn * entirely within the space available, such as a launcher icon. Watch faces may add padding * when drawing these images, but should never crop these images. Icons may be recolored to * fit the complication style. */ const val IMAGE_STYLE_ICON = 2 private const val FIELD_COLOR_RAMP = "COLOR_RAMP" private const val FIELD_COLOR_RAMP_INTERPOLATED = "COLOR_RAMP_INTERPOLATED" private const val FIELD_DATA_SOURCE = "FIELD_DATA_SOURCE" private const val FIELD_DISPLAY_POLICY = "DISPLAY_POLICY" private const val FIELD_ELEMENT_BACKGROUND_COLOR = "ELEMENT_BACKGROUND_COLOR" private const val FIELD_ELEMENT_COLORS = "ELEMENT_COLORS" private const val FIELD_ELEMENT_WEIGHTS = "ELEMENT_WEIGHTS" private const val FIELD_END_TIME = "END_TIME" private const val FIELD_ICON = "ICON" private const val FIELD_ICON_BURN_IN_PROTECTION = "ICON_BURN_IN_PROTECTION" private const val FIELD_IMAGE_STYLE = "IMAGE_STYLE" private const val FIELD_LARGE_IMAGE = "LARGE_IMAGE" private const val FIELD_LONG_TITLE = "LONG_TITLE" private const val FIELD_LONG_TEXT = "LONG_TEXT" private const val FIELD_MAX_VALUE = "MAX_VALUE" private const val FIELD_MIN_VALUE = "MIN_VALUE" private const val FIELD_PERSISTENCE_POLICY = "PERSISTENCE_POLICY" private const val FIELD_PLACEHOLDER_FIELDS = "PLACEHOLDER_FIELDS" private const val FIELD_PLACEHOLDER_TYPE = "PLACEHOLDER_TYPE" private const val FIELD_SMALL_IMAGE = "SMALL_IMAGE" private const val FIELD_SMALL_IMAGE_BURN_IN_PROTECTION = "SMALL_IMAGE_BURN_IN_PROTECTION" private const val FIELD_SHORT_TITLE = "SHORT_TITLE" private const val FIELD_SHORT_TEXT = "SHORT_TEXT" private const val FIELD_START_TIME = "START_TIME" private const val FIELD_TAP_ACTION = "TAP_ACTION" private const val FIELD_TAP_ACTION_LOST = "FIELD_TAP_ACTION_LOST" private const val FIELD_TARGET_VALUE = "TARGET_VALUE" private const val FIELD_TIMELINE_START_TIME = "TIMELINE_START_TIME" private const val FIELD_TIMELINE_END_TIME = "TIMELINE_END_TIME" private const val FIELD_TIMELINE_ENTRIES = "TIMELINE" private const val FIELD_TIMELINE_ENTRY_TYPE = "TIMELINE_ENTRY_TYPE" private const val FIELD_VALUE = "VALUE" private const val FIELD_VALUE_EXPRESSION = "VALUE_EXPRESSION" private const val FIELD_VALUE_TYPE = "VALUE_TYPE" // Experimental fields, these are subject to change without notice. private const val EXP_FIELD_LIST_ENTRIES = "EXP_LIST_ENTRIES" private const val EXP_FIELD_LIST_ENTRY_TYPE = "EXP_LIST_ENTRY_TYPE" private const val EXP_FIELD_LIST_STYLE_HINT = "EXP_LIST_STYLE_HINT" private const val EXP_FIELD_PROTO_LAYOUT_AMBIENT = "EXP_FIELD_PROTO_LAYOUT_AMBIENT" private const val EXP_FIELD_PROTO_LAYOUT_INTERACTIVE = "EXP_FIELD_PROTO_LAYOUT_INTERACTIVE" private const val EXP_FIELD_PROTO_LAYOUT_RESOURCES = "EXP_FIELD_PROTO_LAYOUT_RESOURCES" // Originally it was planned to support both content and image content descriptions. private const val FIELD_CONTENT_DESCRIPTION = "IMAGE_CONTENT_DESCRIPTION" // The set of valid types. private val VALID_TYPES: Set<Int> = setOf( TYPE_NOT_CONFIGURED, TYPE_EMPTY, TYPE_SHORT_TEXT, TYPE_LONG_TEXT, TYPE_RANGED_VALUE, TYPE_ICON, TYPE_SMALL_IMAGE, TYPE_LARGE_IMAGE, TYPE_NO_PERMISSION, TYPE_NO_DATA, EXP_TYPE_PROTO_LAYOUT, EXP_TYPE_LIST, TYPE_GOAL_PROGRESS, TYPE_WEIGHTED_ELEMENTS, ) // Used for validation. REQUIRED_FIELDS[i] is a list containing all the fields which must be // populated for @ComplicationType i. private val REQUIRED_FIELDS: Map<Int, Set<String>> = mapOf( TYPE_NOT_CONFIGURED to setOf(), TYPE_EMPTY to setOf(), TYPE_SHORT_TEXT to setOf(FIELD_SHORT_TEXT), TYPE_LONG_TEXT to setOf(FIELD_LONG_TEXT), TYPE_RANGED_VALUE to setOf(FIELD_MIN_VALUE, FIELD_MAX_VALUE), TYPE_ICON to setOf(FIELD_ICON), TYPE_SMALL_IMAGE to setOf(FIELD_SMALL_IMAGE, FIELD_IMAGE_STYLE), TYPE_LARGE_IMAGE to setOf(FIELD_LARGE_IMAGE), TYPE_NO_PERMISSION to setOf(), TYPE_NO_DATA to setOf(), EXP_TYPE_PROTO_LAYOUT to setOf( EXP_FIELD_PROTO_LAYOUT_AMBIENT, EXP_FIELD_PROTO_LAYOUT_INTERACTIVE, EXP_FIELD_PROTO_LAYOUT_RESOURCES, ), EXP_TYPE_LIST to setOf(EXP_FIELD_LIST_ENTRIES), TYPE_GOAL_PROGRESS to setOf(FIELD_TARGET_VALUE), TYPE_WEIGHTED_ELEMENTS to setOf( FIELD_ELEMENT_WEIGHTS, FIELD_ELEMENT_COLORS, FIELD_ELEMENT_BACKGROUND_COLOR, ), ) // Used for validation. REQUIRED_ONE_OF_FIELDS[i] is a list of field groups of which at // least one field must be populated for @ComplicationType i. // If a field is also in REQUIRED_FIELDS[i], it is not required if another field in the one // of group is populated. private val REQUIRED_ONE_OF_FIELDS: Map<Int, Set<Set<String>>> = mapOf( TYPE_NOT_CONFIGURED to setOf(), TYPE_EMPTY to setOf(), TYPE_SHORT_TEXT to setOf(), TYPE_LONG_TEXT to setOf(), TYPE_RANGED_VALUE to setOf(setOf(FIELD_VALUE, FIELD_VALUE_EXPRESSION)), TYPE_ICON to setOf(), TYPE_SMALL_IMAGE to setOf(), TYPE_LARGE_IMAGE to setOf(), TYPE_NO_PERMISSION to setOf(), TYPE_NO_DATA to setOf(), EXP_TYPE_PROTO_LAYOUT to setOf(), EXP_TYPE_LIST to setOf(), TYPE_GOAL_PROGRESS to setOf(setOf(FIELD_VALUE, FIELD_VALUE_EXPRESSION)), TYPE_WEIGHTED_ELEMENTS to setOf(), ) // Used for validation. OPTIONAL_FIELDS[i] is a list containing all the fields which are // valid but not required for type i. private val OPTIONAL_FIELDS: Map<Int, Set<String>> = mapOf( TYPE_NOT_CONFIGURED to setOf(), TYPE_EMPTY to setOf(), TYPE_SHORT_TEXT to setOf( FIELD_SHORT_TITLE, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_LONG_TEXT to setOf( FIELD_LONG_TITLE, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_RANGED_VALUE to setOf( FIELD_SHORT_TEXT, FIELD_SHORT_TITLE, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_COLOR_RAMP, FIELD_COLOR_RAMP_INTERPOLATED, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, FIELD_VALUE_TYPE, ), TYPE_ICON to setOf( FIELD_TAP_ACTION, FIELD_ICON_BURN_IN_PROTECTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_SMALL_IMAGE to setOf( FIELD_TAP_ACTION, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_LARGE_IMAGE to setOf( FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_NO_PERMISSION to setOf( FIELD_SHORT_TEXT, FIELD_SHORT_TITLE, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_NO_DATA to setOf( FIELD_CONTENT_DESCRIPTION, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_LARGE_IMAGE, FIELD_LONG_TEXT, FIELD_LONG_TITLE, FIELD_MAX_VALUE, FIELD_MIN_VALUE, FIELD_PLACEHOLDER_FIELDS, FIELD_PLACEHOLDER_TYPE, FIELD_SHORT_TEXT, FIELD_SHORT_TITLE, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_TAP_ACTION, FIELD_VALUE, FIELD_VALUE_EXPRESSION, FIELD_VALUE_TYPE, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), EXP_TYPE_PROTO_LAYOUT to setOf( FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), EXP_TYPE_LIST to setOf( FIELD_TAP_ACTION, EXP_FIELD_LIST_STYLE_HINT, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_GOAL_PROGRESS to setOf( FIELD_SHORT_TEXT, FIELD_SHORT_TITLE, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_COLOR_RAMP, FIELD_COLOR_RAMP_INTERPOLATED, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), TYPE_WEIGHTED_ELEMENTS to setOf( FIELD_SHORT_TEXT, FIELD_SHORT_TITLE, FIELD_ICON, FIELD_ICON_BURN_IN_PROTECTION, FIELD_SMALL_IMAGE, FIELD_SMALL_IMAGE_BURN_IN_PROTECTION, FIELD_IMAGE_STYLE, FIELD_TAP_ACTION, FIELD_CONTENT_DESCRIPTION, FIELD_DATA_SOURCE, FIELD_PERSISTENCE_POLICY, FIELD_DISPLAY_POLICY, ), ) @JvmField val CREATOR = object : Parcelable.Creator<ComplicationData> { override fun createFromParcel(source: Parcel) = ComplicationData(source) override fun newArray(size: Int): Array<ComplicationData?> = Array(size) { null } } fun isFieldValidForType(field: String, @ComplicationType type: Int): Boolean { return REQUIRED_FIELDS[type]!!.contains(field) || REQUIRED_ONE_OF_FIELDS[type]!!.any { it.contains(field) } || OPTIONAL_FIELDS[type]!!.contains(field) } private fun isTypeSupported(type: Int) = type in VALID_TYPES /** * The unparceling logic needs to remain backward compatible. * Validates that a value of the given field type can be assigned * to the given complication type. */ internal fun checkFieldValidForTypeWithoutThrowingException( fieldType: String, @ComplicationType complicationType: Int, ) { if (!isTypeSupported(complicationType)) { Log.w(TAG, "Type $complicationType can not be recognized") return } if (!isFieldValidForType(fieldType, complicationType)) { Log.d(TAG, "Field $fieldType is not supported for type $complicationType") } } internal fun checkFieldValidForType(field: String, @ComplicationType type: Int) { check(isTypeSupported(type)) { "Type $type can not be recognized" } check(isFieldValidForType(field, type)) { "Field $field is not supported for type $type" } } /** Returns whether or not we should redact complication data in toString(). */ @JvmStatic fun shouldRedact() = !Log.isLoggable(TAG, Log.DEBUG) @JvmStatic fun maybeRedact(unredacted: CharSequence?): String = if (unredacted == null) "(null)" else maybeRedact(unredacted.toString()) @JvmSynthetic private fun maybeRedact(unredacted: String): String = if (!shouldRedact() || unredacted == PLACEHOLDER_STRING) unredacted else "REDACTED" } } /** Writes a [ByteArray] by writing the size, then the bytes. To be used with [readByteArray]. */ internal fun ObjectOutputStream.writeByteArray(value: ByteArray) { writeInt(value.size) write(value) } /** Reads a [ByteArray] written with [writeByteArray]. */ internal fun ObjectInputStream.readByteArray() = ByteArray(readInt()).also { readFully(it) } /** Writes an [IntArray] by writing the size, then the bytes. To be used with [readIntArray]. */ internal fun ObjectOutputStream.writeIntArray(value: IntArray) { writeInt(value.size) value.forEach(this::writeInt) } /** Reads an [IntArray] written with [writeIntArray]. */ internal fun ObjectInputStream.readIntArray() = IntArray(readInt()).also { for (i in it.indices) it[i] = readInt() } /** Writes a [FloatArray] by writing the size, then the bytes. To be used with [readFloatArray]. */ internal fun ObjectOutputStream.writeFloatArray(value: FloatArray) { writeInt(value.size) value.forEach(this::writeFloat) } /** Reads a [FloatArray] written with [writeFloatArray]. */ internal fun ObjectInputStream.readFloatArray() = FloatArray(readInt()).also { for (i in it.indices) it[i] = readFloat() } /** Writes a generic [List] by writing the size, then the objects. To be used with [readList]. */ internal fun <T> ObjectOutputStream.writeList(value: List<T>, writer: (T) -> Unit) { writeInt(value.size) value.forEach(writer) } /** Reads a list written with [readList]. */ internal fun <T> ObjectInputStream.readList(reader: () -> T) = List(readInt()) { reader() } /** * Writes a nullable object by writing a boolean, then the object. To be used with [readNullable]. */ internal fun <T> ObjectOutputStream.writeNullable(value: T?, writer: (T) -> Unit) { if (value != null) { writeBoolean(true) writer(value) } else { writeBoolean(false) } } /** Reads a nullable value written with [writeNullable]. */ internal fun <T> ObjectInputStream.readNullable(reader: () -> T): T? = if (readBoolean()) reader() else null
apache-2.0
a70d03ca930703758a0ae5260f8a2db4
41.503743
100
0.612364
4.683455
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/typeAliasClsStubBuilding.kt
2
2323
// 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.decompiler.stubBuilder import com.intellij.psi.PsiElement import com.intellij.psi.stubs.StubElement import org.jetbrains.kotlin.idea.decompiler.stubBuilder.flags.VISIBILITY import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.Flags import org.jetbrains.kotlin.metadata.deserialization.underlyingType import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.psi.stubs.impl.KotlinTypeAliasStubImpl import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer import org.jetbrains.kotlin.serialization.deserialization.getClassId import org.jetbrains.kotlin.serialization.deserialization.getName fun createTypeAliasStub( parent: StubElement<out PsiElement>, typeAliasProto: ProtoBuf.TypeAlias, protoContainer: ProtoContainer, outerContext: ClsStubBuilderContext ) { val c = outerContext.child(typeAliasProto.typeParameterList) val shortName = c.nameResolver.getName(typeAliasProto.name) val classId = when (protoContainer) { is ProtoContainer.Class -> protoContainer.classId.createNestedClassId(shortName) is ProtoContainer.Package -> ClassId.topLevel(protoContainer.fqName.child(shortName)) } val typeAlias = KotlinTypeAliasStubImpl( parent, classId.shortClassName.ref(), classId.asSingleFqName().ref(), isTopLevel = !classId.isNestedClass ) val modifierList = createModifierListStubForDeclaration(typeAlias, typeAliasProto.flags, arrayListOf(VISIBILITY), listOf()) val typeStubBuilder = TypeClsStubBuilder(c) val restConstraints = typeStubBuilder.createTypeParameterListStub(typeAlias, typeAliasProto.typeParameterList) assert(restConstraints.isEmpty()) { "'where' constraints are not allowed for type aliases" } if (Flags.HAS_ANNOTATIONS.get(typeAliasProto.flags)) { createAnnotationStubs(typeAliasProto.annotationList.map { c.nameResolver.getClassId(it.id) }, modifierList) } val typeAliasUnderlyingType = typeAliasProto.underlyingType(c.typeTable) typeStubBuilder.createTypeReferenceStub(typeAlias, typeAliasUnderlyingType) }
apache-2.0
8545fa61fa5a2d51c8390c1873566dda
45.46
158
0.798106
4.646
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/fragments/projectpage/ProjectCampaignFragment.kt
1
5752
package com.kickstarter.ui.fragments.projectpage import android.app.Activity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.LinearLayoutManager import com.kickstarter.R import com.kickstarter.databinding.FragmentProjectCampaignBinding import com.kickstarter.libs.BaseFragment import com.kickstarter.libs.Configure import com.kickstarter.libs.qualifiers.RequiresFragmentViewModel import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.ui.ArgumentsKey import com.kickstarter.ui.IntentKey import com.kickstarter.ui.adapters.projectcampaign.HeaderElementAdapter import com.kickstarter.ui.adapters.projectcampaign.ViewElementAdapter import com.kickstarter.ui.data.ProjectData import com.kickstarter.ui.extensions.startVideoActivity import com.kickstarter.ui.views.RecyclerViewScrollListener import com.kickstarter.viewmodels.projectpage.ProjectCampaignViewModel import rx.schedulers.Schedulers import java.util.concurrent.TimeUnit @RequiresFragmentViewModel(ProjectCampaignViewModel.ViewModel::class) class ProjectCampaignFragment : BaseFragment<ProjectCampaignViewModel.ViewModel>(), Configure, ViewElementAdapter.FullScreenDelegate { private var binding: FragmentProjectCampaignBinding? = null private var viewElementAdapter: ViewElementAdapter? = null var startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { // There are no request codes val data = result.data?.getLongExtra(IntentKey.VIDEO_SEEK_POSITION, 0) data?.let { viewModel.inputs.closeFullScreenVideo(it) } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) binding = FragmentProjectCampaignBinding.inflate(inflater, container, false) return binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewElementAdapter = ViewElementAdapter(requireActivity(), this, this.lifecycle()) val headerElementAdapter = HeaderElementAdapter() binding?.projectCampaignViewListItems?.itemAnimator = null binding?.projectCampaignViewListItems?.layoutManager = LinearLayoutManager(context) binding?.projectCampaignViewListItems?.adapter = ConcatAdapter( headerElementAdapter, viewElementAdapter ) headerElementAdapter.updateTitle(resources.getString(R.string.Story)) this.viewModel.outputs.storyViewElements() .subscribeOn(Schedulers.io()) .distinctUntilChanged() .delay(170, TimeUnit.MILLISECONDS) .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { viewElementAdapter?.submitList(it) } this.viewModel.outputs.onScrollToVideoPosition() .subscribeOn(Schedulers.io()) .distinctUntilChanged() .delay(300, TimeUnit.MILLISECONDS) .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding?.projectCampaignViewListItems?.smoothScrollToPosition(it + 1) } this.viewModel.outputs.onOpenVideoInFullScreen() .subscribeOn(Schedulers.io()) .distinctUntilChanged() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { requireActivity().startVideoActivity(startForResult, it.first, it.second) } this.viewModel.outputs.updateVideoCloseSeekPosition() .subscribeOn(Schedulers.io()) .distinctUntilChanged() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { viewElementAdapter?.setPlayerSeekPosition(it.first, it.second) } val scrollListener = object : RecyclerViewScrollListener() { override fun onItemIsFirstVisibleItem(index: Int) { // play just visible item if (index != -1) { viewElementAdapter?.playIndexThenPausePreviousPlayer(index) } } } binding?.projectCampaignViewListItems?.addOnScrollListener(scrollListener) } override fun onDetach() { super.onDetach() viewElementAdapter?.releaseAllPlayers() } override fun onPause() { super.onPause() viewElementAdapter?.releasePlayersOnPause() } override fun configureWith(projectData: ProjectData) { this.viewModel?.inputs?.configureWith(projectData) } override fun onDestroyView() { binding?.projectCampaignViewListItems?.adapter = null super.onDestroyView() } companion object { @JvmStatic fun newInstance(position: Int): ProjectCampaignFragment { val fragment = ProjectCampaignFragment() val bundle = Bundle() bundle.putInt(ArgumentsKey.PROJECT_PAGER_POSITION, position) fragment.arguments = bundle return fragment } } override fun onFullScreenOpened(index: Int, source: String, seekPosition: Long) { viewModel.inputs.openVideoInFullScreen(index, source, seekPosition) } }
apache-2.0
a0d84b15ce14de0991537c1ceac59de2
37.864865
116
0.699583
5.411101
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslSampleColorTexture.kt
1
926
package de.fabmax.kool.modules.ksl.lang import de.fabmax.kool.modules.ksl.generator.KslGenerator import de.fabmax.kool.modules.ksl.model.KslMutatedState class KslSampleColorTexture<T: KslTypeSampler<KslTypeFloat4>>( val sampler: KslExpression<T>, val coord: KslExpression<*>, val lod: KslScalarExpression<KslTypeFloat1>?) : KslVectorExpression<KslTypeFloat4, KslTypeFloat1> { override val expressionType = KslTypeFloat4 override fun collectStateDependencies(): Set<KslMutatedState> { val deps = sampler.collectStateDependencies() + coord.collectStateDependencies() return lod?.let { deps + it.collectStateDependencies() } ?: deps } override fun generateExpression(generator: KslGenerator): String = generator.sampleColorTexture(this) override fun toPseudoCode(): String = "${sampler.toPseudoCode()}.sample(${coord.toPseudoCode()}, lod=${lod?.toPseudoCode() ?: "0"})" }
apache-2.0
fb71029dc272bad4654eef78faec6a2f
43.095238
136
0.74838
4.190045
false
false
false
false
siosio/intellij-community
plugins/kotlin/common/src/org/jetbrains/kotlin/idea/kdoc/resolveKDocLink.kt
1
12492
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.kdoc import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.idea.util.application.getService import org.jetbrains.kotlin.idea.util.getFileResolutionScope import org.jetbrains.kotlin.idea.util.substituteExtensionIfCallable import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.FunctionDescriptorUtil import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.scopes.* import org.jetbrains.kotlin.resolve.scopes.utils.* import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull fun resolveKDocLink( context: BindingContext, resolutionFacade: ResolutionFacade, fromDescriptor: DeclarationDescriptor, fromSubjectOfTag: KDocTag?, qualifiedName: List<String> ): Collection<DeclarationDescriptor> = when (fromSubjectOfTag?.knownTag) { KDocKnownTag.PARAM -> resolveParamLink(fromDescriptor, qualifiedName) KDocKnownTag.SAMPLE -> resolveKDocSampleLink(context, resolutionFacade, fromDescriptor, qualifiedName) else -> resolveDefaultKDocLink(context, resolutionFacade, fromDescriptor, qualifiedName) } fun getParamDescriptors(fromDescriptor: DeclarationDescriptor): List<DeclarationDescriptor> { // TODO resolve parameters of functions passed as parameters when (fromDescriptor) { is CallableDescriptor -> { return fromDescriptor.valueParameters + fromDescriptor.typeParameters } is ClassifierDescriptor -> { val typeParams = fromDescriptor.typeConstructor.parameters if (fromDescriptor is ClassDescriptor) { val constructorDescriptor = fromDescriptor.unsubstitutedPrimaryConstructor if (constructorDescriptor != null) { return typeParams + constructorDescriptor.valueParameters } } return typeParams } else -> { return emptyList() } } } private fun resolveParamLink(fromDescriptor: DeclarationDescriptor, qualifiedName: List<String>): List<DeclarationDescriptor> { val name = qualifiedName.singleOrNull() ?: return emptyList() return getParamDescriptors(fromDescriptor).filter { it.name.asString() == name } } fun resolveKDocSampleLink( context: BindingContext, resolutionFacade: ResolutionFacade, fromDescriptor: DeclarationDescriptor, qualifiedName: List<String> ): Collection<DeclarationDescriptor> { val resolvedViaService = SampleResolutionService.resolveSample(context, fromDescriptor, resolutionFacade, qualifiedName) if (resolvedViaService.isNotEmpty()) return resolvedViaService return resolveDefaultKDocLink(context, resolutionFacade, fromDescriptor, qualifiedName) } private fun resolveDefaultKDocLink( context: BindingContext, resolutionFacade: ResolutionFacade, fromDescriptor: DeclarationDescriptor, qualifiedName: List<String> ): Collection<DeclarationDescriptor> { val contextScope = getKDocLinkResolutionScope(resolutionFacade, fromDescriptor) if (qualifiedName.size == 1) { val shortName = Name.identifier(qualifiedName.single()) val descriptorsByName = SmartList<DeclarationDescriptor>() descriptorsByName.addIfNotNull(contextScope.findClassifier(shortName, NoLookupLocation.FROM_IDE)) descriptorsByName.addIfNotNull(contextScope.findPackage(shortName)) descriptorsByName.addAll(contextScope.collectFunctions(shortName, NoLookupLocation.FROM_IDE)) descriptorsByName.addAll(contextScope.collectVariables(shortName, NoLookupLocation.FROM_IDE)) if (fromDescriptor is FunctionDescriptor && fromDescriptor.isExtension && shortName.asString() == "this") { return listOfNotNull(fromDescriptor.extensionReceiverParameter) } // Try to find a matching local descriptor (parameter or type parameter) first val localDescriptors = descriptorsByName.filter { it.containingDeclaration == fromDescriptor } if (localDescriptors.isNotEmpty()) return localDescriptors return descriptorsByName } val moduleDescriptor = fromDescriptor.module @OptIn(FrontendInternals::class) val qualifiedExpressionResolver = resolutionFacade.getFrontendService(moduleDescriptor, QualifiedExpressionResolver::class.java) val contextElement = DescriptorToSourceUtils.descriptorToDeclaration(fromDescriptor) val factory = KtPsiFactory(resolutionFacade.project) // TODO escape identifiers val codeFragment = factory.createExpressionCodeFragment(qualifiedName.joinToString("."), contextElement) val qualifiedExpression = codeFragment.findElementAt(codeFragment.textLength - 1)?.getStrictParentOfType<KtQualifiedExpression>() ?: return emptyList() val (descriptor, memberName) = qualifiedExpressionResolver.resolveClassOrPackageInQualifiedExpression( qualifiedExpression, contextScope, context ) if (descriptor == null) return emptyList() if (memberName != null) { val memberScope = getKDocLinkMemberScope(descriptor, contextScope) return memberScope.getContributedFunctions(memberName, NoLookupLocation.FROM_IDE) + memberScope.getContributedVariables(memberName, NoLookupLocation.FROM_IDE) + listOfNotNull(memberScope.getContributedClassifier(memberName, NoLookupLocation.FROM_IDE)) } return listOf(descriptor) } private fun getPackageInnerScope(descriptor: PackageFragmentDescriptor): MemberScope { return descriptor.containingDeclaration.getPackage(descriptor.fqName).memberScope } private fun getClassInnerScope(outerScope: LexicalScope, descriptor: ClassDescriptor): LexicalScope { val headerScope = LexicalScopeImpl( outerScope, descriptor, false, descriptor.thisAsReceiverParameter, LexicalScopeKind.SYNTHETIC ) { descriptor.declaredTypeParameters.forEach { addClassifierDescriptor(it) } descriptor.constructors.forEach { addFunctionDescriptor(it) } } return LexicalChainedScope.create( headerScope, descriptor, false, null, LexicalScopeKind.SYNTHETIC, descriptor.defaultType.memberScope, descriptor.staticScope, descriptor.companionObjectDescriptor?.defaultType?.memberScope ) } fun getKDocLinkResolutionScope(resolutionFacade: ResolutionFacade, contextDescriptor: DeclarationDescriptor): LexicalScope { return when (contextDescriptor) { is PackageFragmentDescriptor -> LexicalScope.Base(getPackageInnerScope(contextDescriptor).memberScopeAsImportingScope(), contextDescriptor) is PackageViewDescriptor -> LexicalScope.Base(contextDescriptor.memberScope.memberScopeAsImportingScope(), contextDescriptor) is ClassDescriptor -> getClassInnerScope(getOuterScope(contextDescriptor, resolutionFacade), contextDescriptor) is FunctionDescriptor -> FunctionDescriptorUtil.getFunctionInnerScope( getOuterScope(contextDescriptor, resolutionFacade), contextDescriptor, LocalRedeclarationChecker.DO_NOTHING ) is PropertyDescriptor -> ScopeUtils.makeScopeForPropertyHeader(getOuterScope(contextDescriptor, resolutionFacade), contextDescriptor) is DeclarationDescriptorNonRoot -> getOuterScope(contextDescriptor, resolutionFacade) else -> throw IllegalArgumentException("Cannot find resolution scope for root $contextDescriptor") } } private fun getOuterScope(descriptor: DeclarationDescriptorWithSource, resolutionFacade: ResolutionFacade): LexicalScope { val parent = descriptor.containingDeclaration!! if (parent is PackageFragmentDescriptor) { val containingFile = (descriptor.source as? PsiSourceElement)?.psi?.containingFile as? KtFile ?: return LexicalScope.Base( ImportingScope.Empty, parent ) val kotlinCacheService = containingFile.project.getService<KotlinCacheService>() val facadeToUse = kotlinCacheService?.getResolutionFacade(listOf(containingFile)) ?: resolutionFacade return facadeToUse.getFileResolutionScope(containingFile) } else { return getKDocLinkResolutionScope(resolutionFacade, parent) } } fun getKDocLinkMemberScope(descriptor: DeclarationDescriptor, contextScope: LexicalScope): MemberScope { return when (descriptor) { is PackageFragmentDescriptor -> getPackageInnerScope(descriptor) is PackageViewDescriptor -> descriptor.memberScope is ClassDescriptor -> { ChainedMemberScope.create( "Member scope for KDoc resolve", listOfNotNull( descriptor.unsubstitutedMemberScope, descriptor.staticScope, descriptor.companionObjectDescriptor?.unsubstitutedMemberScope, ExtensionsScope(descriptor, contextScope) ) ) } else -> MemberScope.Empty } } private class ExtensionsScope( private val receiverClass: ClassDescriptor, private val contextScope: LexicalScope ) : MemberScope { private val receiverTypes = listOf(receiverClass.defaultType) override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> { return contextScope.collectFunctions(name, location).flatMap { if (it is SimpleFunctionDescriptor && it.isExtension) it.substituteExtensionIfCallable( receiverTypes, CallType.DOT ) else emptyList() } } override fun getContributedVariables(name: Name, location: LookupLocation): Collection<PropertyDescriptor> { return contextScope.collectVariables(name, location).flatMap { if (it is PropertyDescriptor && it.isExtension) it.substituteExtensionIfCallable( receiverTypes, CallType.DOT ) else emptyList() } } override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = null override fun getContributedDescriptors( kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean ): Collection<DeclarationDescriptor> { if (DescriptorKindExclude.Extensions in kindFilter.excludes) return emptyList() return contextScope.collectDescriptorsFiltered( kindFilter exclude DescriptorKindExclude.NonExtensions, nameFilter, changeNamesForAliased = true ).flatMap { if (it is CallableDescriptor && it.isExtension) it.substituteExtensionIfCallable( receiverTypes, CallType.DOT ) else emptyList() } } override fun getFunctionNames(): Set<Name> = getContributedDescriptors(kindFilter = DescriptorKindFilter.FUNCTIONS).map { it.name }.toSet() override fun getVariableNames(): Set<Name> = getContributedDescriptors(kindFilter = DescriptorKindFilter.VARIABLES).map { it.name }.toSet() override fun getClassifierNames() = null override fun printScopeStructure(p: Printer) { p.println("Extensions for ${receiverClass.name} in:") contextScope.printStructure(p) } }
apache-2.0
0fe3786efe78805ebf6f62c57b70ee57
42.985915
158
0.746077
5.685935
false
false
false
false
LateNightProductions/CardKeeper
app/src/main/java/com/awscherb/cardkeeper/util/behavior/AutoCloseBottomSheetBehavior.kt
1
1036
package com.awscherb.cardkeeper.util.behavior import android.content.Context import android.graphics.Rect import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import com.awscherb.cardkeeper.util.extensions.collapse import com.google.android.material.bottomsheet.BottomSheetBehavior class AutoCloseBottomSheetBehavior<V : View>(context: Context, attrs: AttributeSet) : BottomSheetBehavior<V>(context, attrs) { override fun onInterceptTouchEvent( parent: CoordinatorLayout, child: V, event: MotionEvent ): Boolean { if (event.action == MotionEvent.ACTION_DOWN && state == BottomSheetBehavior.STATE_EXPANDED) { val outRect = Rect() child.getGlobalVisibleRect(outRect) if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) { collapse() } } return super.onInterceptTouchEvent(parent, child, event) } }
apache-2.0
8b0b2cdd2a31cc1bdb3abce6b57a1a58
30.424242
101
0.710425
4.709091
false
false
false
false
vovagrechka/fucking-everything
aplight/src/main/java/aplight/GenerateTypeScriptFromKotlin2.kt
1
4780
package aplight import fuckotlin.psi.* import kotlinx.coroutines.experimental.* import vgrechka.* import java.io.File class GenerateTypeScriptFromKotlin2( val host: ApLight, val inputFilePath: String, val outputFilePath: String, val rootObjectName: String, val rootNamespace: String) { fun schedule() = CodeGen.scheduleJob { val spitPromises = listOf(spitConsts()/*, spitRemoteProcedures()*/) val out = OutLines() outGeneratedFileHeader(out) spitPromises.forEach {it.await()(out)} File(outputFilePath).writeText(out.reify()) } fun spitConsts(): SpitSomeCodePromise { val inputFile = File(inputFilePath) val ktFilesPromise = CodeGen.requestKotlinFilesParsing(l(inputFile)) return async { val ktFiles = ktFilesPromise.await() fun(out: OutLines) { clog("Spitting back-to-front consts: ${inputFile.parentFile.name}/${inputFile.name}") for (ktFile in ktFiles) { for (child in ktFile.children) { (child as? KtObjectDeclaration)?.let {ktObject-> if (ktObject.name == rootObjectName) { messWithConstObject(out, ktObject) } } } } } } } private fun messWithConstObject(out: OutLines, ktObject: KtObjectDeclaration, level: Int = 0) { val indent = " ".repeat(level * 4) if (level == 0) out.ln() when { level == 0 -> out.ln("${indent}declare namespace $rootNamespace.${ktObject.name} {") else -> out.ln("${indent}namespace ${ktObject.name} {")} ktObject.getBody()?.let {ktBody-> for (child in ktBody.children) { (child as? KtProperty)?.let {ktProperty-> out.ln("$indent const ${ktProperty.name}: " + when (ktProperty.typeReference?.text) { "Int" -> "number" "Boolean" -> "boolean" else -> "string" }) } (child as? KtObjectDeclaration)?.let {ktSubObject-> messWithConstObject(out, ktSubObject, level + 1) } } } out.ln(indent + "}") } fun spitRemoteProcedures(): SpitSomeCodePromise { val dir = File(host.alraune + "/alraune/src/main/java/alraune").also {check(it.isDirectory)} val files = dir.listFiles {_, name -> name.startsWith("RP_") && name.endsWith(".kt")}.toList() val ktFilesPromise = CodeGen.requestKotlinFilesParsing(files) return async { val ktFiles = ktFilesPromise.await() fun(out: OutLines) { out.ln() out.ln("export namespace RPC {") for (ktFile in ktFiles) { clog("Spitting RP stubs for ${ktFile.name}") for (child in ktFile.children) { if (child is KtClass && child.name?.startsWith("RP_") == true) { val rpClass = child out.ln() val procName = rpClass.name!!.substring("RP_".length) out.ln(" export function $procName\$(args: {") val rpBody = rpClass.getBody()!! val paramsClass = rpBody.children.find {it is KtClass && it.name == "Params"} as KtClass paramsClass.getBody()?.let {paramsBody-> for (child3 in paramsBody.children) { if (child3 is KtProperty) { val prop = child3 val debugContextDesc = "rpClass.fqName = ${rpClass.fqName}; prop.name = ${prop.name}" val ktTypeName = ApLight.guessTypeName(prop, debugContextDesc) val tsTypeName = when (ktTypeName) { "String" -> "string" else -> wtf("ktTypeName = $ktTypeName") } out.ln(" ${prop.name}: $tsTypeName,") } } } out.ln(" }) {callRemoteProcedure\$({name: '$procName', args})}") } } } out.ln("}") // namespace } } } }
apache-2.0
0bf22e0144a4f717b2804193527a0474
36.054264
125
0.462762
5.112299
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/utils/EthernetUtils.kt
2
932
package com.github.kerubistan.kerub.utils import com.github.kerubistan.kerub.utils.junix.sysfs.Net fun stringToMac(strMac: String): ByteArray { val bytes = strMac.trim().split(':') require(bytes.size == Net.macAddressSize) { "The MAC address must be 6 bytes" } return bytes .map { require(it.length <= 2) { "Maximum two hexadecimal digits needed" } Integer.parseInt(it, Net.hexaDecimal).toByte() } .toByteArray() } val hexaDigits = arrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') fun macToString(mac: ByteArray): String { require(mac.size == Net.macAddressSize) { "The MAC address must be 6 bytes" } return buildString(17) { for (b in mac) { if (length != 0) { append(':') } java.lang.Byte.toUnsignedInt(b) append(hexaDigits[java.lang.Byte.toUnsignedInt(b) and 0xF0 ushr 4]) append(hexaDigits[java.lang.Byte.toUnsignedInt(b) and 0x0F]) } } }
apache-2.0
d0f1448fb832ba4e8083d7871da956e8
30.066667
104
0.651288
2.850153
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/tests/testData/basic/codeFragments/runtimeType/smartCompletion.kt
13
1127
fun main(args: Array<String>) { val b: Base = Derived() <caret>val a = 1 } open class Base { fun funInBase(): Int = 0 open fun funWithOverride(): Int = 0 open fun funWithoutOverride(): Int = 0 fun funInBoth(): Int = 0 } open class Intermediate : Base() { fun funInIntermediate() = 0 } class Derived : Intermediate() { fun funInDerived(): Int = 0 override fun funWithOverride(): Int = 0 fun funInBoth(p: Int): Int = 0 fun funWrongType(): String = "" } // COMPLETION_TYPE: SMART // INVOCATION_COUNT: 1 // EXIST: { itemText: "funInBase", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funWithOverride", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funWithoutOverride", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funInDerived", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funInBoth", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funInBoth", tailText: "(p: Int)", attributes: "bold" } // EXIST: { itemText: "funInIntermediate", tailText: "()", attributes: "" } // NOTHING_ELSE // RUNTIME_TYPE: Derived
apache-2.0
f15e62c8959e0d8e173de8ebc03c6792
26.512195
80
0.625555
3.659091
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/NodeKind.kt
3
7197
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION", "NOTHING_TO_INLINE") package androidx.compose.ui.node import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.DrawModifier import androidx.compose.ui.focus.FocusOrderModifier import androidx.compose.ui.input.pointer.PointerInputModifier import androidx.compose.ui.layout.IntermediateLayoutModifier import androidx.compose.ui.layout.LayoutModifier import androidx.compose.ui.layout.LookaheadOnPlacedModifier import androidx.compose.ui.layout.OnGloballyPositionedModifier import androidx.compose.ui.layout.OnPlacedModifier import androidx.compose.ui.layout.OnRemeasuredModifier import androidx.compose.ui.layout.ParentDataModifier import androidx.compose.ui.modifier.ModifierLocalConsumer import androidx.compose.ui.modifier.ModifierLocalNode import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.semantics.SemanticsModifier @JvmInline internal value class NodeKind<T>(val mask: Int) { inline infix fun or(other: NodeKind<*>): Int = mask or other.mask inline infix fun or(other: Int): Int = mask or other } internal inline infix fun Int.or(other: NodeKind<*>): Int = this or other.mask // For a given NodeCoordinator, the "LayoutAware" nodes that it is concerned with should include // its own measureNode if the measureNode happens to implement LayoutAware. If the measureNode // implements any other node interfaces, such as draw, those should be visited by the coordinator // below them. @OptIn(ExperimentalComposeUiApi::class) internal val NodeKind<*>.includeSelfInTraversal: Boolean get() { return mask and Nodes.LayoutAware.mask != 0 } // Note that these don't inherit from Modifier.Node to allow for a single Modifier.Node // instance to implement multiple Node interfaces @OptIn(ExperimentalComposeUiApi::class) internal object Nodes { @JvmStatic inline val Any get() = NodeKind<Modifier.Node>(0b1 shl 0) @JvmStatic inline val Layout get() = NodeKind<LayoutModifierNode>(0b1 shl 1) @JvmStatic inline val Draw get() = NodeKind<DrawModifierNode>(0b1 shl 2) @JvmStatic inline val Semantics get() = NodeKind<SemanticsModifierNode>(0b1 shl 3) @JvmStatic inline val PointerInput get() = NodeKind<PointerInputModifierNode>(0b1 shl 4) @JvmStatic inline val Locals get() = NodeKind<ModifierLocalNode>(0b1 shl 5) @JvmStatic inline val ParentData get() = NodeKind<ParentDataModifierNode>(0b1 shl 6) @JvmStatic inline val LayoutAware get() = NodeKind<LayoutAwareModifierNode>(0b1 shl 7) @JvmStatic inline val GlobalPositionAware get() = NodeKind<GlobalPositionAwareModifierNode>(0b1 shl 8) @JvmStatic inline val IntermediateMeasure get() = NodeKind<IntermediateLayoutModifierNode>(0b1 shl 9) // ... } @OptIn(ExperimentalComposeUiApi::class) internal fun calculateNodeKindSetFrom(element: Modifier.Element): Int { var mask = Nodes.Any.mask if (element is LayoutModifier) { mask = mask or Nodes.Layout } @OptIn(ExperimentalComposeUiApi::class) if (element is IntermediateLayoutModifier) { mask = mask or Nodes.IntermediateMeasure } if (element is DrawModifier) { mask = mask or Nodes.Draw } if (element is SemanticsModifier) { mask = mask or Nodes.Semantics } if (element is PointerInputModifier) { mask = mask or Nodes.PointerInput } if ( element is ModifierLocalConsumer || element is ModifierLocalProvider<*> || // Special handling for FocusOrderModifier -- we have to use modifier local // consumers and providers for it. element is FocusOrderModifier ) { mask = mask or Nodes.Locals } if (element is OnGloballyPositionedModifier) { mask = mask or Nodes.GlobalPositionAware } if (element is ParentDataModifier) { mask = mask or Nodes.ParentData } if ( element is OnPlacedModifier || element is OnRemeasuredModifier || element is LookaheadOnPlacedModifier ) { mask = mask or Nodes.LayoutAware } return mask } @OptIn(ExperimentalComposeUiApi::class) internal fun calculateNodeKindSetFrom(node: Modifier.Node): Int { var mask = Nodes.Any.mask if (node is LayoutModifierNode) { mask = mask or Nodes.Layout } if (node is DrawModifierNode) { mask = mask or Nodes.Draw } if (node is SemanticsModifierNode) { mask = mask or Nodes.Semantics } if (node is PointerInputModifierNode) { mask = mask or Nodes.PointerInput } if (node is ModifierLocalNode) { mask = mask or Nodes.Locals } if (node is ParentDataModifierNode) { mask = mask or Nodes.ParentData } if (node is LayoutAwareModifierNode) { mask = mask or Nodes.LayoutAware } if (node is GlobalPositionAwareModifierNode) { mask = mask or Nodes.GlobalPositionAware } if (node is IntermediateLayoutModifierNode) { mask = mask or Nodes.IntermediateMeasure } return mask } private const val Updated = 0 private const val Inserted = 1 private const val Removed = 2 @OptIn(ExperimentalComposeUiApi::class) internal fun autoInvalidateRemovedNode(node: Modifier.Node) = autoInvalidateNode(node, Removed) @OptIn(ExperimentalComposeUiApi::class) internal fun autoInvalidateInsertedNode(node: Modifier.Node) = autoInvalidateNode(node, Inserted) @OptIn(ExperimentalComposeUiApi::class) internal fun autoInvalidateUpdatedNode(node: Modifier.Node) = autoInvalidateNode(node, Updated) @OptIn(ExperimentalComposeUiApi::class) private fun autoInvalidateNode(node: Modifier.Node, phase: Int) { if (node.isKind(Nodes.Layout) && node is LayoutModifierNode) { node.invalidateMeasurements() if (phase == Removed) { val coordinator = node.requireCoordinator(Nodes.Layout) val layer = coordinator.layer if (layer != null) { coordinator.onLayerBlockUpdated(null) } } } if (node.isKind(Nodes.GlobalPositionAware) && node is GlobalPositionAwareModifierNode) { node.requireLayoutNode().invalidateMeasurements() } if (node.isKind(Nodes.Draw) && node is DrawModifierNode) { node.invalidateDraw() } if (node.isKind(Nodes.Semantics) && node is SemanticsModifierNode) { node.invalidateSemantics() } if (node.isKind(Nodes.ParentData) && node is ParentDataModifierNode) { node.invalidateParentData() } }
apache-2.0
79057a4f3f8c1f84c857ebadc0d1d0a6
35.912821
97
0.722801
4.401835
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/operations/RewardDatabaseOperations.kt
1
11492
/* * Copyright 2020 Google 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.app.playhvz.firebase.operations import android.util.Log import com.app.playhvz.firebase.classmodels.Reward import com.app.playhvz.firebase.constants.RewardPath import com.app.playhvz.firebase.firebaseprovider.FirebaseProvider import com.app.playhvz.firebase.utils.FirebaseDatabaseUtil import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.json.JSONArray class RewardDatabaseOperations { companion object { private val TAG = RewardDatabaseOperations::class.qualifiedName /** Returns a collection reference to the given chatRoomId. */ fun getRewardCollectionReference( gameId: String ): CollectionReference { return RewardPath.REWARD_COLLECTION(gameId) } /** Returns a document reference to the given rewardId. */ fun getRewardDocumentReference( gameId: String, rewardId: String ): DocumentReference { return RewardPath.REWARD_DOCUMENT_REFERENCE(gameId, rewardId) } fun getRewardDocument( gameId: String, rewardId: String, onSuccessListener: OnSuccessListener<DocumentSnapshot> ) { FirebaseDatabaseUtil.optimizedGet( RewardPath.REWARD_DOCUMENT_REFERENCE( gameId, rewardId ), onSuccessListener ) } /** Create Reward. */ suspend fun asyncCreateReward( gameId: String, rewardDraft: Reward, successListener: () -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "shortName" to rewardDraft.shortName, "longName" to rewardDraft.longName, "description" to rewardDraft.description, "imageUrl" to rewardDraft.imageUrl, "points" to rewardDraft.points ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("createReward") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Failed to create reward: " + task.exception) failureListener.invoke() return@continueWith } successListener.invoke() } } /** Update Reward. */ suspend fun asyncUpdateReward( gameId: String, rewardDraft: Reward, successListener: () -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "rewardId" to rewardDraft.id, "longName" to rewardDraft.longName, "description" to rewardDraft.description, "imageUrl" to rewardDraft.imageUrl, "points" to rewardDraft.points ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("updateReward") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Failed to update reward: " + task.exception) failureListener.invoke() return@continueWith } successListener.invoke() } } /** Generate claim codes for the reward. */ suspend fun asyncGenerateClaimCodes( gameId: String, rewardId: String, numCodes: Int, successListener: () -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "rewardId" to rewardId, "numCodes" to numCodes ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("generateClaimCodes") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Failed to generate claim codes: " + task.exception) failureListener.invoke() return@continueWith } successListener.invoke() } } /** Generate claim codes for the reward. */ suspend fun asyncGetCurrentClaimCodeCount( gameId: String, rewardId: String, successListener: (unusedCount: Int, total: Int) -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "rewardId" to rewardId ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("getRewardClaimedStats") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Failed to get claim code count: " + task.exception) failureListener.invoke() return@continueWith } if (task.result != null) { val resultMap = task.result!!.data as Map<*, *> val unusedCount = resultMap["unusedCount"] as Int val usedCount = resultMap["usedCount"] as Int successListener.invoke(unusedCount, unusedCount + usedCount) } } } /** Gets available claim codes for the reward. */ suspend fun asyncGetAvailableClaimCodes( gameId: String, rewardId: String, successListener: (codes: Array<String>) -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "rewardId" to rewardId ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("getAvailableClaimCodes") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Failed to get claim codes: " + task.exception) failureListener.invoke() return@continueWith } if (task.result != null) { val claimCodes: MutableList<String> = mutableListOf() try { val resultMap = task.result!!.data as Map<*, *> val claimCodesJsonArray = JSONArray(resultMap["claimCodes"] as String) for (i in 0 until claimCodesJsonArray.length()) { claimCodes.add(claimCodesJsonArray.getString(i)) } } finally { successListener.invoke(claimCodes.toTypedArray()) } } } } /** Gets available rewards by name. */ suspend fun asyncGetRewardsByName( gameId: String, successListener: (rewards: Map<String, String>) -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("getRewardsByName") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Failed to get rewards by name: " + task.exception) failureListener.invoke() return@continueWith } if (task.result != null) { val rewards: MutableMap<String, String> = mutableMapOf() try { val resultMap = task.result!!.data as Map<*, *> val rewardJsonArray = JSONArray(resultMap["rewards"] as String) for (i in 0 until rewardJsonArray.length()) { val itemArray = rewardJsonArray.getJSONArray(i) rewards[itemArray.getString(0)] = itemArray.getString(1) } } finally { successListener.invoke(rewards) } } } } /** Redeems a given reward code. */ suspend fun redeemClaimCode( gameId: String, playerId: String, claimCode: String, successListener: () -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "playerId" to playerId, "claimCode" to claimCode ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("redeemRewardCode") .call(data) .continueWith { task -> if (!task.isSuccessful) { Log.e(TAG, "Could not redeem reward code: ${task.exception}") failureListener.invoke() return@continueWith } successListener.invoke() } } /** Permanently deletes reward. */ /* suspend fun asyncDeleteReward( gameId: String, rewardId: String, successListener: () -> Unit, failureListener: () -> Unit ) = withContext(Dispatchers.Default) { val data = hashMapOf( "gameId" to gameId, "rewardId" to rewardId ) FirebaseProvider.getFirebaseFunctions() .getHttpsCallable("deleteReward") .call(data) .continueWith { task -> if (!task.isSuccessful) { failureListener.invoke() return@continueWith } successListener.invoke() } } */ } }
apache-2.0
edc12b8bdb79faf6b367f534ba676cdf
37.959322
98
0.509485
5.703226
false
false
false
false
androidx/androidx
compose/material/material/src/androidAndroidTest/kotlin/androidx/compose/material/SwipeableTest.kt
3
57644
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.ScrollState import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.InspectableValue import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.platform.isDebugInspectorInfoEnabled import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipe import androidx.compose.ui.test.swipeWithVelocity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CancellationException import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlin.math.sign @MediumTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalMaterialApi::class) class SwipeableTest { @get:Rule val rule = createComposeRule() private val swipeableTag = "swipeableTag" @Before fun init() { isDebugInspectorInfoEnabled = true } @After fun after() { isDebugInspectorInfoEnabled = false } /** * Tests that [swipeable] detects horizontal swipes and ignores vertical swipes. */ @Test fun swipeable_horizontalSwipe() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") } swipeLeft() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeDown() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeUp() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that [swipeable] detects vertical swipes and ignores horizontal swipes. */ @Test fun swipeable_verticalSwipe() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Vertical ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeDown() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") } swipeUp() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeLeft() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that [swipeable] ignores horizontal swipes. */ @Test fun swipeable_disabled_horizontal() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal, enabled = false ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeLeft() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that [swipeable] ignores vertical swipes. */ @Test fun swipeable_disabled_vertical() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Vertical, enabled = false ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeDown() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeUp() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that [swipeable] reverses the direction of horizontal swipes. */ @Test fun swipeable_reverseDirection_horizontal() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal, reverseDirection = true ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeLeft() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") } swipeRight() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that [swipeable] reverses the direction of vertical swipes. */ @Test fun swipeable_reverseDirection_vertical() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Vertical, reverseDirection = true ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeDown() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeUp() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") } swipeDown() advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that the state and offset of [swipeable] are updated when swiping. */ @Test fun swipeable_updatedWhenSwiping() { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.offset.value).isEqualTo(0f) } swipeRight() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.offset.value).isNonZero() assertThat(state.offset.value).isLessThan(100f) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.offset.value).isEqualTo(100f) } swipeLeft() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.offset.value).isNonZero() assertThat(state.offset.value).isLessThan(100f) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.offset.value).isEqualTo(0f) } } /** * Tests that fixed thresholds work correctly. */ @Test @LargeTest fun swipeable_thresholds_fixed_small() = runBlocking(AutoTestFrameClock()) { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> val offsetDp = with(rule.density) { 35.toDp() } setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FixedThreshold(offsetDp) }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 35f val thresholdBtoA = 65f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that fixed thresholds work correctly. */ @Test @LargeTest fun swipeable_thresholds_fixed_large() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> val offsetDp = with(rule.density) { 65.toDp() } setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FixedThreshold(offsetDp) }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 65f val thresholdBtoA = 35f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that fractional thresholds work correctly. */ @Test @LargeTest fun swipeable_thresholds_fractional_half() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 50f val thresholdBtoA = 50f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that fractional thresholds work correctly. */ @Test @LargeTest fun swipeable_thresholds_fractional_quarter() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.25f) }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 25f val thresholdBtoA = 75f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that fractional thresholds work correctly. */ @Test @LargeTest fun swipeable_thresholds_fractional_threeQuarters() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.75f) }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 75f val thresholdBtoA = 25f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that mixing fixed and fractional thresholds works correctly. */ @Test @LargeTest fun swipeable_thresholds_mixed() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> val offsetDp = with(rule.density) { 35.toDp() } setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { from, to -> if (from < to) { FixedThreshold(offsetDp) } else { FractionalThreshold(0.75f) } }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 35f val thresholdBtoA = 25f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that a custom implementation of [ThresholdConfig] works correctly. */ @Test @LargeTest fun swipeable_thresholds_custom() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> object : ThresholdConfig { override fun Density.computeThreshold( fromValue: Float, toValue: Float ): Float { return 40 + 5 * sign(toValue - fromValue) } } }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } val thresholdAtoB = 45f val thresholdBtoA = 35f for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value >= thresholdAtoB } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "B" else "A") } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val passedThreshold = rule.runOnIdle { state.offset.value <= thresholdBtoA } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(if (passedThreshold) "A" else "B") } } } /** * Tests that the velocity threshold works correctly. */ @Test fun swipeable_velocityThreshold() { lateinit var state: SwipeableState<String> val velocityThresholdDp = with(rule.density) { 500.toDp() } setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(1f) }, orientation = Orientation.Horizontal, velocityThreshold = velocityThresholdDp ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight(velocity = 499f) advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight(velocity = 501f) advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") } swipeLeft(velocity = 499f) advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") } swipeLeft(velocity = 501f) advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } } /** * Tests that [swipeable] will animate to a neighbouring state, after a high-velocity swipe. */ @Test fun swipeable_cannotSkipStatesByFlinging() { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B", 200f to "C"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") } swipeRight(velocity = 1000f) advanceClock() rule.runOnIdle { assertThat(state.currentValue).isNotEqualTo("C") } } /** * Tests that the overflow is updated when swiping past the bounds. */ @Test fun swipeable_overflow() { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal, resistance = null ) } rule.runOnIdle { assertThat(state.offset.value).isEqualTo(0f) assertThat(state.overflow.value).isEqualTo(0f) } swipeRight() rule.runOnIdle { assertThat(state.offset.value).isZero() assertThat(state.overflow.value).isGreaterThan(0f) } advanceClock() rule.runOnIdle { assertThat(state.offset.value).isEqualTo(0f) assertThat(state.overflow.value).isEqualTo(0f) } swipeLeft() rule.runOnIdle { assertThat(state.offset.value).isZero() assertThat(state.overflow.value).isLessThan(0f) } advanceClock() rule.runOnIdle { assertThat(state.offset.value).isEqualTo(0f) assertThat(state.overflow.value).isEqualTo(0f) } } /** * Tests that resistance is applied correctly when swiping past the min bound. */ @Test fun swipeable_resistance_atMinBound() { lateinit var state: SwipeableState<String> val resistance = ResistanceConfig(100f, 5f, 0f) setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal, resistance = resistance ) } swipeLeft() rule.runOnIdle { assertThat(state.offset.value).isEqualTo( resistance.computeResistance(state.overflow.value) ) } advanceClock() rule.runOnIdle { assertThat(state.offset.value).isEqualTo(0f) } } /** * Tests that resistance is applied correctly when swiping past the max bound. */ @Test fun swipeable_resistance_atMaxBound() { lateinit var state: SwipeableState<String> val resistance = ResistanceConfig(100f, 0f, 5f) setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal, resistance = resistance ) } swipeRight() rule.runOnIdle { assertThat(state.offset.value).isEqualTo( resistance.computeResistance(state.overflow.value) ) } advanceClock() rule.runOnIdle { assertThat(state.offset.value).isEqualTo(0f) } } /** * Tests that the target works correctly. */ @Test @LargeTest fun swipeable_targetValue() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal, velocityThreshold = Dp.Infinity ) } for (i in 0..10) { state.snapTo("A") swipeRight(offset = 50f + i * 10f) val target = rule.runOnIdle { state.targetValue } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(target) } } for (i in 0..10) { state.snapTo("B") swipeLeft(offset = 50f + i * 10f) val target = rule.runOnIdle { state.targetValue } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo(target) } } } /** * Tests that the progress works correctly. */ @Test fun swipeable_progress() { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.progress.from).isEqualTo("A") assertThat(state.progress.to).isEqualTo("A") assertThat(state.progress.fraction).isEqualTo(1f) } swipeRight() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.progress.from).isEqualTo("A") assertThat(state.progress.to).isEqualTo("B") assertThat(state.progress.fraction).isEqualTo(state.offset.value / 100) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.progress.from).isEqualTo("B") assertThat(state.progress.to).isEqualTo("B") assertThat(state.progress.fraction).isEqualTo(1f) } swipeLeft() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.progress.from).isEqualTo("B") assertThat(state.progress.to).isEqualTo("A") assertThat(state.progress.fraction).isEqualTo((100 - state.offset.value) / 100) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.progress.from).isEqualTo("A") assertThat(state.progress.to).isEqualTo("A") assertThat(state.progress.fraction).isEqualTo(1f) } } /** * Tests that the direction works correctly. */ @Test fun swipeable_direction() { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.direction).isEqualTo(0f) } swipeRight() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.direction).isEqualTo(1f) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.direction).isEqualTo(0f) } swipeLeft() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.direction).isEqualTo(-1f) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.direction).isEqualTo(0f) } } /** * Tests that the progress works correctly, after a swipe was in the opposite direction. */ @Test fun swipeable_progress_multipleSwipes() { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> var slop = 0f setSwipeableContent { state = rememberSwipeableState("A") slop = LocalViewConfiguration.current.touchSlop Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.progress.from).isEqualTo("A") assertThat(state.progress.to).isEqualTo("A") assertThat(state.progress.fraction).isEqualTo(1f) } rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center + Offset(125f - slop, 0f)) } rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center - Offset(25f, 0f)) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.progress.from).isEqualTo("A") assertThat(state.progress.to).isEqualTo("B") assertThat(state.progress.fraction).isEqualTo(state.offset.value / 100) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.progress.from).isEqualTo("B") assertThat(state.progress.to).isEqualTo("B") assertThat(state.progress.fraction).isEqualTo(1f) } rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center - Offset(125f - slop, 0f)) } rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center + Offset(25f, 0f)) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.progress.from).isEqualTo("B") assertThat(state.progress.to).isEqualTo("A") assertThat(state.progress.fraction).isWithin(1e-6f).of(1 - state.offset.value / 100) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.progress.from).isEqualTo("A") assertThat(state.progress.to).isEqualTo("A") assertThat(state.progress.fraction).isEqualTo(1f) } } /** * Tests that the direction works correctly, after a swipe was in the opposite direction. */ @Test fun swipeable_direction_multipleSwipes() { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> var slop = 0f setSwipeableContent { state = rememberSwipeableState("A") slop = LocalViewConfiguration.current.touchSlop Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.direction).isEqualTo(0f) } val largeSwipe = with(rule.density) { 125.dp.toPx() + slop } val smallSwipe = with(rule.density) { 25.dp.toPx() + slop } rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center + Offset(largeSwipe, 0f)) } // draggable needs to recompose to toggle startDragImmediately rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center - Offset(smallSwipe, 0f)) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.direction).isEqualTo(1f) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.direction).isEqualTo(0f) } rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center - Offset(largeSwipe, 0f)) } // draggable needs to recompose to toggle startDragImmediately rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag(swipeableTag).performTouchInput { swipe(start = center, end = center + Offset(smallSwipe, 0f)) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.direction).isEqualTo(-1f) } advanceClock() rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.direction).isEqualTo(0f) } } /** * Tests that 'snapTo' updates the state and offset immediately. */ @Test fun swipeable_snapTo() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.currentValue).isEqualTo("A") assertThat(state.offset.value).isEqualTo(0f) } state.snapTo("B") rule.runOnIdle { assertThat(state.currentValue).isEqualTo("B") assertThat(state.offset.value).isEqualTo(100f) } } /** * Tests that 'animateTo' starts an animation which updates the state and offset. */ @Test fun swipeable_animateTo() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } assertThat(state.currentValue).isEqualTo("A") assertThat(state.offset.value).isEqualTo(0f) val job = launch { state.animateTo("B") } assertThat(state.currentValue).isEqualTo("A") assertThat(state.offset.value).isEqualTo(0f) job.join() assertThat(state.currentValue).isEqualTo("B") assertThat(state.offset.value).isEqualTo(100f) } /** * Tests that the 'onEnd' callback of 'animateTo' is invoked and with the correct end value. */ @Test fun swipeable_animateTo_onEnd() = runBlocking(AutoTestFrameClock()) { lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } var result: Boolean? try { state.animateTo("B") result = true } catch (c: CancellationException) { result = false } advanceClock() assertThat(result).isEqualTo(true) } /** * Tests that the 'onEnd' callback of 'animateTo' is invoked if the animation is interrupted. */ @Test @Ignore("couldn't come up with a meaningful test for now. restore in ") fun swipeable_animateTo_onEnd_interrupted() = runBlocking { rule.mainClock.autoAdvance = false lateinit var state: SwipeableState<String> setSwipeableContent { state = rememberSwipeableState("A") Modifier.swipeable( state = state, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } val job = async { state.animateTo("B") } rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag(swipeableTag).performTouchInput { down(center) up() } advanceClock() job.await() } /** * Tests that the [SwipeableState] is restored, when created with [rememberSwipeableState]. */ @Test fun swipeable_restoreSwipeableState() = runBlocking(AutoTestFrameClock()) { val restorationTester = StateRestorationTester(rule) var state: SwipeableState<String>? = null restorationTester.setContent { state = rememberSwipeableState("A") Box( Modifier.swipeable( state = state!!, anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) ) } state!!.animateTo("B") rule.runOnIdle { state = null } restorationTester.emulateSavedInstanceStateRestore() rule.runOnIdle { assertThat(state!!.currentValue).isEqualTo("B") } } /** * Tests that the `onValueChange` callback of [rememberSwipeableState] is invoked correctly. */ @Test fun swipeable_swipeableStateFor_onValueChange() { var onStateChangeCallbacks = 0 lateinit var state: MutableState<String> setSwipeableContent { state = remember { mutableStateOf("A") } Modifier.swipeable( state = rememberSwipeableStateFor( value = state.value, onValueChange = { onStateChangeCallbacks += 1 state.value = it } ), anchors = mapOf(0f to "A", 100f to "B"), thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(state.value).isEqualTo("A") assertThat(onStateChangeCallbacks).isEqualTo(0) } swipeRight() rule.runOnIdle { assertThat(state.value).isEqualTo("B") assertThat(onStateChangeCallbacks).isEqualTo(1) } } /** * Tests that the [SwipeableState] is updated if the anchors change. */ @Test fun swipeable_anchorsUpdated() { lateinit var swipeableState: SwipeableState<String> lateinit var anchors: MutableState<Map<Float, String>> setSwipeableContent { swipeableState = rememberSwipeableState("A") anchors = remember { mutableStateOf(mapOf(0f to "A")) } Modifier.swipeable( state = swipeableState, anchors = anchors.value, thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(swipeableState.offset.value).isEqualTo(0f) } anchors.value = mapOf(50f to "A") rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(swipeableState.offset.value).isEqualTo(50f) } } /** * Tests that the new [SwipeableState] `onValueChange` is set up if the anchors didn't change */ @Test fun swipeable_newStateIsInitialized_afterRecomposingWithOldAnchors() { lateinit var swipeableState: MutableState<SwipeableState<String>> val anchors = mapOf(0f to "A") setSwipeableContent { swipeableState = remember { mutableStateOf(SwipeableState("A")) } Modifier.swipeable( state = swipeableState.value, anchors = anchors, thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(swipeableState.value.currentValue).isEqualTo("A") assertThat(swipeableState.value.offset.value).isEqualTo(0f) assertThat(swipeableState.value.anchors).isEqualTo(anchors) } swipeableState.value = SwipeableState("A") rule.runOnIdle { assertThat(swipeableState.value.currentValue).isEqualTo("A") assertThat(swipeableState.value.offset.value).isEqualTo(0f) assertThat(swipeableState.value.anchors).isEqualTo(anchors) } } /** * Tests that the [SwipeableState] is updated if the anchors change. */ @Test fun swipeable_anchorsUpdated_currentAnchorRemoved() { lateinit var swipeableState: SwipeableState<String> lateinit var anchors: MutableState<Map<Float, String>> setSwipeableContent { swipeableState = rememberSwipeableState("A") anchors = remember { mutableStateOf(mapOf(0f to "A")) } Modifier.swipeable( state = swipeableState, anchors = anchors.value, thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(swipeableState.offset.value).isEqualTo(0f) } anchors.value = mapOf(50f to "B", 100f to "C") rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("B") assertThat(swipeableState.offset.value).isEqualTo(50f) } } /** * Tests that the [SwipeableState] is updated if the anchors change. */ @Test fun swipeable_anchorsUpdated_whenAnimationInProgress() = runBlocking(AutoTestFrameClock()) { rule.mainClock.autoAdvance = false lateinit var swipeableState: SwipeableState<String> lateinit var anchors: MutableState<Map<Float, String>> setSwipeableContent { swipeableState = rememberSwipeableState("A") anchors = remember { mutableStateOf(mapOf(10f to "A", 50f to "B", 100f to "C")) } Modifier.swipeable( state = swipeableState, anchors = anchors.value, thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(swipeableState.offset.value).isEqualTo(10f) } swipeableState.animateTo("B") rule.mainClock.advanceTimeByFrame() anchors.value = mapOf(10f to "A", 100f to "C") advanceClock() rule.runOnIdle { // closes wins assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(swipeableState.offset.value).isEqualTo(10f) } } @Test fun testInspectorValue() { val anchors = mapOf(0f to "A", 100f to "B") rule.setContent { val modifier = Modifier.swipeable( state = rememberSwipeableState("A"), anchors = anchors, orientation = Orientation.Horizontal ) as InspectableValue assertThat(modifier.nameFallback).isEqualTo("swipeable") assertThat(modifier.valueOverride).isNull() assertThat(modifier.inspectableElements.map { it.name }.asIterable()).containsExactly( "state", "anchors", "orientation", "enabled", "reverseDirection", "interactionSource", "thresholds", "resistance", "velocityThreshold" ) } } @Test fun swipeable_defaultVerticalNestedScrollConnection_nestedDrag() { lateinit var swipeableState: SwipeableState<String> lateinit var anchors: MutableState<Map<Float, String>> lateinit var scrollState: ScrollState rule.setContent { swipeableState = rememberSwipeableState("A") anchors = remember { mutableStateOf(mapOf(0f to "A", -1000f to "B")) } scrollState = rememberScrollState() Box( Modifier .size(300.dp) .nestedScroll(swipeableState.PreUpPostDownNestedScrollConnection) .swipeable( state = swipeableState, anchors = anchors.value, thresholds = { _, _ -> FractionalThreshold(0.5f) }, orientation = Orientation.Horizontal ) ) { Column( Modifier.fillMaxWidth().testTag(swipeableTag).verticalScroll(scrollState) ) { repeat(100) { Text(text = it.toString(), modifier = Modifier.requiredHeight(50.dp)) } } } } assertThat(swipeableState.currentValue).isEqualTo("A") rule.onNodeWithTag(swipeableTag) .performTouchInput { down(Offset(x = 10f, y = 10f)) moveBy(Offset(x = 0f, y = -1500f)) up() } advanceClock() assertThat(swipeableState.currentValue).isEqualTo("B") assertThat(scrollState.value).isGreaterThan(0) rule.onNodeWithTag(swipeableTag) .performTouchInput { down(Offset(x = 10f, y = 10f)) moveBy(Offset(x = 0f, y = 1500f)) up() } advanceClock() assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(scrollState.value).isEqualTo(0) } @Test fun swipeable_nestedScroll_preFling() { lateinit var swipeableState: SwipeableState<String> lateinit var anchors: MutableState<Map<Float, String>> lateinit var scrollState: ScrollState rule.setContent { swipeableState = rememberSwipeableState("A") anchors = remember { mutableStateOf(mapOf(0f to "A", -1000f to "B")) } scrollState = rememberScrollState() Box( Modifier .size(300.dp) .nestedScroll(swipeableState.PreUpPostDownNestedScrollConnection) .swipeable( state = swipeableState, anchors = anchors.value, thresholds = { _, _ -> FixedThreshold(56.dp) }, orientation = Orientation.Horizontal ) ) { Column( Modifier.fillMaxWidth().testTag(swipeableTag).verticalScroll(scrollState) ) { repeat(100) { Text(text = it.toString(), modifier = Modifier.requiredHeight(50.dp)) } } } } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") } rule.onNodeWithTag(swipeableTag) .performTouchInput { swipeWithVelocity( center, center.copy(y = centerY - 500, x = centerX), durationMillis = 50, endVelocity = 20000f ) } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("B") // should eat all velocity, no internal scroll assertThat(scrollState.value).isEqualTo(0) } rule.onNodeWithTag(swipeableTag) .performTouchInput { swipeWithVelocity( center, center.copy(y = centerY + 500, x = centerX), durationMillis = 50, endVelocity = 20000f ) } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(scrollState.value).isEqualTo(0) } } @Test fun swipeable_nestedScroll_postFlings() = runBlocking(AutoTestFrameClock()) { lateinit var swipeableState: SwipeableState<String> lateinit var anchors: MutableState<Map<Float, String>> lateinit var scrollState: ScrollState rule.setContent { swipeableState = rememberSwipeableState("B") anchors = remember { mutableStateOf(mapOf(0f to "A", -1000f to "B")) } scrollState = rememberScrollState(initial = 5000) Box( Modifier .size(300.dp) .nestedScroll(swipeableState.PreUpPostDownNestedScrollConnection) .swipeable( state = swipeableState, anchors = anchors.value, thresholds = { _, _ -> FixedThreshold(56.dp) }, orientation = Orientation.Horizontal ) ) { Column( Modifier.fillMaxWidth().testTag(swipeableTag).verticalScroll(scrollState) ) { repeat(100) { Text(text = it.toString(), modifier = Modifier.requiredHeight(50.dp)) } } } } rule.awaitIdle() assertThat(swipeableState.currentValue).isEqualTo("B") assertThat(scrollState.value).isEqualTo(5000) rule.onNodeWithTag(swipeableTag) .performTouchInput { // swipe less than scrollState.value but with velocity to test that backdrop won't // move when receives, because it's at anchor swipeWithVelocity( center, center.copy(y = centerY + 1500, x = centerX), durationMillis = 50, endVelocity = 20000f ) } rule.awaitIdle() assertThat(swipeableState.currentValue).isEqualTo("B") assertThat(scrollState.value).isEqualTo(0) // set value again to test overshoot scrollState.scrollBy(500f) rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("B") assertThat(scrollState.value).isEqualTo(500) } rule.onNodeWithTag(swipeableTag) .performTouchInput { // swipe more than scrollState.value so backdrop start receiving nested scroll swipeWithVelocity( center, center.copy(y = centerY + 1500, x = centerX), durationMillis = 50, endVelocity = 20000f ) } rule.runOnIdle { assertThat(swipeableState.currentValue).isEqualTo("A") assertThat(scrollState.value).isEqualTo(0) } } private fun swipeRight( offset: Float = 100f, velocity: Float? = null ) = performSwipe(x = offset, velocity = velocity) private fun swipeLeft( offset: Float = 100f, velocity: Float? = null ) = performSwipe(x = -offset, velocity = velocity) private fun swipeDown( offset: Float = 100f, velocity: Float? = null ) = performSwipe(y = offset, velocity = velocity) private fun swipeUp( offset: Float = 100f, velocity: Float? = null ) = performSwipe(y = -offset, velocity = velocity) private fun advanceClock() { rule.mainClock.advanceTimeBy(100_000L) } private fun performSwipe(x: Float = 0f, y: Float = 0f, velocity: Float? = null) { rule.onNodeWithTag(swipeableTag).performTouchInput { val start = Offset(center.x - x / 2, center.y - y / 2) val end = Offset(center.x + x / 2, center.y + y / 2) if (velocity == null) swipe(start, end) else swipeWithVelocity(start, end, velocity) } } private fun setSwipeableContent(swipeableFactory: @Composable () -> Modifier) { rule.setMaterialContent { Box(modifier = Modifier.fillMaxSize().testTag(swipeableTag).then(swipeableFactory())) } } }
apache-2.0
2349d9d14124ad6de42c51842daf64c7
29.809193
98
0.553796
4.948832
false
true
false
false
androidx/androidx
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/Configuration.kt
3
12793
/* * 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. */ @file:RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java package androidx.camera.camera2.pipe.compat import android.graphics.SurfaceTexture import android.hardware.camera2.params.OutputConfiguration import android.os.Build import android.util.Size import android.view.Surface import android.view.SurfaceHolder import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.CameraId import androidx.camera.camera2.pipe.OutputStream.DynamicRangeProfile import androidx.camera.camera2.pipe.OutputStream.MirrorMode import androidx.camera.camera2.pipe.OutputStream.OutputType import androidx.camera.camera2.pipe.OutputStream.StreamUseCase import androidx.camera.camera2.pipe.OutputStream.TimestampBase import androidx.camera.camera2.pipe.UnsafeWrapper import androidx.camera.camera2.pipe.compat.OutputConfigurationWrapper.Companion.SURFACE_GROUP_ID_NONE import androidx.camera.camera2.pipe.core.Log import androidx.camera.camera2.pipe.core.checkNOrHigher import androidx.camera.camera2.pipe.core.checkOOrHigher import androidx.camera.camera2.pipe.core.checkPOrHigher import java.util.concurrent.Executor import kotlin.reflect.KClass /** * A data class that mirrors the fields in [android.hardware.camera2.params.SessionConfiguration] so * that a real instance can be constructed when creating a * [android.hardware.camera2.CameraCaptureSession] on newer versions of the OS. */ internal data class SessionConfigData( val sessionType: Int, val inputConfiguration: InputConfigData?, val outputConfigurations: List<OutputConfigurationWrapper>, val executor: Executor, val stateCallback: CameraCaptureSessionWrapper.StateCallback, val sessionTemplateId: Int, val sessionParameters: Map<*, Any?> ) { companion object { /* NOTE: These must keep in sync with their SessionConfiguration values. */ const val SESSION_TYPE_REGULAR = 0 const val SESSION_TYPE_HIGH_SPEED = 1 } } /** * A data class that mirrors the fields in [android.hardware.camera2.params.InputConfiguration] so * that a real instance can be constructed when creating a * [android.hardware.camera2.CameraCaptureSession] on newer versions of the OS. */ internal data class InputConfigData( val width: Int, val height: Int, val format: Int ) /** * An interface for [OutputConfiguration] with minor modifications. * * The primary modifications to this class are to make it harder to accidentally changes things that * cannot be modified after the [android.hardware.camera2.CameraCaptureSession] has been created. * * [OutputConfiguration]'s are NOT immutable, and changing state of an [OutputConfiguration] may * require the CameraCaptureSession to be finalized or updated. */ internal interface OutputConfigurationWrapper : UnsafeWrapper { /** * This method will return null if the output configuration was created without a Surface, * and until addSurface is called for the first time. * * @see OutputConfiguration.getSurface */ val surface: Surface? /** * This method returns the current list of surfaces for this [OutputConfiguration]. Since the * [OutputConfiguration] is stateful, this value may change as a result of calling addSurface * or removeSurface. * * @see OutputConfiguration.getSurfaces */ val surfaces: List<Surface> /** @see OutputConfiguration.addSurface */ fun addSurface(surface: Surface) /** @see OutputConfiguration.removeSurface */ fun removeSurface(surface: Surface) /** @see OutputConfiguration.setPhysicalCameraId */ val physicalCameraId: CameraId? /** @see OutputConfiguration.enableSurfaceSharing */ val surfaceSharing: Boolean /** @see OutputConfiguration.getMaxSharedSurfaceCount */ val maxSharedSurfaceCount: Int /** @see OutputConfiguration.getSurfaceGroupId */ val surfaceGroupId: Int companion object { const val SURFACE_GROUP_ID_NONE = -1 } } @RequiresApi(24) internal class AndroidOutputConfiguration( private val output: OutputConfiguration, override val surfaceSharing: Boolean, override val maxSharedSurfaceCount: Int, override val physicalCameraId: CameraId? ) : OutputConfigurationWrapper { @RequiresApi(24) companion object { /** * Create and validate an OutputConfiguration for Camera2. null is returned when a * non-exceptional error is encountered when creating the OutputConfiguration. */ fun create( surface: Surface?, outputType: OutputType = OutputType.SURFACE, mirrorMode: MirrorMode? = null, timestampBase: TimestampBase? = null, dynamicRangeProfile: DynamicRangeProfile? = null, streamUseCase: StreamUseCase? = null, size: Size? = null, surfaceSharing: Boolean = false, surfaceGroupId: Int = SURFACE_GROUP_ID_NONE, physicalCameraId: CameraId? = null ): OutputConfigurationWrapper? { check(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) // Create the OutputConfiguration using the groupId via the constructor (if set) val configuration: OutputConfiguration if (outputType == OutputType.SURFACE) { check(surface != null) { "OutputConfigurations defined with ${OutputType.SURFACE} must provide a" "non-null surface!" } // OutputConfiguration will, on some OS versions, attempt to read the surface size // from the Surface object. If the Surface has been destroyed, this check will fail. // Because there's no way to cleanly synchronize and check the value, we catch the // exception for these cases. try { configuration = if (surfaceGroupId != SURFACE_GROUP_ID_NONE) { OutputConfiguration(surfaceGroupId, surface) } else { OutputConfiguration(surface) } } catch (e: Throwable) { Log.warn(e) { "Failed to create an OutputConfiguration for $surface!" } return null } } else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { throw IllegalStateException( "Deferred OutputConfigurations are not supported on API " + "${Build.VERSION.SDK_INT} (requires API ${Build.VERSION_CODES.O})" ) } check(size != null) { "Size must defined when creating a deferred OutputConfiguration." } val outputKlass = when (outputType) { OutputType.SURFACE_TEXTURE -> SurfaceTexture::class.java OutputType.SURFACE_VIEW -> SurfaceHolder::class.java OutputType.SURFACE -> throw IllegalStateException( "Unsupported OutputType: $outputType" ) } configuration = Api26Compat.newOutputConfiguration(size, outputKlass) } // Enable surface sharing, if set. if (surfaceSharing) { configuration.enableSurfaceSharingCompat() } // Pass along the physicalCameraId, if set. if (physicalCameraId != null) { configuration.setPhysicalCameraIdCompat(physicalCameraId) } if (mirrorMode != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Api33Compat.setMirrorMode(configuration, mirrorMode.value) } else { if (mirrorMode != MirrorMode.MIRROR_MODE_AUTO) { Log.warn { "Cannot set mirrorMode to a non-default value on API " + "${Build.VERSION.SDK_INT}. This may result in unexpected behavior. " + "Requested $mirrorMode" } } } } if (timestampBase != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Api33Compat.setTimestampBase(configuration, timestampBase.value) } else { if (timestampBase != TimestampBase.TIMESTAMP_BASE_DEFAULT) { Log.info { "The timestamp base on API ${Build.VERSION.SDK_INT} will " + "default to TIMESTAMP_BASE_DEFAULT, with which the camera device" + " adjusts timestamps based on the output target. " + "Requested $timestampBase" } } } } if (dynamicRangeProfile != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Api33Compat.setDynamicRangeProfile(configuration, dynamicRangeProfile.value) } else { if (dynamicRangeProfile != DynamicRangeProfile.STANDARD) { Log.warn { "Cannot set dynamicRangeProfile to a non-default value on API " + "${Build.VERSION.SDK_INT}. This may result in unexpected " + "behavior. Requested $dynamicRangeProfile" } } } } if (streamUseCase != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Api33Compat.setStreamUseCase(configuration, streamUseCase.value) } } // Create and return the Android return AndroidOutputConfiguration( configuration, surfaceSharing, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { Api28Compat.getMaxSharedSurfaceCount(configuration) } else { 1 }, physicalCameraId ) } private fun OutputConfiguration.enableSurfaceSharingCompat() { checkNOrHigher("surfaceSharing") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Api26Compat.enableSurfaceSharing(this) } } private fun OutputConfiguration.setPhysicalCameraIdCompat(physicalCameraId: CameraId) { checkPOrHigher("physicalCameraId") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { Api28Compat.setPhysicalCameraId(this, physicalCameraId.value) } } } override val surface: Surface? = output.surface override val surfaces: List<Surface> get() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return Api26Compat.getSurfaces(output) } // On older versions of the OS, only one surface is allowed, and if an output // configuration is in a deferred state it may not have a surface when it's first // created. return listOfNotNull(output.surface) } override fun addSurface(surface: Surface) { checkOOrHigher("addSurface") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Api26Compat.addSurfaces(output, surface) } } override fun removeSurface(surface: Surface) { checkPOrHigher("removeSurface") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { Api28Compat.removeSurface(output, surface) } } override val surfaceGroupId: Int get() = output.surfaceGroupId @Suppress("UNCHECKED_CAST") override fun <T : Any> unwrapAs(type: KClass<T>): T? = when (type) { OutputConfiguration::class -> output as T else -> null } override fun toString(): String = output.toString() }
apache-2.0
02e1908883dcb60f9aaa2c660c565535
39.356467
101
0.622215
4.958527
false
true
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/history/GitDetailsCollector.kt
2
6383
// 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 git4idea.history import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.Consumer import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogObjectsFactory import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.util.StopWatch import git4idea.GitCommit import git4idea.GitVcs import git4idea.commands.Git import git4idea.commands.GitLineHandler internal abstract class GitDetailsCollector<R : GitLogRecord, C : VcsCommitMetadata>(protected val project: Project, protected val root: VirtualFile, private val recordBuilder: GitLogRecordBuilder<R>) { private val vcs = GitVcs.getInstance(project) @Throws(VcsException::class) fun readFullDetails(commitConsumer: Consumer<in C>, requirements: GitCommitRequirements, lowPriorityProcess: Boolean, vararg parameters: String) { val configParameters = requirements.configParameters() val handler = GitLogUtil.createGitHandler(project, root, configParameters, lowPriorityProcess) readFullDetailsFromHandler(commitConsumer, handler, requirements, *parameters) } @Throws(VcsException::class) fun readFullDetailsForHashes(hashes: List<String>, requirements: GitCommitRequirements, lowPriorityProcess: Boolean, commitConsumer: Consumer<in C>) { if (hashes.isEmpty()) return val handler = GitLogUtil.createGitHandler(project, root, requirements.configParameters(), lowPriorityProcess) GitLogUtil.sendHashesToStdin(hashes, handler) readFullDetailsFromHandler(commitConsumer, handler, requirements, GitLogUtil.getNoWalkParameter(vcs), GitLogUtil.STDIN) } @Throws(VcsException::class) private fun readFullDetailsFromHandler(commitConsumer: Consumer<in C>, handler: GitLineHandler, requirements: GitCommitRequirements, vararg parameters: String) { val factory = GitLogUtil.getObjectsFactoryWithDisposeCheck(project) ?: return val commandParameters = ArrayUtil.mergeArrays(ArrayUtil.toStringArray(requirements.commandParameters()), *parameters) if (requirements.diffInMergeCommits == GitCommitRequirements.DiffInMergeCommits.DIFF_TO_PARENTS) { val consumer = { records: List<R> -> val firstRecord = records.first() val parents = firstRecord.parentsHashes if (parents.isEmpty() || parents.size == records.size) { commitConsumer.consume(createCommit(records, factory, requirements.diffRenameLimit)) } else { LOG.warn("Not enough records for commit ${firstRecord.hash} " + "expected ${parents.size} records, but got ${records.size}") } } val recordCollector = createRecordsCollector(consumer) readRecordsFromHandler(handler, recordCollector, *commandParameters) recordCollector.finish() } else { val consumer = Consumer<R> { record -> commitConsumer.consume(createCommit(mutableListOf(record), factory, requirements.diffRenameLimit)) } readRecordsFromHandler(handler, consumer, *commandParameters) } } @Throws(VcsException::class) private fun readRecordsFromHandler(handler: GitLineHandler, converter: Consumer<R>, vararg parameters: String) { val parser = GitLogParser(project, recordBuilder, GitLogParser.NameStatus.STATUS, *GitLogUtil.COMMIT_METADATA_OPTIONS) handler.setStdoutSuppressed(true) handler.addParameters(*parameters) handler.addParameters(parser.pretty, "--encoding=UTF-8") handler.addParameters("--name-status") handler.endOptions() val sw = StopWatch.start("loading details in [" + root.name + "]") val handlerListener = GitLogOutputSplitter(handler, parser, converter) Git.getInstance().runCommandWithoutCollectingOutput(handler).throwOnError() handlerListener.reportErrors() sw.report() } protected abstract fun createRecordsCollector(consumer: (List<R>) -> Unit): GitLogRecordCollector<R> protected abstract fun createCommit(records: List<R>, factory: VcsLogObjectsFactory, renameLimit: GitCommitRequirements.DiffRenameLimit): C companion object { private val LOG = Logger.getInstance(GitDetailsCollector::class.java) } } internal class GitFullDetailsCollector(project: Project, root: VirtualFile, recordBuilder: GitLogRecordBuilder<GitLogFullRecord>) : GitDetailsCollector<GitLogFullRecord, GitCommit>(project, root, recordBuilder) { internal constructor(project: Project, root: VirtualFile) : this(project, root, DefaultGitLogFullRecordBuilder()) override fun createCommit(records: List<GitLogFullRecord>, factory: VcsLogObjectsFactory, renameLimit: GitCommitRequirements.DiffRenameLimit): GitCommit { val record = records.last() val parents = record.parentsHashes.map { factory.createHash(it) } return GitCommit(project, HashImpl.build(record.hash), parents, record.commitTime, root, record.subject, factory.createUser(record.authorName, record.authorEmail), record.fullMessage, factory.createUser(record.committerName, record.committerEmail), record.authorTimeStamp, records.map { it.statusInfos } ) } override fun createRecordsCollector(consumer: (List<GitLogFullRecord>) -> Unit): GitLogRecordCollector<GitLogFullRecord> { return object : GitLogRecordCollector<GitLogFullRecord>(project, root, consumer) { override fun createEmptyCopy(r: GitLogFullRecord): GitLogFullRecord = GitLogFullRecord(r.options, listOf(), r.isSupportsRawBody) } } }
apache-2.0
136a801846c4902ff41965a8cf43884b
47
158
0.692934
4.975058
false
false
false
false
JetBrains/xodus
utils/src/main/kotlin/jetbrains/exodus/util/StringInterner.kt
1
2483
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.util import jetbrains.exodus.core.dataStructures.ConcurrentObjectCache import jetbrains.exodus.system.JVMConstants import kotlin.math.min class StringInterner private constructor(size: Int = INTERNER_SIZE) { private val cache: ConcurrentObjectCache<String, String> init { cache = ConcurrentObjectCache(size, NUMBER_OF_GENERATIONS) } fun doIntern(s: String?): String? { if (s == null || s.length > MAX_SIZE_OF_CACHED_STRING) return s val cached = cache.tryKey(s) if (cached != null) { return cached } val copy = if (JVMConstants.IS_JAVA8_OR_HIGHER) s else s + "" // to avoid large cached substrings cache.cacheObject(copy, copy) return copy } fun doIntern(builder: StringBuilder, maxLen: Int): String { val result = builder.toString() if (builder.length <= maxLen) { val cached = cache.tryKey(result) if (cached != null) { return cached } cache.cacheObject(result, result) } return result } companion object { private val NUMBER_OF_GENERATIONS = Integer.getInteger("exodus.util.stringInternerNumberOfGenerations", 5) private val MAX_SIZE_OF_CACHED_STRING = Integer.getInteger("exodus.util.stringInternerMaxEntrySize", 1000) private val INTERNER_SIZE = Integer.getInteger("exodus.util.stringInternerCacheSize", 15991 * NUMBER_OF_GENERATIONS) private val DEFAULT_INTERNER = StringInterner() @JvmStatic fun intern(s: String?) = DEFAULT_INTERNER.doIntern(s) @JvmStatic fun intern(builder: StringBuilder, maxLen: Int) = DEFAULT_INTERNER.doIntern(builder, min(maxLen, MAX_SIZE_OF_CACHED_STRING)) @JvmStatic fun newInterner(size: Int) = StringInterner(size) } }
apache-2.0
9b56261ab1dc32e3e73f73edf79f6537
34.985507
132
0.674587
4.194257
false
false
false
false
jwren/intellij-community
platform/remoteDev-util/src/com/intellij/remoteDev/downloader/ThinClientSessionInfoFetcher.kt
1
3277
package com.intellij.remoteDev.downloader import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.util.SystemInfo import com.intellij.remoteDev.connection.CodeWithMeSessionInfoProvider import com.intellij.remoteDev.connection.StunTurnServerInfo import com.intellij.util.io.HttpRequests import com.intellij.util.system.CpuArch import com.intellij.util.withFragment import org.jetbrains.annotations.ApiStatus import java.net.HttpURLConnection import java.net.URI /** * Lightweight implementation of LobbyServerAPI to avoid obfuscation issues */ @ApiStatus.Experimental object ThinClientSessionInfoFetcher { private val objectMapper = lazy { ObjectMapper() } fun getSessionUrl(joinLinkUrl: URI): CodeWithMeSessionInfoProvider { val url = createUrl(joinLinkUrl) val requestString = objectMapper.value.createObjectNode().apply { put("clientBuildNumber", currentBuildNumber()) put("clientPlatform", currentPlatform()) }.toPrettyString() return HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE) .throwStatusCodeException(false) .productNameAsUserAgent() .connect { request -> request.write(requestString) val connection = request.connection as HttpURLConnection val responseString = request.readString() if (connection.responseCode >= 400) { throw Exception("Request to $url failed with status code ${connection.responseCode}") } val sessionInfo = objectMapper.value.reader().readTree(responseString) return@connect object : CodeWithMeSessionInfoProvider { override val hostBuildNumber = sessionInfo["hostBuildNumber"].asText() override val compatibleClientName = sessionInfo["compatibleClientName"].asText() override val compatibleClientUrl = sessionInfo["compatibleClientUrl"].asText() override val compatibleJreName = sessionInfo["compatibleJreName"].asText() override val isUnattendedMode = false override val compatibleJreUrl = sessionInfo["compatibleJreUrl"].asText() override val hostFeaturesToEnable: Set<String> get() = throw UnsupportedOperationException("hostFeaturesToEnable field should not be used") override val stunTurnServers: List<StunTurnServerInfo> get() = throw UnsupportedOperationException("stunTurnServers field should not be used") override val downloadPgpPublicKeyUrl: String? = sessionInfo["downloadPgpPublicKeyUrl"]?.asText() } } } private fun createUrl(joinLinkUrl: URI): String { val baseLink = joinLinkUrl.withFragment(null).toString().trimEnd('/') return "$baseLink/info" } private fun currentBuildNumber(): String { return ApplicationInfo.getInstance().build.toString() } private fun currentPlatform(): String { return when { SystemInfo.isMac && CpuArch.isArm64() -> "osx-aarch64" SystemInfo.isMac && CpuArch.isIntel64() -> "osx-x64" SystemInfo.isLinux && CpuArch.isIntel64() -> "linux-x64" SystemInfo.isWindows && CpuArch.isIntel64() -> "windows-x64" else -> error("Unsupported OS type: ${SystemInfo.OS_NAME}, CpuArch: ${CpuArch.CURRENT}") } } }
apache-2.0
e3857e35c789f81e021855d93af4fac8
41.025641
106
0.732682
4.92042
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/ui/text/paragraph/TextParagraph.kt
2
3374
// 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.ide.ui.text.paragraph import com.intellij.ide.ui.text.parts.TextPart import com.intellij.ui.scale.JBUIScale import org.jetbrains.annotations.ApiStatus import javax.swing.JTextPane import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants /** * Single paragraph of the text inside [JTextPane]. The paragraph inserts the list of [textParts] to the [JTextPane] * and applies the formatting to the whole paragraph using [attributes]. * Inserts line break after the last text part. * The behaviour of inserting text parts can be modified by overriding [insertToDocument] and [insertTextPart] methods. */ @ApiStatus.Experimental @ApiStatus.Internal open class TextParagraph(val textParts: List<TextPart>) { private val unscaledAttributes: SimpleAttributeSet = SimpleAttributeSet().apply { StyleConstants.setRightIndent(this, NO_INDENT) StyleConstants.setLeftIndent(this, NO_INDENT) StyleConstants.setSpaceAbove(this, MEDIUM_INDENT) StyleConstants.setSpaceBelow(this, NO_INDENT) StyleConstants.setLineSpacing(this, 0.3f) } open val attributes: SimpleAttributeSet get() = SimpleAttributeSet().apply { val unscaled = unscaledAttributes StyleConstants.setRightIndent(this, JBUIScale.scale(StyleConstants.getRightIndent(unscaled))) StyleConstants.setLeftIndent(this, JBUIScale.scale(StyleConstants.getLeftIndent(unscaled))) StyleConstants.setSpaceAbove(this, JBUIScale.scale(StyleConstants.getSpaceAbove(unscaled))) StyleConstants.setSpaceBelow(this, JBUIScale.scale(StyleConstants.getSpaceBelow(unscaled))) StyleConstants.setLineSpacing(this, StyleConstants.getLineSpacing(unscaled)) } private val partRanges: MutableList<IntRange> = mutableListOf() fun editAttributes(edit: SimpleAttributeSet.() -> Unit): TextParagraph { unscaledAttributes.edit() return this } /** * Inserts this paragraph to the [textPane] from the given [startOffset] and adds line break at the end * @return current offset after adding the paragraph */ open fun insertToDocument(textPane: JTextPane, startOffset: Int, isLast: Boolean = false): Int { partRanges.clear() var curOffset = startOffset for (part in textParts) { val start = curOffset curOffset = insertTextPart(part, textPane, curOffset) partRanges.add(start until curOffset) } val curAttributes = attributes if (!isLast) { textPane.document.insertString(curOffset, "\n", curAttributes) curOffset++ } textPane.styledDocument.setParagraphAttributes(startOffset, curOffset - startOffset, curAttributes, true) return curOffset } protected open fun insertTextPart(textPart: TextPart, textPane: JTextPane, startOffset: Int): Int { return textPart.insertToTextPane(textPane, startOffset) } open fun findPartByOffset(offset: Int): Pair<TextPart, IntRange>? { val partInd = partRanges.indexOfFirst { offset in it } return if (partInd != -1) { textParts[partInd] to partRanges[partInd] } else null } companion object { const val NO_INDENT: Float = 0f const val SMALL_INDENT: Float = 4f const val MEDIUM_INDENT: Float = 8f const val BIG_INDENT: Float = 12f } }
apache-2.0
ac96058aa8b2fd566a196dfa57f09953
38.705882
120
0.749852
4.238693
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveWhenConditionFix.kt
4
1680
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.EditCommaSeparatedListHelper import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtWhenCondition import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs class RemoveWhenConditionFix(element: KtWhenCondition) : KotlinQuickFixAction<KtWhenCondition>(element) { override fun getFamilyName() = KotlinBundle.message("remove.condition") override fun getText() = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.let { EditCommaSeparatedListHelper.removeItem(it) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveWhenConditionFix? { if (diagnostic.factory != Errors.SENSELESS_NULL_IN_WHEN) return null val whenCondition = diagnostic.psiElement.getStrictParentOfType<KtWhenCondition>() ?: return null val conditions = whenCondition.parent.safeAs<KtWhenEntry>()?.conditions?.size ?: return null if (conditions < 2) return null return RemoveWhenConditionFix(whenCondition) } } }
apache-2.0
b7af31fb2a61ad62a4502da213b4a489
45.666667
158
0.771429
4.772727
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/check/EventsCheck.kt
1
2388
package com.cognifide.gradle.aem.common.instance.check import com.cognifide.gradle.aem.common.instance.service.osgi.byAgeMillis import com.cognifide.gradle.aem.common.instance.service.osgi.byTopics import com.cognifide.gradle.aem.common.instance.service.osgi.ignoreDetails import com.cognifide.gradle.aem.common.utils.shortenClass import java.util.concurrent.TimeUnit import org.apache.commons.lang3.StringUtils @Suppress("MagicNumber") class EventsCheck(group: CheckGroup) : DefaultCheck(group) { val unstableTopics = aem.obj.strings { convention(listOf( "org/osgi/framework/ServiceEvent/*", "org/osgi/framework/FrameworkEvent/*", "org/osgi/framework/BundleEvent/*" )) } val unstableAgeMillis = aem.obj.long { convention(TimeUnit.SECONDS.toMillis(5)) } val ignoredDetails = aem.obj.strings { convention(listOf( "*.*MBean", "org.osgi.service.component.runtime.ServiceComponentRuntime", "java.util.ResourceBundle" )) } init { sync.apply { http.connectionTimeout.convention(1_500) http.connectionRetries.convention(false) } } override fun check() { logger.info("Checking OSGi events on $instance") val state = state(sync.osgiFramework.determineEventState()) if (state.unknown) { statusLogger.error( "Events unknown", "Unknown event state on $instance" ) return } val unstable = state.events.asSequence() .byTopics(unstableTopics.get()) .byAgeMillis(unstableAgeMillis.get(), instance.zoneId) .ignoreDetails(ignoredDetails.get()) .toList() if (unstable.isNotEmpty()) { statusLogger.error( when (unstable.size) { 1 -> "Event unstable '${StringUtils.abbreviate(unstable.first().details.shortenClass(), EVENT_DETAILS_LENGTH)}'" else -> "Events unstable (${unstable.size})" }, "Events causing instability (${unstable.size}) detected on $instance:\n${logValues(unstable)}" ) } } companion object { const val EVENT_DETAILS_LENGTH = 64 } }
apache-2.0
4269f96a0cab07fe05bc30a9c78916c0
33.114286
136
0.59799
4.618956
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SendUDPPacketActionType.kt
1
963
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.framework.extensions.takeUnlessEmpty import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class SendUDPPacketActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = SendUDPPacketAction( data = actionDTO.getByteArray(0) ?: ByteArray(0), ipAddress = actionDTO.getString(1)?.takeUnlessEmpty() ?: "255.255.255.255", port = actionDTO.getInt(2) ?: 0, ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, functionNameAliases = setOf(FUNCTION_NAME_ALIAS), parameters = 3, ) companion object { private const val TYPE = "send_udp_packet" private const val FUNCTION_NAME = "sendUDPPacket" private const val FUNCTION_NAME_ALIAS = "sendUdpPacket" } }
mit
20e2fbef30a205c27be8989b04d31030
33.392857
83
0.70405
4.0125
false
false
false
false
sksamuel/ktest
kotest-common/src/commonMain/kotlin/io/kotest/fp/Try.kt
1
2350
package io.kotest.fp sealed class Try<out T> { data class Success<T>(val value: T) : Try<T>() data class Failure(val error: Throwable) : Try<Nothing>() companion object { fun failure(error: String) = Failure(RuntimeException(error)) operator fun invoke(t: Throwable): Try<Unit> = Failure(t) inline operator fun <T> invoke(f: () -> T): Try<T> = try { Success(f()) } catch (e: Throwable) { if (nonFatal(e)) Failure(e) else throw e } } inline fun <U> map(f: (T) -> U): Try<U> = flatMap { Try { f(it) } } fun isSuccess() = this is Success fun isFailure() = this is Failure fun getOrThrow(): T = when (this) { is Failure -> throw error is Success -> value } inline fun <U> flatMap(f: (T) -> Try<U>): Try<U> = when (this) { is Failure -> this is Success -> f(value) } inline fun <R> fold(ifFailure: (Throwable) -> R, ifSuccess: (T) -> R): R = when (this) { is Failure -> ifFailure(this.error) is Success -> ifSuccess(this.value) } inline fun onFailure(f: (Throwable) -> Unit): Try<T> = when (this) { is Success -> this is Failure -> { f(this.error) this } } inline fun onSuccess(f: (T) -> Unit): Try<T> = when (this) { is Success -> { f(this.value) this } is Failure -> this } fun toOption(): Option<T> = fold({ Option.None }, { Option.Some(it) }) inline fun mapFailure(f: (Throwable) -> Throwable) = fold({ f(it).failure() }, { it.success() }) fun getOrNull(): T? = fold({ null }, { it }) fun errorOrNull(): Throwable? = fold({ it }, { null }) } fun <T> Try<Try<T>>.flatten(): Try<T> = when (this) { is Try.Success -> this.value is Try.Failure -> this } inline fun <U, T : U> Try<T>.getOrElse(f: (Throwable) -> U): U = when (this) { is Try.Success -> this.value is Try.Failure -> f(this.error) } inline fun <U, T : U> Try<T>.recoverWith(f: (Throwable) -> Try<U>): Try<U> = when (this) { is Try.Success -> this is Try.Failure -> f(this.error) } fun <U, T : U> Try<T>.recover(f: (Throwable) -> U): Try<U> = when (this) { is Try.Success -> this is Try.Failure -> Try { f(this.error) } } fun <T> T.success(): Try<T> = Try.Success(this) fun Throwable.failure(): Try<Nothing> = Try.Failure(this)
mit
abf5fadc456b3291e094fca5abb1812c
26.647059
99
0.561702
3.162853
false
false
false
false
hitting1024/SvnDiffBrowser
SvnDiffBrowser/src/main/kotlin/jp/hitting/svn_diff_browser/controller/RepositoryController.kt
1
2573
package jp.hitting.svn_diff_browser.controller import jp.hitting.svn_diff_browser.Constants import jp.hitting.svn_diff_browser.model.RepositoryModel import jp.hitting.svn_diff_browser.service.RepositoryService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import java.util.* import javax.servlet.http.HttpSession /** * Repository Controller. * Created by hitting on 2016/03/04. */ @Controller @RequestMapping("/repository") class RepositoryController { @Autowired private val repositoryServiceImpl: RepositoryService? = null /** * Repository detail page * * @param id repository ID * @param dir target directory * @param session HttpSession * @param model Model * @return detail view name */ @RequestMapping("/{id}") fun detail(@PathVariable("id") id: Int, path: String?, session: HttpSession, model: Model): String { val map = session.getAttribute(Constants.SessionKey.SESSION_REPOSITORY_KEY) as? HashMap<Int, RepositoryModel> if (map == null || !map.containsKey(id)) { // TODO error message return "index" } val repository = map.get(id)!! model.addAttribute("repositoryName", repository.getRepositoryName()) val targetPath = if (path == null) "/" else "/" + path model.addAttribute("path", targetPath) model.addAttribute("pathList", this.repositoryServiceImpl!!.getPathList(repository, targetPath)) return "detail" } /** * Repository commit log page at revision. * * @param id repository ID * @param rev revision * @param session HttpSession * @param model Model * @return diff view name */ @RequestMapping("/{id}/rev/{rev}") fun diff(@PathVariable("id") id: Int, @PathVariable("rev") rev: Long, session: HttpSession, model: Model): String { val map = session.getAttribute(Constants.SessionKey.SESSION_REPOSITORY_KEY) as? HashMap<Int, RepositoryModel> if (map == null || !map.containsKey(id)) { // TODO error message return "index" } val repository = map.get(id)!! model.addAttribute("repositoryName", repository.getRepositoryName()) model.addAttribute("diff", this.repositoryServiceImpl!!.getDiffList(repository, rev)) return "diff" } }
mit
71d1288f2bd6069e82de372b687d792a
32.855263
119
0.678585
4.443869
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/feature/method/GotosFeature.kt
1
8246
/* * Copyright 2016 Carlos Ballesteros Velasco * * 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.jtransc.ast.feature.method import com.jtransc.ast.* import com.jtransc.ast.optimize.optimize import com.jtransc.graph.Relooper import com.jtransc.graph.RelooperException @Suppress("UNUSED_PARAMETER", "LoopToCallChain") // @TODO: Use AstBuilder to make it more readable class GotosFeature : AstMethodFeature() { override fun remove(method: AstMethod, body: AstBody, settings: AstBuildSettings, types: AstTypes): AstBody { if (settings.relooper) { try { return removeRelooper(body, types) ?: removeMachineState(body, types) } catch (t: Throwable) { t.printStackTrace() return removeMachineState(body, types) } } else { return removeMachineState(body, types) } } private fun removeRelooper(body: AstBody, types: AstTypes): AstBody? { class BasicBlock(var index: Int) { var node: Relooper.Node? = null val stms = arrayListOf<AstStm>() var next: BasicBlock? = null var condExpr: AstExpr? = null var ifNext: BasicBlock? = null //val targets by lazy { (listOf(next, ifNext) + (switchNext?.values ?: listOf())).filterNotNull() } override fun toString(): String = "BasicBlock($index)" } val entryStm = body.stm as? AstStm.STMS ?: return null // Not relooping single statements if (body.traps.isNotEmpty()) return null // Not relooping functions with traps by the moment val stms = entryStm.stms val bblist = arrayListOf<BasicBlock>() val bbs = hashMapOf<AstLabel, BasicBlock>() fun createBB(): BasicBlock { val bb = BasicBlock(bblist.size) bblist += bb return bb } fun getBBForLabel(label: AstLabel): BasicBlock { return bbs.getOrPut(label) { createBB() } } val entry = createBB() var current = entry for (stmBox in stms) { val stm = stmBox.value when (stm) { is AstStm.STM_LABEL -> { val prev = current current = getBBForLabel(stm.label) prev.next = current } is AstStm.GOTO -> { val prev = current current = createBB() prev.next = getBBForLabel(stm.label) } is AstStm.IF_GOTO -> { val prev = current current = createBB() prev.condExpr = stm.cond.value prev.ifNext = getBBForLabel(stm.label) prev.next = current } is AstStm.SWITCH_GOTO -> { // Not handled switches yet! return null } is AstStm.RETURN, is AstStm.THROW, is AstStm.RETHROW -> { current.stms += stm val prev = current current = createBB() prev.next = null } else -> { current.stms += stm } } } val relooper = Relooper(types) for (n in bblist) { n.node = relooper.node(n.stms) //println("NODE(${n.index}): ${n.stms}") //if (n.next != null) println(" -> ${n.next}") //if (n.ifNext != null) println(" -> ${n.ifNext} [${n.condExpr}]") } for (n in bblist) { val next = n.next val ifNext = n.ifNext if (next != null) relooper.edge(n.node!!, next.node!!) if (n.condExpr != null && ifNext != null) relooper.edge(n.node!!, ifNext.node!!, n.condExpr!!) } try { return body.copy( stm = relooper.render(bblist[0].node!!)?.optimize(body.flags) ?: return null ) } catch (e: RelooperException) { //println("RelooperException: ${e.message}") return null } //return AstBody(relooper.render(bblist[0].node!!) ?: return null, body.locals, body.traps) } fun removeMachineState(body: AstBody, types: AstTypes): AstBody { // @TODO: this should create simple blocks and do analysis like that, instead of creating a gigantic switch // @TODO: trying to generate whiles, ifs and so on to allow javascript be fast. See relooper paper. var stm = body.stm //val locals = body.locals.toCollection(arrayListOf<AstLocal>()) val traps = body.traps.toCollection(arrayListOf<AstTrap>()) //val gotostate = AstLocal(-1, "_gotostate", AstType.INT) val gotostate = AstExpr.LOCAL(AstLocal(-1, "G", AstType.INT)) var hasLabels = false var stateIndex = 0 val labelsToState = hashMapOf<AstLabel, Int>() fun getStateFromLabel(label: AstLabel): Int { if (label !in labelsToState) { labelsToState[label] = ++stateIndex } return labelsToState[label]!! } fun strip(stm: AstStm): AstStm = when (stm) { is AstStm.STMS -> { // Without labels/gotos if (!stm.stms.any { it.value is AstStm.STM_LABEL }) { stm } // With labels/gotos else { hasLabels = true val stms = stm.stms var stateIndex2 = 0 var stateStms = arrayListOf<AstStm>() val cases = arrayListOf<Pair<List<Int>, AstStm>>() fun flush() { cases.add(Pair(listOf(stateIndex2), stateStms.stm())) stateIndex2 = -1 stateStms = arrayListOf<AstStm>() } fun simulateGotoLabel(index: Int) = listOf( gotostate.setTo(index.lit), AstStm.CONTINUE() ) fun simulateGotoLabel(label: AstLabel) = simulateGotoLabel(getStateFromLabel(label)) for (ss in stms) { val s = ss.value when (s) { is AstStm.STM_LABEL -> { val nextIndex = getStateFromLabel(s.label) val lastStm = stateStms.lastOrNull() if ((lastStm !is AstStm.CONTINUE) && (lastStm !is AstStm.BREAK) && (lastStm !is AstStm.RETURN)) { stateStms.addAll(simulateGotoLabel(s.label)) } flush() stateIndex2 = nextIndex stateStms = arrayListOf<AstStm>() } is AstStm.IF_GOTO -> { stateStms.add(AstStm.IF( s.cond.value, simulateGotoLabel(s.label).stm() )) } is AstStm.GOTO -> { stateStms.addAll(simulateGotoLabel(s.label)) } is AstStm.SWITCH_GOTO -> { //throw NotImplementedError("Must implement switch goto ") stateStms.add(AstStm.SWITCH( s.subject.value, simulateGotoLabel(s.default).stm(), s.cases.map { Pair(it.first, simulateGotoLabel(it.second).stm()) } )) } else -> { stateStms.add(s) } } } flush() fun extraReturn() = when (body.type.ret) { is AstType.VOID -> AstStm.RETURN_VOID() is AstType.BOOL -> AstStm.RETURN(false.lit) is AstType.BYTE, is AstType.SHORT, is AstType.CHAR, is AstType.INT -> AstStm.RETURN(0.lit) is AstType.LONG -> AstStm.RETURN(0L.lit) is AstType.FLOAT -> AstStm.RETURN(0f.lit) is AstType.DOUBLE -> AstStm.RETURN(0.0.lit) else -> AstStm.RETURN(null.lit) } val plainWhile = listOf( AstStm.WHILE(true.lit, AstStm.SWITCH(gotostate, AstStm.NOP("no default"), cases) ), extraReturn() ).stm() if (traps.isEmpty()) { plainWhile } else { // Calculate ranges for try...catch val checkTraps = traps.map { trap -> val startState = getStateFromLabel(trap.start) val endState = getStateFromLabel(trap.end) val handlerState = getStateFromLabel(trap.handler) AstStm.IF( //(gotostate ge AstExpr.LITERAL(startState)) band (gotostate le AstExpr.LITERAL(endState)) band (AstExpr.CAUGHT_EXCEPTION() instanceof trap.exception), (gotostate ge startState.lit) band (gotostate lt endState.lit) band (AstExpr.CAUGHT_EXCEPTION() instanceof trap.exception), simulateGotoLabel(handlerState).stm() ) } listOf( AstStm.WHILE(true.lit, AstStm.TRY_CATCH(plainWhile, stms( checkTraps.stms, AstStm.RETHROW() )) ), extraReturn() ).stm() } } } else -> stm } stm = strip(stm) //if (hasLabels) locals.add(gotostate.local) return body.copy(types = types, stm = stm, traps = traps) } }
apache-2.0
f9611b7a1a87976d7943e94728345c31
28.661871
159
0.634489
3.259289
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/utils/AppLinkUtils.kt
2
1299
package org.fossasia.openevent.general.utils import android.content.Intent import android.os.Bundle import androidx.navigation.NavController import org.fossasia.openevent.general.R const val EVENT_IDENTIFIER = "eventIdentifier" const val VERIFICATION_TOKEN = "verificationToken" const val RESET_PASSWORD_TOKEN = "resetPasswordToken" private const val SEGMENT_VERIFY = "verify" private const val SEGMENT_RESET_PASSWORD = "reset-password" private const val SEGMENT_EVENT = "e" object AppLinkUtils { fun getData(uri: String): AppLinkData? { val values = uri.split("/", "?", "=") return when (values[3]) { SEGMENT_EVENT -> AppLinkData(R.id.eventDetailsFragment, EVENT_IDENTIFIER, values.last()) SEGMENT_VERIFY -> AppLinkData(R.id.profileFragment, VERIFICATION_TOKEN, values.last()) SEGMENT_RESET_PASSWORD -> AppLinkData(R.id.eventsFragment, RESET_PASSWORD_TOKEN, values.last()) else -> null } } fun handleIntent(intent: Intent?, navController: NavController) { val uri = intent?.data ?: return val data = getData(uri.toString()) ?: return val bundle = Bundle() bundle.putString(data.argumentKey, data.argumentValue) navController.navigate(data.destinationId, bundle) } }
apache-2.0
633912119785a4e9f0020e7452e261e3
38.363636
107
0.699769
4.110759
false
false
false
false
seventhroot/elysium
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/currency/RPKCurrencyProviderImpl.kt
1
2707
/* * Copyright 2016 Ross 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.economy.bukkit.currency import com.rpkit.economy.bukkit.RPKEconomyBukkit import com.rpkit.economy.bukkit.database.table.RPKCurrencyTable import com.rpkit.economy.bukkit.event.currency.RPKBukkitCurrencyCreateEvent import com.rpkit.economy.bukkit.event.currency.RPKBukkitCurrencyDeleteEvent import com.rpkit.economy.bukkit.event.currency.RPKBukkitCurrencyUpdateEvent /** * Currency provider implementation. */ class RPKCurrencyProviderImpl(private val plugin: RPKEconomyBukkit): RPKCurrencyProvider { override fun getCurrency(id: Int): RPKCurrency? { return plugin.core.database.getTable(RPKCurrencyTable::class)[id] } override fun getCurrency(name: String): RPKCurrency? { return plugin.core.database.getTable(RPKCurrencyTable::class).get(name) } override val currencies: Collection<RPKCurrency> get() = plugin.core.database.getTable(RPKCurrencyTable::class).getAll() override fun addCurrency(currency: RPKCurrency) { val event = RPKBukkitCurrencyCreateEvent(currency) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return plugin.core.database.getTable(RPKCurrencyTable::class).insert(event.currency) } override fun removeCurrency(currency: RPKCurrency) { val event = RPKBukkitCurrencyDeleteEvent(currency) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return plugin.core.database.getTable(RPKCurrencyTable::class).delete(event.currency) } override fun updateCurrency(currency: RPKCurrency) { val event = RPKBukkitCurrencyUpdateEvent(currency) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return plugin.core.database.getTable(RPKCurrencyTable::class).update(event.currency) } override val defaultCurrency: RPKCurrency? get() { val currencyName = plugin.config.getString("currency.default") return if (currencyName != null) getCurrency(currencyName) else null } }
apache-2.0
f273ca75af8502fb941ba09bd3ded6e4
36.597222
90
0.72959
4.557239
false
false
false
false
Yorxxx/played-next-kotlin
app/src/main/java/com/piticlistudio/playednext/data/entity/mapper/datasources/game/RoomGameMapper.kt
1
3484
package com.piticlistudio.playednext.data.entity.mapper.datasources.game import com.piticlistudio.playednext.data.entity.mapper.DataLayerMapper import com.piticlistudio.playednext.data.entity.mapper.DomainLayerMapper import com.piticlistudio.playednext.data.entity.mapper.datasources.timetobeat.RoomTimeToBeatMapper import com.piticlistudio.playednext.data.entity.room.RoomGame import com.piticlistudio.playednext.data.entity.room.RoomGameProxy import com.piticlistudio.playednext.data.entity.room.RoomImage import com.piticlistudio.playednext.domain.model.Game import com.piticlistudio.playednext.domain.model.Image import javax.inject.Inject /** * Mapper for converting [RoomGameProxy] and [Game] * This mapperIGDB implements both [DataLayerMapper] and [DomainLayerMapper], which allows to map entities * from datalayer into domain layer, and viceversa */ class RoomGameMapper @Inject constructor(private val timeToBeatMapper: RoomTimeToBeatMapper) : DataLayerMapper<RoomGameProxy, Game>, DomainLayerMapper<Game, RoomGameProxy> { override fun mapFromDataLayer(model: RoomGameProxy): Game { with(model) { return Game(id = game.id, name = game.name, createdAt = game.createdAt, updatedAt = game.updatedAt, summary = game.summary, storyline = game.storyline, url = game.url, rating = game.rating, ratingCount = game.ratingCount, aggregatedRating = game.agregatedRating, aggregatedRatingCount = game.aggregatedRatingCount, totalRating = game.totalRating, totalRatingCount = game.totalRatingCount, releasedAt = game.firstReleaseAt, cover = game.cover?.let { Image(it.url, it.width, it.height) }, timeToBeat = game.timeToBeat?.let { timeToBeatMapper.mapFromDataLayer(it) }, developers = developers, publishers = publishers, genres = genres, platforms = platforms, syncedAt = game.syncedAt, collection = collection, images = images) } } override fun mapIntoDataLayerModel(model: Game): RoomGameProxy { with(model) { val game = RoomGame(id = id, collection = collection?.id, syncedAt = syncedAt, timeToBeat = timeToBeat?.let { timeToBeatMapper.mapIntoDataLayerModel(it) }, cover = cover?.let { RoomImage(it.url, it.width, it.height) }, totalRatingCount = totalRatingCount, totalRating = totalRating, aggregatedRatingCount = aggregatedRatingCount, ratingCount = ratingCount, rating = rating, url = url, storyline = storyline, summary = summary, updatedAt = updatedAt, createdAt = createdAt, name = name, popularity = null, hypes = null, franchise = null, agregatedRating = aggregatedRating, firstReleaseAt = releasedAt) return RoomGameProxy(game = game) } } }
mit
fd2aae136e1f100fbff1ccbd68473682
46.094595
173
0.589839
4.977143
false
false
false
false
ekoshkin/teamcity-kubernetes-plugin
teamcity-kubernetes-plugin-server/src/test/java/jetbrains/buildServer/clouds/kubernetes/KubeCloudImageTest.kt
1
3992
package jetbrains.buildServer.clouds.kubernetes import io.fabric8.kubernetes.api.model.ObjectMeta import io.fabric8.kubernetes.api.model.Pod import jetbrains.buildServer.BaseTestCase import jetbrains.buildServer.clouds.CloudImageParameters import jetbrains.buildServer.clouds.CloudInstanceUserData import jetbrains.buildServer.clouds.CloudKeys import jetbrains.buildServer.clouds.kubernetes.connector.FakeKubeApiConnector import jetbrains.buildServer.clouds.kubernetes.connector.KubeApiConnector import jetbrains.buildServer.clouds.kubernetes.podSpec.BuildAgentPodTemplateProvider import jetbrains.buildServer.clouds.kubernetes.podSpec.BuildAgentPodTemplateProviders import jetbrains.buildServer.clouds.server.impl.profile.CloudImageDataImpl import jetbrains.buildServer.clouds.server.impl.profile.CloudImageParametersImpl import org.assertj.core.api.BDDAssertions.then import org.testng.annotations.BeforeMethod import org.testng.annotations.Test @Test class KubeCloudImageTest : BaseTestCase() { private val PROJECT_ID = "project123" private lateinit var myApiConnector: KubeApiConnector private var myPods: MutableList<Pair<Pod, Map<String, String>>> = arrayListOf() @BeforeMethod override fun setUp() { super.setUp() myPods = arrayListOf() myApiConnector = object: FakeKubeApiConnector(){ override fun listPods(labels: MutableMap<String, String>): MutableCollection<Pod> { return myPods.filter { var retval = true labels.forEach { k, v -> retval = retval &&(it.second.containsKey(k) && it.second[k] == v) } retval }.map { it.first }.toMutableList() } } } public fun check_populate_instances(){ val image1Profile1 = createImage(createMap( CloudImageParameters.SOURCE_ID_FIELD, "image1", CloudKeys.PROFILE_ID, "kube-1", KubeParametersConstants.DOCKER_IMAGE, "jetbrains/teamcity-agent")) val image1Profile2 = createImage(createMap( CloudImageParameters.SOURCE_ID_FIELD, "image1", CloudKeys.PROFILE_ID, "kube-2", KubeParametersConstants.DOCKER_IMAGE, "jetbrains/teamcity-agent")) val pod = Pod() pod.metadata = ObjectMeta() pod.metadata.name = "jetbrains-teamcity-agent-1"; myPods.add(Pair(pod, createMap( KubeTeamCityLabels.TEAMCITY_CLOUD_PROFILE, "kube-1", KubeTeamCityLabels.TEAMCITY_CLOUD_IMAGE, image1Profile1.id))) image1Profile1.populateInstances() then(image1Profile1.instances).hasSize(1) then(image1Profile1.instances.first().name).isEqualTo("jetbrains-teamcity-agent-1") image1Profile2.populateInstances() then(image1Profile2.instances).hasSize(0) } private fun createImage(imageData: Map<String, String> = emptyMap()): KubeCloudImage { var cloudImageData = CloudImageDataImpl(imageData) val buildAgentPodTemplateProviders = object : BuildAgentPodTemplateProviders { override fun getAll(): MutableCollection<BuildAgentPodTemplateProvider> { return arrayListOf() } override fun find(id: String?): BuildAgentPodTemplateProvider? { return null; } override fun get(id: String?): BuildAgentPodTemplateProvider { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } } return KubeCloudImageImpl(KubeCloudImageData(CloudImageParametersImpl(cloudImageData, PROJECT_ID, "image1")), myApiConnector, KubeDataCacheImpl(), buildAgentPodTemplateProviders) } private fun createInstanceTag(): CloudInstanceUserData { return CloudInstanceUserData("agent name", "auth token", "server address", null, "profile id", "profile description", emptyMap()) } }
apache-2.0
a1fa4c04974d27472ce59fe2a0f59e5f
44.896552
137
0.697144
4.583238
false
true
false
false
BenAlderfer/hand-and-foot-scores
app/src/main/java/com/alderferstudios/handandfootscores/InstructionActivity.kt
1
4636
package com.alderferstudios.handandfootscores import android.content.Context import android.os.Bundle import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView /** * Instructional activity * * @author Ben Alderfer */ class InstructionActivity : AppCompatActivity() { private var slideNum = 0 private var viewPager: ViewPager? = null private var backArrow: Button? = null private var forwardArrow: Button? = null private var dots: ImageView? = null /** * Creates the activity and saves the items for changing later * * @param savedInstanceState the previous state */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_instruction) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) if (supportActionBar != null) { supportActionBar?.setDisplayHomeAsUpEnabled(true) } forwardArrow = findViewById(R.id.forwardArrow) backArrow = findViewById(R.id.backArrow) backArrow?.visibility = View.INVISIBLE dots = findViewById(R.id.dots) viewPager = findViewById(R.id.instructionPager) viewPager?.adapter = Adapter(this) viewPager?.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() { override fun onPageSelected(position: Int) { viewPager?.currentItem = position slideNum = position updateControls() } }) } /** * If the back arrow was clicked on toolbar * * @param item the item selected (only option is back arrow) * @return always true (useless) */ override fun onOptionsItemSelected(item: MenuItem): Boolean { onBackPressed() return true } /** * Goes to previous instruction * * @param v the calling button */ fun back(@Suppress("UNUSED_PARAMETER") v: View) { --slideNum updateControls() viewPager?.currentItem = slideNum } /** * Advances the instruction * * @param v the calling button */ fun forward(@Suppress("UNUSED_PARAMETER") v: View) { ++slideNum updateControls() viewPager?.currentItem = slideNum } /** * Updates the arrows and dots */ private fun updateControls() { if (slideNum == 0) { backArrow?.visibility = View.INVISIBLE } else { backArrow?.visibility = View.VISIBLE } if (slideNum == 3) { forwardArrow?.visibility = View.INVISIBLE } else { forwardArrow?.visibility = View.VISIBLE } when (slideNum) { 0 -> dots?.setImageResource(R.drawable.dots1) 1 -> dots?.setImageResource(R.drawable.dots2) 2 -> dots?.setImageResource(R.drawable.dots3) 3 -> dots?.setImageResource(R.drawable.dots4) } } /** * Custom adapter for the instructions */ private inner class Adapter(val context: Context) : PagerAdapter() { private val layouts = arrayOfNulls<Int>(4) init { layouts[0] = R.layout.instruction_setup layouts[1] = R.layout.instruction_objective layouts[2] = R.layout.instruction_play layouts[3] = R.layout.instruction_scoring } override fun instantiateItem(collection: ViewGroup, position: Int): Any { val inflater = LayoutInflater.from(context) //defaults to main screen val layout = inflater.inflate(layouts[position] ?: R.layout.instruction_setup, collection, false) as ViewGroup collection.addView(layout) return layout } override fun destroyItem(collection: ViewGroup, position: Int, view: Any) { collection.removeView(view as View) } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view === `object` } override fun getPageTitle(position: Int): CharSequence { return getString(R.string.title_activity_instruction) } override fun getCount(): Int { return layouts.size } } }
mit
048e143a684c5375fe5015f12b53a9fb
28.909677
92
0.621872
4.784314
false
false
false
false
TonnyTao/Acornote
Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/HomeActivity.kt
1
3820
package tonnysunm.com.acornote.ui import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.graphics.drawable.DrawerArrowDrawable import androidx.appcompat.widget.Toolbar import androidx.core.view.GravityCompat import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.Observer import androidx.navigation.findNavController import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.android.synthetic.main.app_bar_navigation.* import tonnysunm.com.acornote.R import tonnysunm.com.acornote.SettingsActivity import tonnysunm.com.acornote.model.NoteFilter import tonnysunm.com.acornote.ui.note.NoteActivity class HomeActivity : AppCompatActivity(R.layout.activity_main) { companion object { var scrollToTop = false } private val homeSharedModel by viewModels<HomeSharedViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) //set drawer icon supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeAsUpIndicator(DrawerArrowDrawable(this)) homeSharedModel.noteFilterLiveData.observe(this, Observer { titleView.text = it.title if (it is NoteFilter.ByColorTag) { colorTagView.colorString = it.colorTag.color colorTagView.isVisible = true } else { colorTagView.isGone = true } }) //fab val fab: FloatingActionButton = findViewById(R.id.fab) fab.setOnClickListener { val intent = Intent(this, NoteActivity::class.java).apply { when (val noteFilter = homeSharedModel.noteFilterLiveData.value) { NoteFilter.Star -> putExtra(getString(R.string.starKey), true) is NoteFilter.ByLabel -> putExtra(getString(R.string.labelIdKey), noteFilter.labelId) } } startActivity(intent) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) true } else -> { super.onOptionsItemSelected(item) } } override fun onSupportNavigateUp(): Boolean { fun navigateUp(): Boolean { val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navController = findNavController(R.id.nav_host_fragment) val currentDestination = navController.currentDestination ?: return false return if (R.id.nav_label == currentDestination.id) { drawerLayout.openDrawer(GravityCompat.START) true } else { navController.navigateUp() } } return navigateUp() || super.onSupportNavigateUp() } override fun onBackPressed() { val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) if (drawerLayout.isDrawerOpen(GravityCompat.START)) { super.onBackPressed() } else { drawerLayout.openDrawer(GravityCompat.START) } } }
apache-2.0
51d06b724a7f8e2a8a99824e4b55f305
32.80531
85
0.661518
5.059603
false
false
false
false
mniami/android.kotlin.benchmark
app/src/main/java/guideme/volunteers/ui/fragments/genericlist/GenericListAdapter.kt
2
2547
package guideme.volunteers.ui.fragments.genericlist import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.squareup.picasso.Picasso import guideme.volunteers.R import guideme.volunteers.ui.utils.CircleTransform class GenericListAdapter(val list: List<GenericItem<*>>, val onClickListener: (GenericItem<*>?) -> Unit) : RecyclerView.Adapter<GenericListAdapter.ViewHolder>() { var filteredList = list fun filter(text: String) { if (text.isBlank()) { filteredList = list } else { filteredList = list.filter { item -> item.title.contains(text, true) || item.subTitle.contains(text, true) } } notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GenericListAdapter.ViewHolder { return GenericListAdapter.ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.generic_item, parent, false), onClickListener) } override fun onBindViewHolder(holder: GenericListAdapter.ViewHolder, position: Int) { val item = filteredList[position] holder.update(item) } override fun getItemCount(): Int = filteredList.size class ViewHolder(itemView: View?, val onClickListener: (GenericItem<*>?) -> Unit) : RecyclerView.ViewHolder(itemView) { fun update(item: GenericItem<*>?) { val titleView = itemView.findViewById<TextView>(R.id.title) val subtitleView = itemView.findViewById<TextView>(R.id.subtitle) val imageView = itemView.findViewById<ImageView>(R.id.image) titleView.text = item?.title subtitleView.text = item?.subTitle titleView.tag = item subtitleView.tag = item imageView.tag = item itemView.tag = item titleView.setOnClickListener(this::onClick) subtitleView.setOnClickListener(this::onClick) imageView.setOnClickListener(this::onClick) itemView.setOnClickListener(this::onClick) if (item?.imageUrl != null && item.imageUrl.isNotEmpty()) { Picasso.with(itemView.context).load(item.imageUrl).transform(CircleTransform()).into(imageView) } else { } } fun onClick(view: View) { onClickListener(view.tag as GenericItem<*>?) } } }
apache-2.0
346cc60b4d3763f9073876e71dd7aa0d
35.4
162
0.659992
4.814745
false
false
false
false
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/transactions/ThreadLocalTransactionManager.kt
1
4155
package org.jetbrains.exposed.sql.transactions import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.exposedLogger import java.sql.Connection import java.sql.SQLException class ThreadLocalTransactionManager(private val db: Database, @Volatile override var defaultIsolationLevel: Int) : TransactionManager { val threadLocal = ThreadLocal<Transaction>() override fun newTransaction(isolation: Int): Transaction = Transaction(ThreadLocalTransaction(db, isolation, threadLocal)).apply { threadLocal.set(this) } override fun currentOrNull(): Transaction? = threadLocal.get() private class ThreadLocalTransaction(override val db: Database, isolation: Int, val threadLocal: ThreadLocal<Transaction>) : TransactionInterface { private val connectionLazy = lazy(LazyThreadSafetyMode.NONE) { db.connector().apply { autoCommit = false transactionIsolation = isolation } } override val connection: Connection get() = connectionLazy.value override val outerTransaction: Transaction? = threadLocal.get() override fun commit() { connection.commit() } override fun rollback() { if (connectionLazy.isInitialized() && !connection.isClosed) { connection.rollback() } } override fun close() { try { if (connectionLazy.isInitialized()) connection.close() } finally { threadLocal.set(outerTransaction) } } } } fun <T> transaction(statement: Transaction.() -> T): T = transaction(TransactionManager.manager.defaultIsolationLevel, 3, statement) fun <T> transaction(transactionIsolation: Int, repetitionAttempts: Int, statement: Transaction.() -> T): T { val outer = TransactionManager.currentOrNull() return if (outer != null) { outer.statement() } else { inTopLevelTransaction(transactionIsolation, repetitionAttempts, statement) } } private fun TransactionInterface.rollbackLoggingException(log: (Exception) -> Unit){ try { rollback() } catch (e: Exception){ log(e) } } private inline fun TransactionInterface.closeLoggingException(log: (Exception) -> Unit){ try { close() } catch (e: Exception){ log(e) } } fun <T> inTopLevelTransaction(transactionIsolation: Int, repetitionAttempts: Int, statement: Transaction.() -> T): T { var repetitions = 0 while (true) { val transaction = TransactionManager.manager.newTransaction(transactionIsolation) try { val answer = transaction.statement() transaction.commit() return answer } catch (e: SQLException) { val currentStatement = transaction.currentStatement exposedLogger.info("Transaction attempt #$repetitions failed: ${e.message}. Statement: $currentStatement", e) transaction.rollbackLoggingException { exposedLogger.info("Transaction rollback failed: ${it.message}. See previous log line for statement", it) } repetitions++ if (repetitions >= repetitionAttempts) { throw e } } catch (e: Throwable) { val currentStatement = transaction.currentStatement transaction.rollbackLoggingException { exposedLogger.info("Transaction rollback failed: ${it.message}. Statement: $currentStatement", it) } throw e } finally { TransactionManager.removeCurrent() val currentStatement = transaction.currentStatement currentStatement?.let { if(!it.isClosed) it.close() transaction.currentStatement = null } transaction.closeExecutedStatements() transaction.closeLoggingException { exposedLogger.info("Transaction close failed: ${it.message}. Statement: $currentStatement", it) } } } }
mit
fd570b45f5e89eaf68cc7a8555c4ec7e
33.633333
158
0.638748
5.16791
false
false
false
false
davinkevin/Podcast-Server
backend/src/test/kotlin/com/github/davinkevin/podcastserver/business/stats/StatsPodcastTypeTest.kt
1
1134
package com.github.davinkevin.podcastserver.business.stats import com.github.davinkevin.podcastserver.podcast.NumberOfItemByDateWrapper import com.github.davinkevin.podcastserver.podcast.StatsPodcastType import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.Month /** * Created by kevin on 01/07/15 for Podcast Server */ class StatsPodcastTypeTest { @Test fun `should has correct value`() { /* Given */ val numberOfItemSets = setOf(NI_1, NI_2, NI_3) /* When */ val (type, values) = StatsPodcastType(FAKE_TYPE, numberOfItemSets) /* Then */ assertThat(type).isEqualTo(FAKE_TYPE) assertThat(values).contains(NI_1, NI_2, NI_3) } companion object { private val NI_1 = NumberOfItemByDateWrapper(LocalDate.of(2015, Month.JULY, 1), 100) private val NI_2 = NumberOfItemByDateWrapper(LocalDate.of(2015, Month.JULY, 2), 200) private val NI_3 = NumberOfItemByDateWrapper(LocalDate.of(2015, Month.JULY, 3), 300) private const val FAKE_TYPE = "FakeType" } }
apache-2.0
d887be471f05d02c840a1820f21ed70f
32.352941
92
0.700176
3.634615
false
true
false
false
PaleoCrafter/BitReplicator
src/main/kotlin/de/mineformers/bitreplicator/util/Inventories.kt
1
6083
package de.mineformers.bitreplicator.util import com.google.common.base.Objects import net.minecraft.entity.Entity import net.minecraft.entity.item.EntityItem import net.minecraft.entity.player.EntityPlayer import net.minecraft.init.SoundEvents import net.minecraft.inventory.IInventory import net.minecraft.inventory.InventoryHelper import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.SoundCategory import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.world.World import net.minecraftforge.items.IItemHandler import net.minecraftforge.items.IItemHandlerModifiable /** * Various utilities for dealing with inventories and item stacks. */ object Inventories { /** * Spills the contents of the [IItemHandler] onto the ground. * * @param slots the slots to spill, may be null if all slots are to be spilled */ fun spill(world: World, pos: BlockPos, inventory: IItemHandler, slots: Iterable<Int>? = null) { spill(world, Vec3d(pos), inventory, slots) } /** * Spills the contents of the [IItemHandler] onto the ground at an entity's feet. * * @param slots the slots to spill, may be null if all slots are to be spilled */ fun spill(world: World, entity: Entity, inventory: IItemHandler, slots: Iterable<Int>? = null) { spill(world, entity.position, inventory, slots) } /** * Spills the contents of the [IItemHandler] onto the ground. * * @param slots the slots to spill, may be null if all slots are to be spilled */ private fun spill(world: World, pos: Vec3d, inventory: IItemHandler, slots: Iterable<Int>? = null) { val indices = slots ?: 0..inventory.slots - 1 for (i in indices) { val stack = inventory.getStackInSlot(i) if (stack != null) { InventoryHelper.spawnItemStack(world, pos.x, pos.y, pos.z, stack) } } } /** * Insert an item stack into a player's inventory or drop it to the ground if there is no space left. */ fun insertOrDrop(player: EntityPlayer, stack: ItemStack?) { if (stack == null) return if (!player.inventory.addItemStackToInventory(stack)) InventoryHelper.spawnItemStack(player.world, player.posX, player.posY, player.posZ, stack) else player.world.playSound(null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, .2f, ((player.rng.nextFloat() - player.rng.nextFloat()) * .7f + 1f) * 2f) } /** * Drop an item stack in a certain direction from a block. * The entity will spawn in the middle of the specified face and will move away from it. */ fun spawn(world: World, pos: BlockPos, side: EnumFacing, stack: ItemStack?) { if (stack == null || world.isRemote) return val offset = Vec3d(0.5, 0.5, 0.5) + 0.5 * Vec3d(side.directionVec) + pos val entity = EntityItem(world, offset.x, offset.y, offset.z, stack) // Add some random motion away from the block's face entity.motionX = world.rand.nextGaussian() * 0.05 + 0.05 * side.frontOffsetX entity.motionY = world.rand.nextGaussian() * 0.05 + 0.05 * side.frontOffsetY entity.motionZ = world.rand.nextGaussian() * 0.05 + 0.05 * side.frontOffsetZ world.spawnEntity(entity) // Play the drop sound world.playSound(null, offset.x, offset.y, offset.z, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.BLOCKS, 0.2f, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7f + 1.0f) * 2.0f) } /** * Completely clears out all slots of an [inventory], i.e. setting them to `null`. */ fun clear(inventory: IInventory) { for (i in 0..(inventory.sizeInventory - 1)) inventory.setInventorySlotContents(i, null) } /** * Completely clears out all slots of an [inventory], i.e. setting them to `null`. */ fun clear(inventory: IItemHandlerModifiable) { for (i in 0..(inventory.slots - 1)) inventory.setStackInSlot(i, null) } /** * Checks whether to item stacks are to be considered equal in regards to their * <ul> * <li>Item</li> * <li>Metadata</li> * <li>NBT Tag Compound</li> * </ul> */ fun equal(a: ItemStack?, b: ItemStack?) = a == b || a != null && b != null && equalsImpl(a, b) private fun equalsImpl(a: ItemStack, b: ItemStack) = a.item === b.item && a.metadata == b.metadata && Objects.equal(a.tagCompound, b.tagCompound) /** * Tries to merge an item stack into another one if they are equal. * Note that this function will mutate the passed stacks, * meaning that modifying the stacks' sizes afterwards is *not* necessary. * * @return the result of merging both item stacks */ fun merge(from: ItemStack?, into: ItemStack?) = merge(from, into, false) /** * Tries to merge an item stack into another one. * Note that this function will mutate the passed stacks, * meaning that modifying the stacks' sizes afterwards is *not* necessary. * * @param force if true, the merging will be performed even if the stacks are not equal * @return the result of merging both item stacks */ fun merge(from: ItemStack?, into: ItemStack?, force: Boolean): ItemStack? { if (from == null) { return into } if (into == null) { val result = from.copy() from.stackSize = 0 return result } if (force || equalsImpl(from, into)) { val transferCount = Math.min(into.maxStackSize - into.stackSize, from.stackSize) from.stackSize -= transferCount into.stackSize += transferCount } return into } }
mit
372f9fb871101b5a90641f09663b6680
38.251613
119
0.626664
4.012533
false
false
false
false
cketti/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/general/LanguagePreference.kt
1
1232
package com.fsck.k9.ui.settings.general import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import androidx.core.content.res.TypedArrayUtils import androidx.preference.ListPreference import com.fsck.k9.core.R class LanguagePreference @JvmOverloads @SuppressLint("RestrictedApi") constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = TypedArrayUtils.getAttr( context, androidx.preference.R.attr.dialogPreferenceStyle, android.R.attr.dialogPreferenceStyle ), defStyleRes: Int = 0 ) : ListPreference(context, attrs, defStyleAttr, defStyleRes) { init { val supportedLanguages = context.resources.getStringArray(R.array.supported_languages).toSet() val newEntries = mutableListOf<CharSequence>() val newEntryValues = mutableListOf<CharSequence>() entryValues.forEachIndexed { index, language -> if (language in supportedLanguages) { newEntries.add(entries[index]) newEntryValues.add(entryValues[index]) } } entries = newEntries.toTypedArray() entryValues = newEntryValues.toTypedArray() } }
apache-2.0
f96bfcbd7c307b57c04ead426eb665e4
30.589744
102
0.707792
4.793774
false
false
false
false
kittinunf/ReactiveAndroid
reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/view/ViewGroupAnimationEventTest.kt
1
2119
package com.github.kittinunf.reactiveandroid.view import android.support.test.InstrumentationRegistry import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.view.animation.Animation import android.view.animation.LayoutAnimationController import android.view.animation.RotateAnimation import android.view.animation.TranslateAnimation import io.reactivex.observers.TestObserver import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ViewGroupAnimationEventTest { @Rule @JvmField val activityRule = ActivityTestRule(ViewTestActivity::class.java) val instrumentation = InstrumentationRegistry.getInstrumentation() @Test fun testLayoutAnimation() { val parent = activityRule.activity.parent val child = activityRule.activity.child instrumentation.runOnMainSync { parent.addView(child) } val translateAnimation = TranslateAnimation(0.0f, 10.0f, 0.0f, 20.0f) translateAnimation.duration = 100 parent.layoutAnimation = LayoutAnimationController(translateAnimation) val t1 = TestObserver<Animation>() val t2 = TestObserver<Animation>() parent.rx_animationStart().subscribeWith(t1) parent.rx_animationEnd().subscribeWith(t2) t1.assertNoValues() t1.assertNoErrors() t2.assertNoValues() t2.assertNoErrors() instrumentation.runOnMainSync { parent.startLayoutAnimation() } t1.assertValueCount(1) // t2.assertValueCount(1) val rotateAnimation = RotateAnimation(0.0f, 360.0f) rotateAnimation.repeatCount = Animation.INFINITE parent.layoutAnimation = LayoutAnimationController(rotateAnimation) val t3 = TestObserver<Animation>() parent.rx_animationRepeat().subscribeWith(t3) t3.assertNoValues() t3.assertNoErrors() instrumentation.runOnMainSync { parent.startLayoutAnimation() } // t3.assertValueCount(1) } }
mit
4350bceb705537c6489712d9d6df1e31
29.271429
78
0.714488
4.740492
false
true
false
false
CPRTeam/CCIP-Android
app/src/main/java/app/opass/ccip/ui/fastpass/CountdownActivity.kt
1
2405
package app.opass.ccip.ui.fastpass import android.graphics.Color import android.os.Bundle import android.os.CountDownTimer import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import app.opass.ccip.R import app.opass.ccip.model.Scenario import app.opass.ccip.util.JsonUtil import kotlinx.android.synthetic.main.activity_countdown.* import java.text.SimpleDateFormat import java.util.* class CountdownActivity : AppCompatActivity() { companion object { const val INTENT_EXTRA_SCENARIO = "scenario" private val SDF = SimpleDateFormat("HH:mm:ss") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_countdown) val attrText = attr val countdownText = countdown val (_, _, _, _, attr1, _, countdown1, used) = JsonUtil.fromJson( intent.getStringExtra(INTENT_EXTRA_SCENARIO).toString(), Scenario::class.java ) button.setOnClickListener { finish() } val attr = attr1.asJsonObject val elemDiet = attr.get("diet") if (elemDiet != null) { val diet = elemDiet.asString if (diet == "meat") { countdown_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorDietMeat)) attrText.setText(R.string.meal) } else { countdown_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorDietVegetarian)) attrText.setText(R.string.vegan) } } else { val entries = attr.entrySet() attrText.text = entries.joinToString("\n") { (key, value) -> "$key: $value" } } val countdown = if (used == null) { countdown1 * 1000L } else { (used + countdown1) * 1000L - Date().time } object : CountDownTimer(countdown, 1000L) { override fun onTick(l: Long) { countdownText.text = (l / 1000).toString() current_time.text = SDF.format(Date().time) } override fun onFinish() { countdownText.text = "0" current_time.visibility = View.GONE countdown_layout.setBackgroundColor(Color.RED) } }.start() } }
gpl-3.0
656235441d6e25ab1ccd709e37fe2a58
32.402778
110
0.611642
4.356884
false
false
false
false
rosariopfernandes/rollapass
app/src/main/java/io/github/rosariopfernandes/rollapass/AccountActivity.kt
1
4248
package io.github.rosariopfernandes.rollapass import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import io.github.rosariopfernandes.rollapass.model.Account import io.github.rosariopfernandes.rollapass.room.AccountViewModelFactory import io.github.rosariopfernandes.rollapass.room.PassDatabase import io.github.rosariopfernandes.rollapass.viewmodel.AccountViewModel import kotlinx.android.synthetic.main.activity_account.* import kotlinx.android.synthetic.main.content_account.* import org.jetbrains.anko.alert import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread class AccountActivity : AppCompatActivity() { var account: Account? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) val accountId = intent.extras!!.getInt("accountId") val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager ViewModelProviders.of(this, AccountViewModelFactory(application, accountId)) .get(AccountViewModel::class.java) .account?.observe(this, Observer { account -> //toolbar.title = account?.userWebsite this.account = account account?.let { txtWebsite.editText?.setText(account.userWebsite) txtUsername.editText?.setText(account.userName) txtPassword.editText?.setText(account.userPassword) btnCopyUsername.setOnClickListener { val clip = ClipData.newPlainText("username", account.userName) clipboard.setPrimaryClip(clip) } btnCopyPassword.setOnClickListener { val clip = ClipData.newPlainText("password", account.userPassword) clipboard.setPrimaryClip(clip) } btnBrowse.setOnClickListener { val webpage = Uri.parse("http://${account.userWebsite}") val intent = Intent(Intent.ACTION_VIEW, webpage) if (intent.resolveActivity(packageManager) != null) { startActivity(intent) } } } }) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_account, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_edit -> { val intent = Intent(this@AccountActivity, NewAccountActivity::class.java) intent.putExtra("accountId", account?.accountId) startActivity(intent) true } R.id.action_delete -> { alert{ title = getString(R.string.title_delete) positiveButton(R.string.action_cancel, { }) negativeButton(R.string.action_delete, { val database = PassDatabase.getInstance(this@AccountActivity) doAsync { database?.accountDao()?.deleteAccount(account!!) uiThread { finish() } } }) }.show() true } else -> super.onOptionsItemSelected(item) } } }
gpl-3.0
1424f9bf8c5d57940425e9afb251e075
39.846154
87
0.611582
5.343396
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuInterceptor.kt
4
1442
package eu.kanade.tachiyomi.data.track.kitsu import com.google.gson.Gson import okhttp3.Interceptor import okhttp3.Response class KitsuInterceptor(val kitsu: Kitsu, val gson: Gson) : Interceptor { /** * OAuth object used for authenticated requests. */ private var oauth: OAuth? = kitsu.restoreToken() override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val currAuth = oauth ?: throw Exception("Not authenticated with Kitsu") val refreshToken = currAuth.refresh_token!! // Refresh access token if expired. if (currAuth.isExpired()) { val response = chain.proceed(KitsuApi.refreshTokenRequest(refreshToken)) if (response.isSuccessful) { newAuth(gson.fromJson(response.body()!!.string(), OAuth::class.java)) } else { response.close() } } // Add the authorization header to the original request. val authRequest = originalRequest.newBuilder() .addHeader("Authorization", "Bearer ${oauth!!.access_token}") .header("Accept", "application/vnd.api+json") .header("Content-Type", "application/vnd.api+json") .build() return chain.proceed(authRequest) } fun newAuth(oauth: OAuth?) { this.oauth = oauth kitsu.saveToken(oauth) } }
apache-2.0
bba168163f18c7f4a8e77a95564f0daf
30.369565
85
0.617892
4.520376
false
false
false
false
yuzumone/ExpandableTextView
app/src/main/kotlin/net/expandable/sample/MainActivity.kt
1
804
package net.expandable.sample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.Toast import net.expandable.ExpandableTextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<ExpandableTextView>(R.id.text) textView.text = getString(R.string.long_text) textView.collapseLines = 2 textView.setOnExpandableClickListener( onExpand = { showToast("Expand") }, onCollapse = { showToast("Collapse") } ) } private fun showToast(text: String) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } }
apache-2.0
1e7606987ab978f20a1a62dc84bf2d9d
31.16
66
0.689055
4.62069
false
false
false
false
kotlintest/kotlintest
kotest-extensions/src/jvmMain/kotlin/io/kotest/extensions/system/SystemExitExtensions.kt
1
6476
package io.kotest.extensions.system import io.kotest.core.config.AbstractProjectConfig import io.kotest.core.test.Description import io.kotest.core.spec.description import io.kotest.core.spec.Spec import io.kotest.core.listeners.TestListener import java.io.FileDescriptor import java.net.InetAddress import java.security.Permission import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass /** * Will replace the [SecurityManager] used by the Java runtime * with a [NoExitSecurityManager] that will throw an exception * if System.exit() is invoked. This exception can then be * tested for with shouldThrow(). * * To use this, override `listeners()` in your [AbstractProjectConfig]. * * Note: This listener will change the security manager * for all tests. If you want to change the security manager * for just a single [Spec] then consider the * alternative [SpecSystemExitListener] */ object SystemExitListener : TestListener { override suspend fun prepareSpec(kclass: KClass<out Spec>) { val previous = System.getSecurityManager() System.setSecurityManager(NoExitSecurityManager(previous)) } } /** * Will replace the [SecurityManager] used by the Java runtime * with a [NoExitSecurityManager] that will throw an exception * if System.exit() is invoked. This exception can then be * tested for with shouldThrow(). * * After the spec has completed, the original security manager * will be set. * * To use this, override `listeners`() in your [Spec] class. * * Note: This listener is only suitable for use if parallelism is * set to 1 (the default) otherwise a race condition could occur. * * If you want to change the security manager for the entire * project, then use the alternative [SystemExitListener] */ object SpecSystemExitListener : TestListener { private val previousSecurityManagers = ConcurrentHashMap<Description, SecurityManager>() override suspend fun beforeSpec(spec: Spec) { val previous = System.getSecurityManager() if (previous != null) previousSecurityManagers[spec::class.description()] = previous System.setSecurityManager(NoExitSecurityManager(previous)) } override suspend fun afterSpec(spec: Spec) { if (previousSecurityManagers.contains(spec::class.description())) System.setSecurityManager(previousSecurityManagers[spec::class.description()]) else System.setSecurityManager(null) } } class SystemExitException(val exitCode: Int) : RuntimeException() /** * An implementation of [SecurityManager] that throws a [SystemExitException] * exception whenever System.exit(int) is invoked. * * Implemenation inspired from * https://github.com/stefanbirkner/system-rules/blob/72250d0451f9f1a5c5852502b5e9b0c874aeab42/src/main/java/org/junit/contrib/java/lang/system/internal/NoExitSecurityManager.java * Apache Licensed. */ @Suppress("OverridingDeprecatedMember", "DEPRECATION") class NoExitSecurityManager(private val originalSecurityManager: SecurityManager?) : SecurityManager() { override fun checkExit(status: Int) = throw SystemExitException(status) override fun getSecurityContext(): Any { return if (originalSecurityManager == null) super.getSecurityContext() else originalSecurityManager.securityContext } override fun checkPermission(perm: Permission) { originalSecurityManager?.checkPermission(perm) } override fun checkPermission(perm: Permission, context: Any) { originalSecurityManager?.checkPermission(perm, context) } override fun checkCreateClassLoader() { originalSecurityManager?.checkCreateClassLoader() } override fun checkAccess(t: Thread) { originalSecurityManager?.checkAccess(t) } override fun checkAccess(g: ThreadGroup) { originalSecurityManager?.checkAccess(g) } override fun checkExec(cmd: String) { originalSecurityManager?.checkExec(cmd) } override fun checkLink(lib: String) { originalSecurityManager?.checkLink(lib) } override fun checkRead(fd: FileDescriptor) { originalSecurityManager?.checkRead(fd) } override fun checkRead(file: String) { originalSecurityManager?.checkRead(file) } override fun checkRead(file: String, context: Any) { originalSecurityManager?.checkRead(file, context) } override fun checkWrite(fd: FileDescriptor) { originalSecurityManager?.checkWrite(fd) } override fun checkWrite(file: String) { originalSecurityManager?.checkWrite(file) } override fun checkDelete(file: String) { originalSecurityManager?.checkDelete(file) } override fun checkConnect(host: String, port: Int) { originalSecurityManager?.checkConnect(host, port) } override fun checkConnect(host: String, port: Int, context: Any) { originalSecurityManager?.checkConnect(host, port, context) } override fun checkListen(port: Int) { originalSecurityManager?.checkListen(port) } override fun checkAccept(host: String, port: Int) { originalSecurityManager?.checkAccept(host, port) } override fun checkMulticast(maddr: InetAddress) { originalSecurityManager?.checkMulticast(maddr) } override fun checkMulticast(maddr: InetAddress, ttl: Byte) { originalSecurityManager?.checkMulticast(maddr, ttl) } override fun checkPropertiesAccess() { originalSecurityManager?.checkPropertiesAccess() } override fun checkPropertyAccess(key: String) { originalSecurityManager?.checkPropertyAccess(key) } override fun checkPrintJobAccess() { originalSecurityManager?.checkPrintJobAccess() } override fun checkPackageAccess(pkg: String) { originalSecurityManager?.checkPackageAccess(pkg) } override fun checkPackageDefinition(pkg: String) { originalSecurityManager?.checkPackageDefinition(pkg) } override fun checkSetFactory() { originalSecurityManager?.checkSetFactory() } override fun checkSecurityAccess(target: String) { originalSecurityManager?.checkSecurityAccess(target) } override fun getThreadGroup(): ThreadGroup { return if (originalSecurityManager == null) super.getThreadGroup() else originalSecurityManager.threadGroup } }
apache-2.0
d3b86b5b0c3cf9f48121f467cc3f826e
31.059406
179
0.721124
4.622413
false
true
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/servers/list/ServerListAdapter.kt
2
4689
package com.lasthopesoftware.bluewater.client.servers.list import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageButton import android.widget.RelativeLayout import android.widget.TextView import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.lasthopesoftware.bluewater.R import com.lasthopesoftware.bluewater.client.browsing.library.access.session.BrowserLibrarySelection import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectBrowserLibrary import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.servers.list.listeners.EditServerClickListener import com.lasthopesoftware.bluewater.client.servers.list.listeners.SelectServerOnClickListener import com.lasthopesoftware.bluewater.shared.android.adapters.DeferredListAdapter import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder import com.lasthopesoftware.bluewater.shared.android.view.ViewUtils import com.namehillsoftware.handoff.promises.Promise class ServerListAdapter(private val activity: Activity, private val browserLibrarySelection: SelectBrowserLibrary) : DeferredListAdapter<Library, ServerListAdapter.ViewHolder>(activity, LibraryDiffer) { private val localBroadcastManager = lazy { LocalBroadcastManager.getInstance(activity) } private var activeLibrary: Library? = null fun updateLibraries(libraries: Collection<Library>, activeLibrary: Library?): Promise<Unit> { this.activeLibrary = activeLibrary return updateListEventually(libraries.toList()) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val relativeLayout = getInflater(parent.context).inflate(R.layout.layout_server_item, parent, false) as RelativeLayout return ViewHolder(relativeLayout) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.update(getItem(position)) } companion object { private fun getInflater(context: Context): LayoutInflater { return context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } } inner class ViewHolder(private val parent: RelativeLayout) : RecyclerView.ViewHolder(parent) { private val textView = LazyViewFinder<TextView>(parent, R.id.tvServerItem) private val btnSelectServer = LazyViewFinder<Button>(parent, R.id.btnSelectServer) private val btnConfigureServer = LazyViewFinder<ImageButton>(parent, R.id.btnConfigureServer) private var broadcastReceiver: BroadcastReceiver? = null private var onAttachStateChangeListener: View.OnAttachStateChangeListener? = null fun update(library: Library) { val textView = textView.findView() textView.text = library.accessCode textView.setTypeface(null, ViewUtils.getActiveListItemTextViewStyle(activeLibrary != null && library.id == activeLibrary?.id)) broadcastReceiver?.run { localBroadcastManager.value.unregisterReceiver(this) } localBroadcastManager.value.registerReceiver( object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { textView.setTypeface(null, ViewUtils.getActiveListItemTextViewStyle(library.id == intent.getIntExtra( BrowserLibrarySelection.chosenLibraryId, -1))) } }.apply { broadcastReceiver = this }, IntentFilter(BrowserLibrarySelection.libraryChosenEvent)) onAttachStateChangeListener?.run { parent.removeOnAttachStateChangeListener(this) } parent.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) {} override fun onViewDetachedFromWindow(v: View) { val broadcastReceiver = broadcastReceiver if (broadcastReceiver != null) localBroadcastManager.value.unregisterReceiver(broadcastReceiver) } }.apply { onAttachStateChangeListener = this }) btnSelectServer.findView().setOnClickListener(SelectServerOnClickListener(library, browserLibrarySelection)) btnConfigureServer.findView().setOnClickListener(EditServerClickListener(activity, library.id)) } } private object LibraryDiffer : DiffUtil.ItemCallback<Library>() { override fun areItemsTheSame(oldItem: Library, newItem: Library): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Library, newItem: Library): Boolean = areItemsTheSame(oldItem, newItem) } }
lgpl-3.0
e9c1a3f9436020430cccf73843ddaf7b
46.846939
129
0.819791
4.726815
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/multiblocks/Multiblock.kt
2
1600
package com.cout970.magneticraft.systems.multiblocks import com.cout970.magneticraft.api.multiblock.IMultiblock import com.cout970.magneticraft.misc.vector.* import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.util.text.ITextComponent /** * Created by cout970 on 19/08/2016. */ abstract class Multiblock : IMultiblock { abstract val name: String abstract val size: BlockPos abstract val scheme: List<MultiblockLayer> abstract val center: BlockPos class MultiblockLayer(val components: List<List<IMultiblockComponent>>) abstract fun checkExtraRequirements(data: MutableList<BlockData>, context: MultiblockContext): List<ITextComponent> companion object { fun yLayers(vararg args: List<List<IMultiblockComponent>>): List<MultiblockLayer> = args.map(Multiblock::MultiblockLayer) fun zLayers(vararg args: List<IMultiblockComponent>): List<List<IMultiblockComponent>> = listOf(*args) } open fun onActivate(data: List<BlockData>, context: MultiblockContext) = Unit open fun onDeactivate(data: List<BlockData>, context: MultiblockContext) = Unit open fun getGlobalCollisionBoxes(): List<AxisAlignedBB> = listOf((BlockPos.ORIGIN createAABBUsing size).offset(-center)) infix fun Vec3d.to(other: Vec3d) = AxisAlignedBB(xd, yd, zd, other.xd, other.yd, other.zd) override fun getMultiblockName(): String = name override fun getMultiblockSize(): BlockPos = size override fun getMultiblockCenter(): BlockPos = center }
gpl-2.0
a0cee5c6433e67411f3756382f216f58
34.577778
124
0.758125
4.210526
false
false
false
false
springboot-angular2-tutorial/boot-app
src/main/kotlin/com/myapp/controller/UserController.kt
1
1819
package com.myapp.controller import com.myapp.domain.User import com.myapp.dto.page.Page import com.myapp.dto.request.UserEditParams import com.myapp.dto.request.UserNewParams import com.myapp.dto.response.ErrorResponse import com.myapp.repository.exception.EmailDuplicatedException import com.myapp.repository.exception.RecordNotFoundException import com.myapp.service.UserService import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* import javax.validation.Valid @RestController @RequestMapping("/api/users") class UserController( private val userService: UserService ) { @GetMapping fun list( @RequestParam(value = "page", required = false) page: Int?, @RequestParam(value = "size", required = false) size: Int? ): Page<User> { return userService.findAll( page = page ?: 1, size = size ?: 5 ) } @PostMapping fun create(@Valid @RequestBody params: UserNewParams): User { return userService.create(params) } @GetMapping(path = arrayOf("{id:\\d+}")) fun show(@PathVariable("id") id: Long) = userService.findOne(id) @GetMapping(path = arrayOf("/me")) fun showMe() = userService.findMe() @PatchMapping(path = arrayOf("/me")) fun updateMe(@Valid @RequestBody params: UserEditParams) = userService.updateMe(params) @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(EmailDuplicatedException::class) fun handleEmailDuplicatedException(e: EmailDuplicatedException): ErrorResponse { return ErrorResponse("email_already_taken", "This email is already taken.") } @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No user") @ExceptionHandler(RecordNotFoundException::class) fun handleUserNotFound() { } }
mit
4aaad80902bf05a40453b08a5731e5c8
29.830508
91
0.715228
4.220418
false
false
false
false
ze-pequeno/okhttp
okhttp/src/jsTest/kotlin/okhttp3/TestCall.kt
2
1486
/* * Copyright (c) 2022 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 import okhttp3.internal.jsExecuteAsync import okio.IOException class TestCall( private val request: Request, private val callbackHandler: (Call, Callback) -> Unit ) : Call { var cancelled = false var executed = false override fun request(): Request = request override suspend fun executeAsync(): Response = jsExecuteAsync() override fun enqueue(responseCallback: Callback) { check(!executed) { "Already Executed" } if (cancelled) { responseCallback.onFailure(this, IOException("Canceled")) } else { callbackHandler.invoke(this, responseCallback) } } override fun cancel() { cancelled = true } override fun isExecuted(): Boolean { return executed } override fun isCanceled(): Boolean { return cancelled } override fun clone(): Call { return TestCall(request, callbackHandler) } }
apache-2.0
805cc94a50b4dd9ff45127130045b1d5
24.186441
75
0.708614
4.319767
false
false
false
false
BennyKok/PxerStudio
app/src/main/java/com/benny/pxerstudio/shape/BaseShape.kt
1
1178
package com.benny.pxerstudio.shape import com.benny.pxerstudio.widget.PxerView import com.benny.pxerstudio.widget.PxerView.Pxer /** * Created by BennyKok on 10/12/2016. */ abstract class BaseShape { private var hasEnded = false private var startX = -1 private var startY = -1 private var endX = -1 private var endY = -1 open fun onDraw(pxerView: PxerView, startX: Int, startY: Int, endX: Int, endY: Int): Boolean { if (this.startX == startX && this.startY == startY && this.endX == endX && this.endY == endY) { return false } this.startX = startX this.startY = startY this.endX = endX this.endY = endY return true } open fun onDrawEnd(pxerView: PxerView) { hasEnded = true } fun hasEnded(): Boolean { hasEnded = !hasEnded return !hasEnded } protected fun PxerView.endDraw(previousPxer: ArrayList<Pxer>) { if (previousPxer.isEmpty()) { return } this.currentHistory.addAll(previousPxer) previousPxer.clear() this.setUnrecordedChanges(true) this.finishAddHistory() } }
apache-2.0
c78241197261689e4d1f02924af73374
25.177778
103
0.612054
4.034247
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
example/src/test/java/org/wordpress/android/fluxc/network/rest/wpcom/planoffers/PlanOffersFixtures.kt
1
5269
package org.wordpress.android.fluxc.network.rest.wpcom.planoffers import org.mockito.kotlin.mock import org.wordpress.android.fluxc.model.plans.PlanOffersModel import org.wordpress.android.fluxc.network.rest.wpcom.planoffers.PlanOffersRestClient.PlanOffersResponse import org.wordpress.android.fluxc.network.rest.wpcom.planoffers.PlanOffersRestClient.PlanOffersResponse.Feature import org.wordpress.android.fluxc.network.rest.wpcom.planoffers.PlanOffersRestClient.PlanOffersResponse.Group import org.wordpress.android.fluxc.network.rest.wpcom.planoffers.PlanOffersRestClient.PlanOffersResponse.Plan import org.wordpress.android.fluxc.network.rest.wpcom.planoffers.PlanOffersRestClient.PlanOffersResponse.PlanId import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOffer import org.wordpress.android.fluxc.persistence.PlanOffersDao.PlanOfferWithDetails val PLAN_OFFER_MODELS = listOf( PlanOffersModel( listOf(1), listOf( PlanOffersModel.Feature("subdomain", "WordPress.com Subdomain", "Subdomain Description"), PlanOffersModel.Feature("jetpack-essentials", "JE Features", "JE Description") ), "WordPress.com Free", "Free", "Best for Getting Started", "Free description", "https://s0.wordpress.com/i/store/mobile/plan-free.png" ), PlanOffersModel( listOf(1003, 1023), listOf( PlanOffersModel.Feature("custom-domain", "Custom Domain Name", "CDN Description"), PlanOffersModel.Feature("support-live", "Email & Live Chat Support", "LS Description"), PlanOffersModel.Feature("no-ads", "Remove WordPress.com Ads", "No Ads Description") ), "WordPress.com Premium", "Premium", "Best for Entrepreneurs and Freelancers", "Premium description", "https://s0.wordpress.com/i/store/mobile/plan-premium.png" ) ) val PLAN_OFFERS_RESPONSE = PlanOffersResponse( listOf( Group("personal", "Personal"), Group("business", "Business") ), listOf( Plan( listOf("personal", "too personal"), listOf(PlanId(1)), listOf("subdomain", "jetpack-essentials"), "WordPress.com Free", "Free", "Best for Getting Started", "Free description", "https://s0.wordpress.com/i/store/mobile/plan-free.png" ), Plan( listOf("business"), listOf(PlanId(1003), PlanId(1023)), listOf("custom-domain", "support-live", "no-ads"), "WordPress.com Premium", "Premium", "Best for Entrepreneurs and Freelancers", "Premium description", "https://s0.wordpress.com/i/store/mobile/plan-premium.png" ) ), listOf( Feature("subdomain", "WordPress.com Subdomain", "Subdomain Description"), Feature("jetpack-essentials", "JE Features", "JE Description"), Feature("custom-domain", "Custom Domain Name", "CDN Description"), Feature("support-live", "Email & Live Chat Support", "LS Description"), Feature("no-ads", "Remove WordPress.com Ads", "No Ads Description") ) ) fun getDatabaseModel( emptyPlanIds: Boolean = false, emptyPlanFeatures: Boolean = false ): PlanOfferWithDetails { return PlanOfferWithDetails( planOffer = PlanOffer( internalPlanId = 0, name = null, shortName = "shortName", tagline = "tagline", description = null, icon = null ), planIds = if (emptyPlanIds) emptyList() else listOf(mock(), mock()), planFeatures = if (emptyPlanFeatures) emptyList() else listOf(mock(), mock(), mock()) ) } fun getDomainModel( emptyPlanIds: Boolean = false, emptyFeatures: Boolean = false ): PlanOffersModel { return PlanOffersModel( planIds = if (emptyPlanIds) null else listOf(100, 200), features = if (emptyFeatures) null else listOf(mock(), mock()), name = "name", shortName = null, tagline = null, description = "description", iconUrl = "iconUrl" ) } fun areSame( domainModel: PlanOffersModel, databaseModel: PlanOfferWithDetails ): Boolean { return domainModel.name == databaseModel.planOffer.name && domainModel.shortName == databaseModel.planOffer.shortName && domainModel.tagline == databaseModel.planOffer.tagline && domainModel.description == databaseModel.planOffer.description && domainModel.iconUrl == databaseModel.planOffer.icon && (domainModel.planIds ?: emptyList()).size == databaseModel.planIds.size && (domainModel.features ?: emptyList()).size == databaseModel.planFeatures.size && domainModel.planIds?.equals(databaseModel.planIds.map { it.productId }) ?: true && databaseModel.planFeatures.map { PlanOffersModel.Feature(id = it.stringId, name = it.name, description = it.description) } == domainModel.features ?: emptyList<PlanOffersModel.Feature>() }
gpl-2.0
98a83e3f9851267bf57a9ea316930b23
43.277311
112
0.636174
4.329499
false
false
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/main/MainViewModel.kt
1
2460
package us.mikeandwan.photos.ui.main import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import us.mikeandwan.photos.authorization.AuthService import us.mikeandwan.photos.domain.ErrorRepository import us.mikeandwan.photos.domain.FileStorageRepository import us.mikeandwan.photos.domain.NavigationStateRepository import java.io.File import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( authService: AuthService, private val navigationStateRepository: NavigationStateRepository, private val fileStorageRepository: FileStorageRepository, private val errorRepository: ErrorRepository ) : ViewModel() { val authStatus = authService.authStatus val enableDrawer = navigationStateRepository.enableDrawer val shouldCloseDrawer = navigationStateRepository.closeNavDrawerSignal val shouldOpenDrawer = navigationStateRepository.openNavDrawerSignal val shouldNavigateBack = navigationStateRepository.navigateBackSignal val navigationRequests = navigationStateRepository.requestedNavigation val navigationArea = navigationStateRepository.navArea val displayError = errorRepository.error fun drawerClosed() { navigationStateRepository.closeNavDrawerCompleted() } fun drawerOpened() { navigationStateRepository.openNavDrawerCompleted() } fun destinationChanged(destinationId: Int) { viewModelScope.launch { navigationStateRepository.onDestinationChanged(destinationId) } } fun navigationBackCompleted() { navigationStateRepository.navigateBackCompleted() } fun navigationRequestCompleted() { navigationStateRepository.requestNavigationCompleted() } fun requestNavDrawerClose() { navigationStateRepository.requestNavDrawerClose() } fun errorDisplayed() { errorRepository.errorDisplayed() } suspend fun clearFileCache() { fileStorageRepository.clearLegacyDatabase() fileStorageRepository.clearShareCache() fileStorageRepository.clearLegacyFiles() } suspend fun saveUploadFile(mediaUri: Uri): File? { return fileStorageRepository.saveFileToUpload(mediaUri) } init { viewModelScope.launch { fileStorageRepository.refreshPendingUploads() } } }
mit
74fe6b91ad856b532c3d81102173bf2d
31.381579
74
0.768293
5.603645
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/MiniGameEntity.kt
1
3021
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.blockball.core.logic.persistence.entity import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.GameStorage import com.github.shynixn.blockball.api.persistence.entity.MiniGame import com.github.shynixn.blockball.api.persistence.entity.Sound /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ open class MiniGameEntity( /** * Arena of the game. */ override val arena: Arena) : GameEntity(arena), MiniGame { /** * Is the lobby countdown active. */ override var lobbyCountDownActive: Boolean = false /** * Actual countdown. */ override var lobbyCountdown: Int = 20 /** * Actual game coutndown. */ override var gameCountdown: Int = 20 /** * Index of the current match time. */ override var matchTimeIndex: Int = 0 /** * Returns if the lobby is full. */ override val isLobbyFull: Boolean get() { val amount = arena.meta.redTeamMeta.maxAmount + arena.meta.blueTeamMeta.maxAmount if (this.ingamePlayersStorage.size >= amount) { return true } return false } /** * Returns the bling sound. */ override val blingSound: Sound = SoundEntity("NOTE_PLING", 1.0, 2.0) /** * Are the players currently waiting in the lobby? */ override var inLobby: Boolean = false /** * Storage for [spectatorPlayers], */ override val spectatorPlayersStorage: MutableMap<Any, GameStorage> = HashMap() /** * List of players which are spectating the game. */ override val spectatorPlayers: List<Any> get() { return spectatorPlayersStorage.keys.toList() } }
apache-2.0
a95a9331b56b47c097dea26393fbcd7a
30.479167
93
0.672294
4.242978
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/model/api/Group.kt
2
671
package com.commit451.gitlab.model.api import android.os.Parcelable import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize @Parcelize data class Group ( @Json(name = "id") var id: Long = 0, @Json(name = "name") var name: String? = null, @Json(name = "path") var path: String? = null, @Json(name = "description") var description: String? = null, @Json(name = "visibility") var visibility: String? = null, @Json(name = "avatar_url") var avatarUrl: String? = null, @Json(name = "web_url") var webUrl: String? = null, @Json(name = "projects") var projects: List<Project>? = null ): Parcelable
apache-2.0
b82fa91099f850942224784c619ff25a
25.84
39
0.637854
3.388889
false
false
false
false
vigilancer/rx-jobqueue
lib/src/test/kotlin/ae/vigilancer/jobqueue/lib/JobsFlowContractTest.kt
1
4203
package ae.vigilancer.jobqueue.lib import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test import rx.Observable import rx.observers.TestSubscriber import rx.schedulers.TestScheduler import java.util.* import java.util.concurrent.TimeUnit @Test class JobsFlowContractTest() { val testScheduler = TestScheduler() class SimpleJob: Job<String>() { companion object { @JvmField val RESULT = "simple.job.result" } override fun run(): Observable<String?> { return Observable.just(RESULT) } } // простая проверка что Job проходит сквозь RequestsManager и результат приходит @Test fun `jobs go through with TestSubscriber`() { val testSubscriber = TestSubscriber<Job<*>>() val rm = RequestsManager() rm.init() rm.toObservable().subscribe(testSubscriber) rm.request(SimpleJob()) testSubscriber.assertNoErrors() assertThat(testSubscriber.onNextEvents).hasSize(1) assertThat(testSubscriber.onNextEvents[0].result).isEqualTo(SimpleJob.RESULT) } // простая проверка что Job проходит сквозь RequestsManager и результат приходит @Test fun `jobs go through with TestScheduler`() { val rm = RequestsManager() rm.init() val result: ArrayList<Job<*>> = ArrayList(0) rm.toObservable().subscribeOn(testScheduler).observeOn(testScheduler) .subscribe { j -> result.add(j) } Observable.just(SimpleJob()).subscribeOn(testScheduler).observeOn(testScheduler) .subscribe{ rm.request(it) } assertThat(result).isEmpty() testScheduler.advanceTimeBy(1, TimeUnit.MINUTES) assertThat(result).hasSize(1) } // проверка что задача отлавливается по uuid @Test fun `can catch job by uuid`() { val result: ArrayList<Job<*>> = ArrayList(0) val rm = RequestsManager() rm.init() val specialJob = SimpleJob() val feed = Observable.just(specialJob, SimpleJob(), SimpleJob(), specialJob) rm.toObservable().subscribeOn(testScheduler).observeOn(testScheduler) .subscribe { j -> if (j.uuid == specialJob.uuid) result.add(j) } feed.subscribeOn(testScheduler).observeOn(testScheduler) .subscribe{ rm.request(it) } assertThat(result).isEmpty() testScheduler.advanceTimeBy(10, TimeUnit.MINUTES) assertThat(result).hasSize(2) assertThat(result[0].uuid).isEqualTo(specialJob.uuid) } // что задача отлавливается по своему типу @Test fun `can catch job by subtype`() { class OtherJob : Job<Int>() { override fun run(): Observable<Int?> { return Observable.just(1) } } val thisJobs: ArrayList<Job<*>> = ArrayList(0) val thatJobs: ArrayList<Job<*>> = ArrayList(0) val rm = RequestsManager() rm.init() val feed = Observable.just(SimpleJob(), SimpleJob(), OtherJob(), OtherJob(), SimpleJob()) rm.toObservable().subscribeOn(testScheduler).observeOn(testScheduler) .subscribe { j -> if (j is SimpleJob) { thisJobs.add(j) } else if (j is OtherJob) { thatJobs.add(j) } } feed.subscribeOn(testScheduler).observeOn(testScheduler) .subscribe{ rm.request(it) } assertThat(thisJobs).isEmpty() assertThat(thatJobs).isEmpty() testScheduler.advanceTimeBy(10, TimeUnit.MINUTES) assertThat(thisJobs).hasSize(3) assertThat(thatJobs).hasSize(2) assertThat(thisJobs[0]).isExactlyInstanceOf(SimpleJob::class.java) assertThat(thatJobs[0]).isExactlyInstanceOf(OtherJob::class.java) } // что несколько одновременных подписчиков получают // одинаковые дубликаты выполненной Job }
isc
4389d9809f7edd094e04626dc2cbd1c7
30.204724
97
0.632854
4.229456
false
true
false
false
toastkidjp/Yobidashi_kt
search/src/main/java/jp/toastkid/search/SearchCategory.kt
1
16939
package jp.toastkid.search import android.net.Uri import android.webkit.URLUtil import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.core.net.toUri import java.util.Locale /** * Web search category. * * @author toastkidjp */ enum class SearchCategory( @StringRes val id: Int, @DrawableRes val iconId: Int, private val host: String, private val generator: (l: String, h: String, q: String) -> String = { _, h, q -> h + Uri.encode(q) } ) { GOOGLE( R.string.google, R.drawable.ic_google, "https://www.google.com/search?q=" ), YAHOO( R.string.search_category_yahoo, R.drawable.ic_yahoo, "https://search.yahoo.com/search?p=" ), YAHOO_JAPAN_REALTIME_SEARCH( R.string.search_category_yahoo_japan_realtime_search, R.drawable.ic_yahoo_japan_realtime_search, "https://search.yahoo.co.jp/realtime/search?p=" ), YAHOO_JAPAN( R.string.search_category_yahoo_japan, R.drawable.ic_yahoo_japan_logo, "https://search.yahoo.co.jp/search?p=" ), SITE_SEARCH( R.string.title_site_search_by_google, R.drawable.ic_site_search, "https://www.google.com/search?q=" ), WOLFRAM_ALPHA( R.string.wolfram_alpha, R.drawable.ic_wolfram_alpha, "https://www.wolframalpha.com/input/?i=" ), BING( R.string.bing, R.drawable.ic_bing_logo, "https://www.bing.com/search?q=" ), DUCKDUCKGO( R.string.search_category_web, R.drawable.ic_duckduckgo, "https://duckduckgo.com/?ia=web&q=" ), AOL( R.string.aol, R.drawable.ic_aol, "https://www.aolsearch.com/search?s_chn=prt_bon-mobile&q=" ), ASK_COM( R.string.search_category_ask_com, R.drawable.ic_ask_com, "https://www.ask.com/web?q=" ), QWANT( R.string.search_category_qwant, R.drawable.ic_qwant, "https://www.qwant.com/?q=" ), GMX( R.string.search_category_gmx, R.drawable.ic_gmx, "https://search.gmx.com/web?q=" ), ECOSIA( R.string.search_category_ecosia, R.drawable.ic_ecosia, "https://www.ecosia.org/search?q=" ), FINDX( R.string.search_category_findx, R.drawable.ic_findx, "https://www.findx.com/search?q=" ), STARTPAGE( R.string.search_category_startpage, R.drawable.ic_startpage, "https://www.startpage.com/sp/search?q=" ), TEOMA( R.string.search_category_teoma, R.drawable.ic_teoma, "https://www.teoma.com/web?q=" ), INFO_COM( R.string.search_category_info_com, R.drawable.ic_info_com, "https://www.info.com/serp?q=" ), LOOKSMART( R.string.search_category_looksmart, R.drawable.ic_looksmart, "https://results.looksmart.com/serp?q=" ), MOJEEK( R.string.search_category_mojeek, R.drawable.ic_mojeek, "https://www.mojeek.com/search?q=" ), PRIVACY_WALL( R.string.search_category_privacy_wall, R.drawable.ic_privacywall, "https://www.privacywall.org/search/secure/?q=" ), BRAVE( R.string.search_category_brave, R.drawable.ic_brave, "https://search.brave.com/search?source=web&q=" ), ALOHA_FIND( R.string.search_category_aloha_find, R.drawable.ic_alohafind, "https://alohafind.com/search/?q=" ), GIVERO( R.string.givero, R.drawable.ic_givero, "https://www.givero.com/search?q=" ), YOU_COM( R.string.you_com, R.drawable.ic_you_com, "https://you.com/search?q=" ), YANDEX( R.string.search_category_yandex, R.drawable.ic_yandex, "https://www.yandex.com/search/?text=" ), RAMBLER( R.string.search_category_rambler, R.drawable.ic_rambler, "https://nova.rambler.ru/search?query=" ), GOO( R.string.goo, R.drawable.ic_goo, "https://search.goo.ne.jp/web.jsp?IE=UTF-8&OE=UTF-8&MT=" ), SIFY( R.string.sify, R.drawable.ic_sify, "http://search.sify.com/search.php?q=" ), NAVER( R.string.naver, R.drawable.ic_naver, "https://search.naver.com/search.naver?ie=utf8&query=" ), DAUM( R.string.daum, R.drawable.ic_daum, "https://search.daum.net/search?w=tot&q=" ), SCHOLAR( R.string.search_category_google_scholar, R.drawable.ic_google_scholar, "https://scholar.google.com/scholar?q=" ), IMAGE( R.string.search_category_image, R.drawable.ic_image_search, "https://www.google.co.jp/search?site=imghp&tbm=isch&q=" ), YOUTUBE( R.string.search_category_youtube, R.drawable.ic_video, "https://www.youtube.com/results?search_query=" ), BBC( R.string.search_category_bbc, R.drawable.ic_bbc, "https://www.bbc.co.uk/search?q=" ), WIKIPEDIA( R.string.search_category_wikipedia, R.drawable.ic_wikipedia, "https://%s.m.wikipedia.org/w/index.php?search=", { l, h, q -> String.format(h, l) + Uri.encode(q) } ), WEBSTER( R.string.search_category_webster, R.drawable.ic_webster, "https://www.merriam-webster.com/dictionary/" ), WEBLIO( R.string.search_category_weblio, R.drawable.ic_weblio, "https://ejje.weblio.jp/content/" ), DICTIONARY_COM( R.string.search_category_dictionary_com, R.drawable.ic_dictionary_com, "https://www.dictionary.com/browse/" ), INTERNET_ARCHIVE( R.string.search_category_internet_archive, R.drawable.ic_internet_archive, "https://archive.org/search.php?query=", { l, h, q -> String.format(h, l) + Uri.encode(q) } ), WAYBACK_MACHINE( R.string.wayback_machine, R.drawable.ic_wayback_machine, "https://web.archive.org/web/*/" ), LINKED_IN( R.string.linked_in, R.drawable.ic_linked_in, "https://www.linkedin.com/jobs/search?keywords=" ), TWITTER( R.string.search_category_twitter, R.drawable.ic_twitter, "https://mobile.twitter.com/search?src=typd&q=" ), REDDIT( R.string.search_category_reddit, R.drawable.ic_reddit, "https://www.reddit.com/search/?q=" ), FACEBOOK( R.string.search_category_facebook, R.drawable.ic_facebook, "https://m.facebook.com/public/" ), INSTAGRAM( R.string.search_category_instagram, R.drawable.ic_instagram_logo, "https://www.instagram.com/explore/tags/" ), FLICKR( R.string.search_category_flickr, R.drawable.ic_flickr, "https://www.flickr.com/search/?text=" ), PX500( R.string.search_category_500px, R.drawable.ic_500px, "https://500px.com/search?type=photos&sort=relevance&q=" ), WIKIMEDIA_COMMONS( R.string.search_category_wikimedia_commons, R.drawable.ic_wikimedia_commons, "https://commons.wikimedia.org/w/index.php?search=" ), MAP( R.string.search_category_map, R.drawable.ic_map, "https://www.google.co.jp/maps/place/" ), OPEN_STREET_MAP( R.string.search_category_open_street_map, R.drawable.ic_openstreetmap, "https://www.openstreetmap.org/search?query=" ), OPEN_WEATHER_MAP( R.string.search_category_open_weather, R.drawable.ic_open_weather, "https://openweathermap.org/find?q=" ), APPS( R.string.search_category_apps, R.drawable.ic_google_play, "https://play.google.com/store/search?q=" ), YELP( R.string.yelp, R.drawable.ic_yelp, "https://www.yelp.com/search?find_desc=" ), ESPN( R.string.espn, R.drawable.ic_espn, "https://www.espn.com/search/_/q/" ), IMDB( R.string.imdb, R.drawable.ic_imdb, "https://www.imdb.com/find?q=" ), GUTENBERG( R.string.gutenberg, R.drawable.ic_local_library_black, "http://www.gutenberg.org/ebooks/search/?query=" ), AMAZON( R.string.search_category_shopping, R.drawable.ic_amazon, "https://www.amazon.co.jp/s/ref=nb_sb_noss?field-keywords=", { l, h, q -> if (Locale.JAPANESE.language == l) { h + Uri.encode(q) } else { "https://www.amazon.com/s/ref=nb_sb_noss?field-keywords=" + Uri.encode(q) } } ), EBAY( R.string.search_category_ebay, R.drawable.ic_ebay, "https://www.ebay.com/sch/i.html?_nkw=" ), QUORA( R.string.search_category_quora, R.drawable.ic_quora, "https://www.quora.com/search?q=", { l, h, q -> if (Locale.JAPANESE.language == l) { "https://jp.quora.com/search?q=${Uri.encode(q)}" } else { "$h${Uri.encode(q)}" } } ), TECHNICAL_QA( R.string.search_category_stack_overflow, R.drawable.ic_stackoverflow, "https://stackoverflow.com/search?q=" ), BGR( R.string.search_category_bgr, R.drawable.ic_bgr, "https://bgr.com/?s=%s", { _, h, q -> String.format(h, Uri.encode(q)) } ), HACKER_NEWS( R.string.search_category_hacker_news, R.drawable.ic_hacker_news, "https://hn.algolia.com/?q=" ), TECHNOLOGY( R.string.search_category_technology, R.drawable.ic_techcrunch, "http://jp.techcrunch.com/search/", {l, h, q -> if (Locale.JAPANESE.language == l) { h + Uri.encode(q) } "https://techcrunch.com/search/" + Uri.encode(q) } ), GIZMODE( R.string.search_category_gizmode, R.drawable.ic_gizmodo, "https://gizmodo.com/search?q=" ), GITHUB( R.string.search_category_github, R.drawable.ic_github, "https://github.com/search?utf8=%E2%9C%93&type=&q=" ), MVNREPOSITORY( R.string.search_category_mvnrepository, R.drawable.ic_mvn, "https://mvnrepository.com/search?q=" ), ANDROID_DEVELOPER( R.string.search_category_android_developer, R.drawable.ic_android_developer, "https://developer.android.com/s/results?q=" ), MEDIUM( R.string.medium, R.drawable.ic_medium, "https://medium.com/search?q=" ), TUMBLR( R.string.tumblr, R.drawable.ic_tumblr, "https://www.tumblr.com/search/" ), TED( R.string.ted, R.drawable.ic_ted, "https://www.ted.com/search?q=" ), SLIDESHARE( R.string.slideshare, R.drawable.ic_slideshare, "https://www.slideshare.net/search/slideshow?q=" ), SPEAKERDECK( R.string.speakerdeck, R.drawable.ic_speakerdeck, "https://cse.google.com/cse?cx=010150859881542981030%3Ahqhxyxpwtc4&q=" ), ECONOMIST( R.string.search_category_economist, R.drawable.ic_the_economist_logo, "https://www.economist.com/search?q=" ), FT( R.string.financial_times, R.drawable.ic_financial_times, "https://www.ft.com/search?q=" ), MORNINGSTAR( R.string.morningstar, R.drawable.ic_morningstar, "https://www.morningstar.com/search?query=" ), FORBES( R.string.forbes, R.drawable.ic_forbes, "https://www.forbes.com/search?q=" ), MY_INDEX( R.string.my_index, R.drawable.ic_myindex, "https://myindex.jp/search.php?w=" ), SEEKING_ALPHA( R.string.seeking_alpha, R.drawable.ic_seeking_alpha, "https://seekingalpha.com/search?q=" ), YAHOO_JAPAN_FINANCE( R.string.yahoo_japan_finance, R.drawable.ic_yahoo_japan_finance, "https://info.finance.yahoo.co.jp/search/?query=" ), BUZZFEED( R.string.buzzfeed, R.drawable.ic_buzzfeed, "https://www.buzzfeed.com/jp/search?q=" ), LIVEJOURNAL( R.string.livejournal, R.drawable.ic_livejournal, "https://www.livejournal.com/gsearch/?engine=google&cx=partner-pub-5600223439108080:3711723852&q=" ), GOOGLE_NEWS( R.string.google_news, R.drawable.ic_google_news, "https://news.google.com/search?q=" ), JAPAN_SEARCH( R.string.search_category_japan_search, R.drawable.ic_japan_search, "https://jpsearch.go.jp/csearch/jps-cross?csid=jps-cross&keyword=" ) ; /** * Make search URL with query. * * @param query Query string * @param currentUrl * @return Search result URL */ fun make(query: String, currentUrl: String?): String { if (this == SITE_SEARCH && currentUrl != null) { return SiteSearchUrlGenerator().invoke(currentUrl, query) } return generate( Locale.getDefault().language, host, query ) } /** * Generate URL. * * @param l Locale string * @param h Host of search result * @param q Search query * * @return Search result URL */ private fun generate(l: String, h: String, q: String): String = generator(l, h, q) companion object { private val hostAndCategories = values() .filter { it != SITE_SEARCH && it != MAP && it != IMAGE } .map { val key = if (it == YAHOO_JAPAN_REALTIME_SEARCH) "search.yahoo.co.jp/realtime" else it.host.toUri().host key to it } .toMap() fun findByUrlOrNull(url: String?): SearchCategory? { val key = makeKey(url) return if (key.isNullOrEmpty()) null else hostAndCategories[key] } private fun makeKey(url: String?): String? { if (url.isNullOrBlank() || URLUtil.isValidUrl(url).not()) { return null } val uri = url.toUri() if (url.contains("/realtime/").not()) { return uri.host } val pathSegments = uri.pathSegments val firstPath = if (pathSegments.size >= 2) pathSegments[0] ?: "" else "" return "${uri.host}/$firstPath" } /** * Find [SearchCategory] by search category. * * @param category Search category * @return [SearchCategory] */ fun findByCategory(category: String?): SearchCategory { val locale = Locale.getDefault() val target = category?.uppercase(locale) ?: "" return values().find { it.name == target } ?: getDefault() } /** * Find index in values by search category string form. * * @param category Search category string form * * @return index */ fun findIndex(category: String): Int { val locale = Locale.getDefault() return values().find { it.name == category.uppercase(locale) } ?.ordinal ?: getDefault().ordinal } /** * Get default object. * * @return GOOGLE */ fun getDefault(): SearchCategory = GOOGLE /** * Get default category name. * * @return "GOOGLE" */ fun getDefaultCategoryName(): String = getDefault().name } }
epl-1.0
af048c75509dcac2f130522123638b9b
29.25
132
0.520161
3.566856
false
false
false
false
chrisbanes/tivi
common/ui/compose/src/main/java/app/tivi/common/compose/ui/SearchTextField.kt
1
2496
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.common.compose.ui import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.TextFieldValue import app.tivi.common.ui.resources.R as UiR @Composable fun SearchTextField( value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, hint: String, modifier: Modifier = Modifier, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions() ) { OutlinedTextField( value = value, onValueChange = onValueChange, trailingIcon = { AnimatedVisibility( visible = value.text.isNotEmpty(), enter = fadeIn(), exit = fadeOut() ) { IconButton( onClick = { onValueChange(TextFieldValue()) } ) { Icon( imageVector = Icons.Default.Clear, contentDescription = stringResource(UiR.string.cd_clear_text) ) } } }, placeholder = { Text(text = hint) }, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, maxLines = 1, singleLine = true, modifier = modifier ) }
apache-2.0
17f3c2d3e04a081f570c12a36a9c6cb7
34.15493
85
0.682692
4.932806
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_cgms/src/main/java/no/nordicsemi/android/cgms/data/CGMManager.kt
1
15140
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.cgms.data import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.content.Context import android.util.Log import android.util.SparseArray import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import no.nordicsemi.android.ble.BleManager import no.nordicsemi.android.ble.common.callback.RecordAccessControlPointResponse import no.nordicsemi.android.ble.common.callback.battery.BatteryLevelResponse import no.nordicsemi.android.ble.common.callback.cgm.CGMFeatureResponse import no.nordicsemi.android.ble.common.callback.cgm.CGMSpecificOpsControlPointResponse import no.nordicsemi.android.ble.common.callback.cgm.CGMStatusResponse import no.nordicsemi.android.ble.common.callback.cgm.ContinuousGlucoseMeasurementResponse import no.nordicsemi.android.ble.common.data.RecordAccessControlPointData import no.nordicsemi.android.ble.common.data.cgm.CGMSpecificOpsControlPointData import no.nordicsemi.android.ble.common.profile.RecordAccessControlPointCallback import no.nordicsemi.android.ble.common.profile.cgm.CGMSpecificOpsControlPointCallback import no.nordicsemi.android.ble.ktx.asValidResponseFlow import no.nordicsemi.android.ble.ktx.suspend import no.nordicsemi.android.ble.ktx.suspendForValidResponse import no.nordicsemi.android.cgms.repository.toList import no.nordicsemi.android.logger.NordicLogger import no.nordicsemi.android.service.ConnectionObserverAdapter import no.nordicsemi.android.utils.launchWithCatch import java.util.* val CGMS_SERVICE_UUID: UUID = UUID.fromString("0000181F-0000-1000-8000-00805f9b34fb") private val CGM_STATUS_UUID = UUID.fromString("00002AA9-0000-1000-8000-00805f9b34fb") private val CGM_FEATURE_UUID = UUID.fromString("00002AA8-0000-1000-8000-00805f9b34fb") private val CGM_MEASUREMENT_UUID = UUID.fromString("00002AA7-0000-1000-8000-00805f9b34fb") private val CGM_OPS_CONTROL_POINT_UUID = UUID.fromString("00002AAC-0000-1000-8000-00805f9b34fb") private val RACP_UUID = UUID.fromString("00002A52-0000-1000-8000-00805f9b34fb") private val BATTERY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb") private val BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb") internal class CGMManager( context: Context, private val scope: CoroutineScope, private val logger: NordicLogger ) : BleManager(context) { private var cgmStatusCharacteristic: BluetoothGattCharacteristic? = null private var cgmFeatureCharacteristic: BluetoothGattCharacteristic? = null private var cgmMeasurementCharacteristic: BluetoothGattCharacteristic? = null private var cgmSpecificOpsControlPointCharacteristic: BluetoothGattCharacteristic? = null private var recordAccessControlPointCharacteristic: BluetoothGattCharacteristic? = null private val records: SparseArray<CGMRecord> = SparseArray<CGMRecord>() private var batteryLevelCharacteristic: BluetoothGattCharacteristic? = null private var secured = false private var recordAccessRequestInProgress = false private var sessionStartTime: Long = 0 private val data = MutableStateFlow(CGMData()) val dataHolder = ConnectionObserverAdapter<CGMData>() init { connectionObserver = dataHolder data.onEach { dataHolder.setValue(it) }.launchIn(scope) } override fun getGattCallback(): BleManagerGattCallback { return CGMManagerGattCallback() } override fun log(priority: Int, message: String) { logger.log(priority, message) } override fun getMinLogPriority(): Int { return Log.VERBOSE } private inner class CGMManagerGattCallback : BleManagerGattCallback() { override fun initialize() { super.initialize() setNotificationCallback(cgmMeasurementCharacteristic).asValidResponseFlow<ContinuousGlucoseMeasurementResponse>() .onEach { if (sessionStartTime == 0L && !recordAccessRequestInProgress) { val timeOffset = it.items.minOf { it.timeOffset } sessionStartTime = System.currentTimeMillis() - timeOffset * 60000L } it.items.map { val timestamp = sessionStartTime + it.timeOffset * 60000L val item = CGMRecord(it.timeOffset, it.glucoseConcentration, timestamp) records.put(item.sequenceNumber, item) } data.value = data.value.copy(records = records.toList()) }.launchIn(scope) setIndicationCallback(cgmSpecificOpsControlPointCharacteristic).asValidResponseFlow<CGMSpecificOpsControlPointResponse>() .onEach { if (it.isOperationCompleted) { when (it.requestCode) { CGMSpecificOpsControlPointCallback.CGM_OP_CODE_START_SESSION -> sessionStartTime = System.currentTimeMillis() CGMSpecificOpsControlPointCallback.CGM_OP_CODE_STOP_SESSION -> sessionStartTime = 0 } } else { when (it.requestCode) { CGMSpecificOpsControlPointCallback.CGM_OP_CODE_START_SESSION -> if (it.errorCode == CGMSpecificOpsControlPointCallback.CGM_ERROR_PROCEDURE_NOT_COMPLETED) { sessionStartTime = 0 } CGMSpecificOpsControlPointCallback.CGM_OP_CODE_STOP_SESSION -> sessionStartTime = 0 } } }.launchIn(scope) setIndicationCallback(recordAccessControlPointCharacteristic).asValidResponseFlow<RecordAccessControlPointResponse>() .onEach { if (it.isOperationCompleted && it.wereRecordsFound() && it.numberOfRecords > 0) { onRecordsReceived(it) } else if (it.isOperationCompleted && !it.wereRecordsFound()) { onNoRecordsFound() } else if (it.isOperationCompleted && it.wereRecordsFound()) { onOperationCompleted(it) } else if (it.errorCode > 0) { onError(it) } }.launchIn(scope) setNotificationCallback(batteryLevelCharacteristic).asValidResponseFlow<BatteryLevelResponse>() .onEach { data.value = data.value.copy(batteryLevel = it.batteryLevel) }.launchIn(scope) enableNotifications(cgmMeasurementCharacteristic).enqueue() enableIndications(cgmSpecificOpsControlPointCharacteristic).enqueue() enableIndications(recordAccessControlPointCharacteristic).enqueue() enableNotifications(batteryLevelCharacteristic).enqueue() scope.launchWithCatch { val cgmResponse = readCharacteristic(cgmFeatureCharacteristic).suspendForValidResponse<CGMFeatureResponse>() [email protected] = cgmResponse.features.e2eCrcSupported } scope.launchWithCatch { val response = readCharacteristic(cgmStatusCharacteristic).suspendForValidResponse<CGMStatusResponse>() if (response.status?.sessionStopped == false) { sessionStartTime = System.currentTimeMillis() - response.timeOffset * 60000L } } scope.launchWithCatch { if (sessionStartTime == 0L) { writeCharacteristic( cgmSpecificOpsControlPointCharacteristic, CGMSpecificOpsControlPointData.startSession(secured), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).suspend() } } } private suspend fun onRecordsReceived(response: RecordAccessControlPointResponse) { if (response.numberOfRecords > 0) { if (records.size() > 0) { val sequenceNumber = records.keyAt(records.size() - 1) + 1 writeCharacteristic( recordAccessControlPointCharacteristic, RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo( sequenceNumber ), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).suspend() } else { writeCharacteristic( recordAccessControlPointCharacteristic, RecordAccessControlPointData.reportAllStoredRecords(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).suspend() } } else { recordAccessRequestInProgress = false data.value = data.value.copy(requestStatus = RequestStatus.SUCCESS) } } private fun onNoRecordsFound() { recordAccessRequestInProgress = false data.value = data.value.copy(requestStatus = RequestStatus.SUCCESS) } private fun onOperationCompleted(response: RecordAccessControlPointResponse) { when (response.requestCode) { RecordAccessControlPointCallback.RACP_OP_CODE_ABORT_OPERATION -> data.value = data.value.copy(requestStatus = RequestStatus.ABORTED) else -> { recordAccessRequestInProgress = false data.value = data.value.copy(requestStatus = RequestStatus.SUCCESS) } } } private fun onError(response: RecordAccessControlPointResponse) { if (response.errorCode == RecordAccessControlPointCallback.RACP_ERROR_OP_CODE_NOT_SUPPORTED) { data.value = data.value.copy(requestStatus = RequestStatus.NOT_SUPPORTED) } else { data.value = data.value.copy(requestStatus = RequestStatus.FAILED) } } override fun isRequiredServiceSupported(gatt: BluetoothGatt): Boolean { gatt.getService(CGMS_SERVICE_UUID)?.run { cgmStatusCharacteristic = getCharacteristic(CGM_STATUS_UUID) cgmFeatureCharacteristic = getCharacteristic(CGM_FEATURE_UUID) cgmMeasurementCharacteristic = getCharacteristic(CGM_MEASUREMENT_UUID) cgmSpecificOpsControlPointCharacteristic = getCharacteristic(CGM_OPS_CONTROL_POINT_UUID) recordAccessControlPointCharacteristic = getCharacteristic(RACP_UUID) } gatt.getService(BATTERY_SERVICE_UUID)?.run { batteryLevelCharacteristic = getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC_UUID) } return cgmMeasurementCharacteristic != null && cgmSpecificOpsControlPointCharacteristic != null && recordAccessControlPointCharacteristic != null && cgmStatusCharacteristic != null && cgmFeatureCharacteristic != null } override fun onServicesInvalidated() { cgmStatusCharacteristic = null cgmFeatureCharacteristic = null cgmMeasurementCharacteristic = null cgmSpecificOpsControlPointCharacteristic = null recordAccessControlPointCharacteristic = null batteryLevelCharacteristic = null } } private fun clear() { records.clear() } fun requestLastRecord() { if (recordAccessControlPointCharacteristic == null) return clear() data.value = data.value.copy(requestStatus = RequestStatus.PENDING) recordAccessRequestInProgress = true scope.launchWithCatch { writeCharacteristic( recordAccessControlPointCharacteristic, RecordAccessControlPointData.reportLastStoredRecord(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).suspend() } } fun requestFirstRecord() { if (recordAccessControlPointCharacteristic == null) return clear() data.value = data.value.copy(requestStatus = RequestStatus.PENDING) recordAccessRequestInProgress = true scope.launchWithCatch { writeCharacteristic( recordAccessControlPointCharacteristic, RecordAccessControlPointData.reportFirstStoredRecord(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).suspend() } } fun requestAllRecords() { if (recordAccessControlPointCharacteristic == null) return clear() data.value = data.value.copy(requestStatus = RequestStatus.PENDING) recordAccessRequestInProgress = true scope.launchWithCatch { writeCharacteristic( recordAccessControlPointCharacteristic, RecordAccessControlPointData.reportNumberOfAllStoredRecords(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).suspend() } } }
bsd-3-clause
836bd3ab2664c0de1bb3c56cb54b10f2
45.728395
133
0.659643
5.183156
false
false
false
false
neva-dev/javarel
tooling/gradle-plugin/src/main/kotlin/com/neva/javarel/gradle/internal/Formats.kt
1
2037
package com.neva.javarel.gradle.internal import com.fasterxml.jackson.core.util.DefaultIndenter import com.fasterxml.jackson.core.util.DefaultPrettyPrinter import com.fasterxml.jackson.databind.ObjectMapper import org.apache.commons.lang3.time.DurationFormatUtils import org.apache.commons.validator.routines.UrlValidator import java.text.SimpleDateFormat import java.util.* object Formats { val URL_VALIDATOR = UrlValidator(arrayOf("http", "https"), UrlValidator.ALLOW_LOCAL_URLS) val JSON_MAPPER = { val printer = DefaultPrettyPrinter() printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE) ObjectMapper().writer(printer) }() fun <T> fromJson(json: String, clazz: Class<T>): T { return ObjectMapper().readValue(json, clazz) } fun toJson(value: Any): String? { return JSON_MAPPER.writeValueAsString(value) } fun toBase64(value: String): String { return Base64.getEncoder().encodeToString(value.toByteArray()) } fun bytesToHuman(bytes: Long): String { if (bytes < 1024) { return bytes.toString() + " B" } else if (bytes < 1024 * 1024) { return (bytes / 1024).toString() + " KB" } else if (bytes < 1024 * 1024 * 1024) { return String.format("%.2f MB", bytes / (1024.0 * 1024.0)) } else { return String.format("%.2f GB", bytes / (1024.0 * 1024.0 * 1024.0)) } } fun percent(current: Int, total: Int): String { return percent(current.toLong(), total.toLong()) } fun percent(current: Long, total: Long): String { val value: Double = if (total == 0L) 0.0 else current.toDouble() / total.toDouble() return "${"%.2f".format(value * 100.0)}%" } fun duration(millis: Long): String { return DurationFormatUtils.formatDurationHMS(millis) } fun date(date: Date = Date(), format: String = "EEE MM-dd-yy hh:mm:ss"): String { return SimpleDateFormat(format).format(date) } }
apache-2.0
ad808c75202e3ea6e7b4fac30d2bc28f
31.349206
93
0.643594
3.947674
false
false
false
false
MyDogTom/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/Detektion.kt
1
1035
package io.gitlab.arturbosch.detekt.core import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Notification import io.gitlab.arturbosch.detekt.api.ProjectMetric import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.com.intellij.util.keyFMap.KeyFMap /** * @author Artur Bosch */ data class DetektResult(override val findings: Map<String, List<Finding>>, override val notifications: MutableCollection<Notification>) : Detektion { private var userData = KeyFMap.EMPTY_MAP private val _metrics = ArrayList<ProjectMetric>() override val metrics: Collection<ProjectMetric> = _metrics override fun add(projectMetric: ProjectMetric) { _metrics.add(projectMetric) } override fun add(notification: Notification) { notifications.add(notification) } override fun <V> getData(key: Key<V>): V? = userData.get(key) override fun <V> addData(key: Key<V>, value: V) { userData = userData.plus(key, value) } }
apache-2.0
623464385c71dbbf17b1568bfa641a01
30.363636
80
0.771014
3.532423
false
false
false
false
rei-m/android_hyakuninisshu
feature/trainingstarter/src/main/java/me/rei_m/hyakuninisshu/feature/trainingstarter/ui/ExamPracticeTrainingStarterFragment.kt
1
3327
/* * Copyright (c) 2020. Rei Matsushita. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package me.rei_m.hyakuninisshu.feature.trainingstarter.ui 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.fragment.findNavController import me.rei_m.hyakuninisshu.feature.corecomponent.helper.EventObserver import me.rei_m.hyakuninisshu.feature.trainingstarter.databinding.TrainingStarterFragmentBinding import me.rei_m.hyakuninisshu.feature.trainingstarter.di.TrainingStarterComponent import me.rei_m.hyakuninisshu.state.question.model.Referer import me.rei_m.hyakuninisshu.state.training.model.DisplayAnimationSpeedCondition import me.rei_m.hyakuninisshu.state.training.model.DisplayStyleCondition import me.rei_m.hyakuninisshu.state.training.model.InputSecondCondition import javax.inject.Inject class ExamPracticeTrainingStarterFragment : Fragment() { @Inject lateinit var viewModelFactory: ExamPracticeTrainingStarterViewModel.Factory private var _binding: TrainingStarterFragmentBinding? = null private val binding get() = _binding!! private val viewModel by viewModels<ExamPracticeTrainingStarterViewModel> { viewModelFactory } override fun onCreate(savedInstanceState: Bundle?) { (requireActivity() as TrainingStarterComponent.Injector) .trainingStarterComponent() .create() .inject(this) super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = TrainingStarterFragmentBinding.inflate(inflater, container, false) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onDestroyView() { _binding = null super.onDestroyView() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewModel = viewModel viewModel.onReadyEvent.observe(viewLifecycleOwner, EventObserver { val action = ExamPracticeTrainingStarterFragmentDirections .actionExamPracticeTrainingStarterToQuestion( questionId = it, kamiNoKuStyle = DisplayStyleCondition.KANJI, shimoNoKuStyle = DisplayStyleCondition.KANA, inputSecond = InputSecondCondition.NONE, animationSpeed = DisplayAnimationSpeedCondition.NORMAL, referer = Referer.Training ) findNavController().navigate(action) }) } }
apache-2.0
b6745a12e9b694f7b9105e2f54affba6
37.686047
98
0.729185
4.90708
false
false
false
false
alashow/music-android
modules/core-playback/src/main/java/tm/alashow/datmusic/playback/models/MediaId.kt
1
3372
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.playback.models import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.firstOrNull import timber.log.Timber import tm.alashow.datmusic.data.db.daos.AlbumsDao import tm.alashow.datmusic.data.db.daos.ArtistsDao import tm.alashow.datmusic.data.db.daos.AudiosDao import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams.Companion.withTypes import tm.alashow.datmusic.domain.entities.Audio const val MEDIA_TYPE_AUDIO = "Media.Audio" const val MEDIA_TYPE_ARTIST = "Media.Artist" const val MEDIA_TYPE_ALBUM = "Media.Album" const val MEDIA_TYPE_AUDIO_QUERY = "Media.AudioQuery" const val MEDIA_TYPE_AUDIO_MINERVA_QUERY = "Media.AudioMinervaQuery" const val MEDIA_TYPE_AUDIO_FLACS_QUERY = "Media.AudioFlacsQuery" private const val MEDIA_ID_SEPARATOR = " | " data class MediaId( val type: String = MEDIA_TYPE_AUDIO, val value: String = "0", val index: Int = 0, val caller: String = CALLER_SELF ) { companion object { const val CALLER_SELF = "self" const val CALLER_OTHER = "other" } override fun toString(): String { return type + MEDIA_ID_SEPARATOR + value + MEDIA_ID_SEPARATOR + index + MEDIA_ID_SEPARATOR + caller } } fun String.toMediaId(): MediaId { val parts = split(MEDIA_ID_SEPARATOR) val type = parts[0] val knownTypes = listOf( MEDIA_TYPE_AUDIO, MEDIA_TYPE_ARTIST, MEDIA_TYPE_ALBUM, MEDIA_TYPE_AUDIO_QUERY, MEDIA_TYPE_AUDIO_MINERVA_QUERY, MEDIA_TYPE_AUDIO_FLACS_QUERY ) if (type !in knownTypes) { Timber.e("Unknown media type: $type") return MediaId() } return if (parts.size > 1) MediaId(type, parts[1], parts[2].toInt(), parts[3]) else MediaId() } suspend fun MediaId.toAudioList(audiosDao: AudiosDao, artistsDao: ArtistsDao, albumsDao: AlbumsDao): List<Audio>? = when (type) { MEDIA_TYPE_AUDIO -> listOfNotNull(audiosDao.entry(value).firstOrNull()) MEDIA_TYPE_ALBUM -> albumsDao.entry(value).firstOrNull()?.audios MEDIA_TYPE_ARTIST -> artistsDao.entry(value).firstOrNull()?.audios MEDIA_TYPE_AUDIO_QUERY, MEDIA_TYPE_AUDIO_MINERVA_QUERY, MEDIA_TYPE_AUDIO_FLACS_QUERY -> { val params = DatmusicSearchParams(value).run { when (type) { MEDIA_TYPE_AUDIO_MINERVA_QUERY -> withTypes(DatmusicSearchParams.BackendType.MINERVA) MEDIA_TYPE_AUDIO_FLACS_QUERY -> withTypes(DatmusicSearchParams.BackendType.FLACS) else -> this } } audiosDao.entries(params).first() } else -> emptyList() } suspend fun MediaId.toQueueTitle(audiosDao: AudiosDao, artistsDao: ArtistsDao, albumsDao: AlbumsDao): QueueTitle = when (type) { MEDIA_TYPE_AUDIO -> QueueTitle(QueueTitle.Type.AUDIO, audiosDao.entry(value).firstOrNull()?.title) MEDIA_TYPE_ARTIST -> QueueTitle(QueueTitle.Type.ARTIST, artistsDao.entry(value).firstOrNull()?.name) MEDIA_TYPE_ALBUM -> QueueTitle(QueueTitle.Type.ALBUM, albumsDao.entry(value).firstOrNull()?.title) MEDIA_TYPE_AUDIO_QUERY, MEDIA_TYPE_AUDIO_MINERVA_QUERY, MEDIA_TYPE_AUDIO_FLACS_QUERY -> QueueTitle(QueueTitle.Type.SEARCH, value) else -> QueueTitle() }
apache-2.0
199237e712eab45381a137b2df47c752
36.88764
133
0.697212
3.549474
false
false
false
false
prfarlow1/nytc-meet
app/src/main/kotlin/org/needhamtrack/nytc/screens/login/SplashPresenter.kt
1
2226
package org.needhamtrack.nytc.screens.login import android.app.Activity import com.google.android.gms.common.GoogleApiAvailability import org.needhamtrack.nytc.base.BasePresenter import org.needhamtrack.nytc.base.PresenterConfiguration class SplashPresenter(view: SplashContract.View, configuration: PresenterConfiguration) : BasePresenter<SplashContract.View>(view, configuration), SplashContract.Presenter { override fun apiCheck() { when { view?.isGooglePlayServicesAvailable() == false -> acquireGooglePlayServices() userSettings.accountName.isEmpty() -> view?.chooseAccount() view?.isOnline() == false -> view?.showNoNetworkToast() else -> view?.goToEventSelectScreen() } } private fun acquireGooglePlayServices() { val apiAvailability = GoogleApiAvailability.getInstance() val connectionStatusCode = view?.getConnectionStatusCode(apiAvailability) val statusCode = connectionStatusCode ?: 0 if (apiAvailability.isUserResolvableError(statusCode)) { view?.showGooglePlayServicesAvailabilityErrorDialog(statusCode) } } override fun chooseAccount() { if (view?.hasAccountPermissions() == true) { val accountName = userSettings.accountName if (accountName.isNotEmpty()) { view?.goToEventSelectScreen() } else { view?.requestAccountPicker() } } else { view?.requestAccountPermission() } } override fun onActivityResult(requestCode: Int, resultCode: Int, accountName: String?) { when (requestCode) { SplashActivity.REQUEST_ACCOUNT_PICKER -> { if (resultCode == Activity.RESULT_OK && accountName?.isNotEmpty() == true) { userSettings.accountName = accountName apiCheck() } } SplashActivity.REQUEST_GOOGLE_PLAY_SERVICES -> { if (resultCode == Activity.RESULT_OK) { apiCheck() } else { view?.showNoGooglePlayServicesToast() } } } } }
mit
befe54c3ba5d0e17a8516b11b133675a
36.745763
92
0.617251
5.496296
false
true
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/times/SunView.kt
1
14382
package com.byagowi.persiancalendar.ui.calendar.times import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.content.Context import android.content.res.Resources import android.graphics.* import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.view.animation.DecelerateInterpolator import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.utils.formatNumber import com.byagowi.persiancalendar.utils.getAppFont import com.byagowi.persiancalendar.utils.isRTL import io.github.persiancalendar.praytimes.Clock import io.github.persiancalendar.praytimes.PrayTimes import java.util.* import kotlin.math.PI import kotlin.math.abs import kotlin.math.cos /** * @author MEHDI DIMYADI * MEHDIMYADI */ class SunView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs), ValueAnimator.AnimatorUpdateListener { private val FULL_DAY = Clock(24, 0).toInt().toFloat() private val HALF_DAY = Clock(12, 0).toInt().toFloat() private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { typeface = getAppFont(context) } private val sunPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } private var sunRaisePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeWidth = 7f pathEffect = DashPathEffect(floatArrayOf(3f, 7f), 0f) /* Sun rays effect */ } private val dayPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL_AND_STROKE } @ColorInt private var horizonColor: Int = 0 @ColorInt private var timelineColor: Int = 0 @ColorInt private var taggingColor: Int = 0 @ColorInt private var nightColor: Int = 0 @ColorInt private var dayColor: Int = 0 @ColorInt private var daySecondColor: Int = 0 @ColorInt private var sunColor: Int = 0 @ColorInt private var sunBeforeMiddayColor: Int = 0 @ColorInt private var sunAfterMiddayColor: Int = 0 @ColorInt private var sunEveningColor: Int = 0 @ColorInt private var sunriseTextColor: Int = 0 @ColorInt private var middayTextColor: Int = 0 @ColorInt private var sunsetTextColor: Int = 0 @ColorInt private var colorTextNormal: Int = 0 @ColorInt private var colorTextSecond: Int = 0 internal var width: Int = 0 internal var height: Int = 0 lateinit var curvePath: Path lateinit var nightPath: Path private var current = 0f private var linearGradient = LinearGradient(0f, 0f, 1f, 0f, 0, 0, Shader.TileMode.MIRROR) private var moonPaint = Paint(Paint.ANTI_ALIAS_FLAG) private var moonPaintB = Paint(Paint.ANTI_ALIAS_FLAG) private var moonPaintO = Paint(Paint.ANTI_ALIAS_FLAG) private var moonPaintD = Paint(Paint.ANTI_ALIAS_FLAG) private var moonRect = RectF() private var moonOval = RectF() private var dayLengthString = "" private var remainingString = "" private var sunriseString = "" private var middayString = "" private var sunsetString = "" private var isRTL = false private var segmentByPixel: Double = 0.toDouble() private var argbEvaluator = ArgbEvaluator() private var prayTimes: PrayTimes? = null // private Horizontal moonPosition; private var moonPhase = 1.0 private var fontSize: Int = 0 private val Number.dp: Int get() = (toFloat() * Resources.getSystem().displayMetrics.density).toInt() init { val tempTypedValue = TypedValue() @ColorInt fun resolveColor(attr: Int) = tempTypedValue.let { context.theme.resolveAttribute(attr, it, true) ContextCompat.getColor(context, it.resourceId) } colorTextNormal = resolveColor(R.attr.colorTextNormal) colorTextSecond = resolveColor(R.attr.colorTextSecond) horizonColor = resolveColor(R.attr.SunViewHorizonColor) timelineColor = resolveColor(R.attr.SunViewTimelineColor) taggingColor = resolveColor(R.attr.SunViewTaglineColor) sunriseTextColor = resolveColor(R.attr.SunViewSunriseTextColor) middayTextColor = resolveColor(R.attr.SunViewMiddayTextColor) sunsetTextColor = resolveColor(R.attr.SunViewSunsetTextColor) // resolveColor(R.attr.SunViewNightColor) nightColor = ContextCompat.getColor(context, R.color.sViewNightColor) // resolveColor(R.attr.SunViewDayColor) dayColor = ContextCompat.getColor(context, R.color.sViewDayColor) // resolveColor(R.attr.SunViewDaySecondColor) daySecondColor = ContextCompat.getColor(context, R.color.sViewDaySecondColor) // resolveColor(R.attr.SunViewSunColor) sunColor = ContextCompat.getColor(context, R.color.sViewSunColor) // resolveColor(R.attr.SunViewBeforeMiddayColor) sunBeforeMiddayColor = ContextCompat.getColor(context, R.color.sViewSunBeforeMiddayColor) // resolveColor(R.attr.SunViewAfterMiddayColor) sunAfterMiddayColor = ContextCompat.getColor(context, R.color.sViewSunAfterMiddayColor) // resolveColor(R.attr.SunViewEveningColor) sunEveningColor = ContextCompat.getColor(context, R.color.sViewSunEveningColor) sunPaint.color = sunColor sunRaisePaint.color = sunColor fontSize = 14.dp } override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) { super.onSizeChanged(w, h, oldW, oldH) width = w height = h - 18 curvePath = Path() curvePath.moveTo(0f, height.toFloat()) if (width != 0) { segmentByPixel = 2 * PI / width } (0..width).forEach { curvePath.lineTo(it.toFloat(), getY(it, segmentByPixel, (height * 0.9f).toInt())) } nightPath = Path(curvePath) nightPath.setLastPoint(width.toFloat(), height.toFloat()) nightPath.lineTo(width.toFloat(), 0f) nightPath.lineTo(0f, 0f) nightPath.close() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.save() // draw fill of night paint.style = Paint.Style.FILL paint.color = nightColor canvas.clipRect(0f, height * 0.75f, width * current, height.toFloat()) canvas.drawPath(nightPath, paint) canvas.restore() canvas.save() // draw fill of day canvas.clipRect(0, 0, width, height) canvas.clipRect(0f, 0f, width * current, height * 0.75f) dayPaint.shader = linearGradient canvas.drawPath(curvePath, dayPaint) canvas.restore() canvas.save() // draw time curve canvas.clipRect(0, 0, width, height) paint.strokeWidth = 3f paint.style = Paint.Style.STROKE paint.color = timelineColor canvas.drawPath(curvePath, paint) canvas.restore() // draw horizon line paint.color = horizonColor canvas.drawLine(0f, height * 0.75f, width.toFloat(), height * 0.75f, paint) // draw sunset and sunrise tag line indicator paint.color = taggingColor paint.strokeWidth = 2f canvas.drawLine(width * 0.17f, height * 0.3f, width * 0.17f, height * 0.7f, paint) canvas.drawLine(width * 0.83f, height * 0.3f, width * 0.83f, height * 0.7f, paint) canvas.drawLine(getWidth() / 2f, height * 0.7f, getWidth() / 2f, height * 0.8f, paint) // draw text paint.textAlign = Paint.Align.CENTER paint.textSize = fontSize.toFloat() paint.strokeWidth = 0f paint.style = Paint.Style.FILL paint.color = sunriseTextColor canvas.drawText(sunriseString, width * 0.17f, height * .2f, paint) paint.color = middayTextColor canvas.drawText(middayString, width / 2f, height * .94f, paint) paint.color = sunsetTextColor canvas.drawText(sunsetString, width * 0.83f, height * .2f, paint) // draw remaining time paint.textAlign = Paint.Align.CENTER paint.strokeWidth = 0f paint.style = Paint.Style.FILL paint.color = colorTextSecond canvas.drawText(dayLengthString, width * if (isRTL) 0.70f else 0.30f, height * .94f, paint) if (remainingString.isNotEmpty()) { canvas.drawText( remainingString, width * if (isRTL) 0.30f else 0.70f, height * .94f, paint ) } // draw sun if (current in 0.17f..0.83f) { @ColorInt val color = argbEvaluator.evaluate( current, sunBeforeMiddayColor, sunAfterMiddayColor ) as Int sunPaint.color = color //mSunRaisePaint.setColor(color); //mPaint.setShadowLayer(1.0f, 1.0f, 2.0f, 0x33000000); canvas.drawCircle( width * current, getY((width * current).toInt(), segmentByPixel, (height * 0.9f).toInt()), height * 0.09f, sunPaint ) //mPaint.clearShadowLayer(); //canvas.drawCircle(width * current, getY((int) (width * current), segmentByPixel, (int) (height * 0.9f)), (height * 0.09f) - 5, mSunRaisePaint); } else { drawMoon(canvas) } } private fun drawMoon(canvas: Canvas) { // This is brought from QiblaCompassView with some modifications val r = height * 0.08f val radius = 1f val px = width * current val py = getY((width * current).toInt(), segmentByPixel, (height * 0.9f).toInt()) moonPaint.reset() moonPaint.flags = Paint.ANTI_ALIAS_FLAG moonPaint.color = Color.WHITE moonPaint.style = Paint.Style.FILL_AND_STROKE moonPaintB.reset()// moon Paint Black moonPaintB.flags = Paint.ANTI_ALIAS_FLAG moonPaintB.color = Color.BLACK moonPaintB.style = Paint.Style.FILL_AND_STROKE moonPaintO.reset()// moon Paint for Oval moonPaintO.flags = Paint.ANTI_ALIAS_FLAG moonPaintO.color = Color.WHITE moonPaintO.style = Paint.Style.FILL_AND_STROKE moonPaintD.reset()// moon Paint for Diameter // draw moonPaintD.color = Color.GRAY moonPaintD.style = Paint.Style.STROKE moonPaintD.flags = Paint.ANTI_ALIAS_FLAG canvas.rotate(180f, px, py) val eOffset = 0 // elevation Offset 0 for 0 degree; r for 90 degree moonRect.set(px - r, py + eOffset - radius - r, px + r, py + eOffset - radius + r) canvas.drawArc(moonRect, 90f, 180f, false, moonPaint) canvas.drawArc(moonRect, 270f, 180f, false, moonPaintB) val arcWidth = ((moonPhase - 0.5) * (4 * r)).toInt() moonPaintO.color = if (arcWidth < 0) Color.BLACK else Color.WHITE moonOval.set( px - abs(arcWidth) / 2f, py + eOffset - radius - r, px + abs(arcWidth) / 2f, py + eOffset - radius + r ) canvas.drawArc(moonOval, 0f, 360f, false, moonPaintO) canvas.drawArc(moonRect, 0f, 360f, false, moonPaintD) canvas.drawLine(px, py - radius, px, py + radius, moonPaintD) moonPaintD.pathEffect = null } private fun getY(x: Int, segment: Double, height: Int): Float { val cos = (cos(-PI + x * segment) + 1) / 2 return height - height * cos.toFloat() + height * 0.1f } fun setSunriseSunsetMoonPhase(prayTimes: PrayTimes, moonPhase: Double) { this.prayTimes = prayTimes this.moonPhase = moonPhase postInvalidate() } fun startAnimate(immediate: Boolean = false) { val context = context if (prayTimes == null || context == null) return isRTL = isRTL(context) sunriseString = context.getString(R.string.sunriseSunView) middayString = context.getString(R.string.middaySunView) sunsetString = context.getString(R.string.sunsetSunView) val sunset = prayTimes?.sunsetClock?.toInt()?.toFloat() val sunrise = prayTimes?.sunriseClock?.toInt()?.toFloat() var midnight = prayTimes?.midnightClock?.toInt()?.toFloat() sunset ?: return sunrise ?: return midnight ?: return if (midnight > HALF_DAY) midnight -= FULL_DAY val now = Clock(Calendar.getInstance(Locale.getDefault())).toInt().toFloat() var c = 0f if (now <= sunrise) { if (sunrise != 0f) { c = (now - midnight) / sunrise * 0.17f } } else if (now <= sunset) { if (sunset - sunrise != 0f) { c = (now - sunrise) / (sunset - sunrise) * 0.66f + 0.17f } } else { if (FULL_DAY + midnight - sunset != 0f) { c = (now - sunset) / (FULL_DAY + midnight - sunset) * 0.17f + 0.17f + 0.66f } } val dayLength = Clock.fromInt((sunset - sunrise).toInt()) val remaining = Clock.fromInt(if (now > sunset || now < sunrise) 0 else (sunset - now).toInt()) dayLengthString = context.getString(R.string.length_of_day).format( formatNumber(dayLength.hour), formatNumber(dayLength.minute) ) remainingString = if (remaining.toInt() == 0) "" else context.getString( R.string.remaining_daylight ).format(formatNumber(remaining.hour), formatNumber(remaining.minute)) argbEvaluator = ArgbEvaluator() linearGradient = LinearGradient( getWidth() * 0.17f, 0f, getWidth() * 0.5f, 0f, dayColor, daySecondColor, Shader.TileMode.MIRROR ) if (immediate) { current = c postInvalidate() } else { val animator = ValueAnimator.ofFloat(0F, c) animator.duration = 1500L animator.interpolator = DecelerateInterpolator() animator.addUpdateListener(this) animator.start() } } fun clear() { current = 0f postInvalidate() } override fun onAnimationUpdate(valueAnimator: ValueAnimator) { current = valueAnimator.animatedValue as Float postInvalidate() } }
gpl-3.0
5ecc21640a5393334352326ad4321eb0
34.511111
157
0.630997
3.995
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/sessions/SessionFragment.kt
1
14032
package org.fossasia.openevent.general.sessions import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.provider.CalendarContract import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_session.view.progressBar import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailAbstract import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailAbstractContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailAbstractSeeMore import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailEndTime import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailInfoLocation import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailLanguage import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailLanguageContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailLocation import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailLocationContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailLocationImageMap import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailLocationInfoContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailName import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailSignUpButton import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailSpeakersContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailStartTime import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailTimeContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailTrack import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailTrackContainer import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailTrackIcon import kotlinx.android.synthetic.main.fragment_session.view.sessionDetailType import kotlinx.android.synthetic.main.fragment_session.view.speakersProgressBar import kotlinx.android.synthetic.main.fragment_session.view.speakersUnderSessionRecycler import org.fossasia.openevent.general.R import org.fossasia.openevent.general.common.SpeakerClickListener import org.fossasia.openevent.general.event.EventUtils import org.fossasia.openevent.general.speakers.SpeakerRecyclerAdapter import org.fossasia.openevent.general.utils.Utils import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.stripHtml import org.jetbrains.anko.design.snackbar import org.koin.androidx.viewmodel.ext.android.viewModel const val LINE_COUNT_ABSTRACT = 3 class SessionFragment : Fragment() { private lateinit var rootView: View private val sessionViewModel by viewModel<SessionViewModel>() private val speakersAdapter = SpeakerRecyclerAdapter() private val safeArgs: SessionFragmentArgs by navArgs() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_session, container, false) setToolbar(activity) setHasOptionsMenu(true) sessionViewModel.error .nonNull() .observe(viewLifecycleOwner, Observer { rootView.snackbar(it) if (it == getString(R.string.error_fetching_speakers_for_session)) { rootView.sessionDetailSpeakersContainer.isVisible = false } }) sessionViewModel.session .nonNull() .observe(viewLifecycleOwner, Observer { makeSessionView(it) }) sessionViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { rootView.progressBar.isVisible = it rootView.sessionDetailContainer.isVisible = !it }) sessionViewModel.speakersUnderSession .nonNull() .observe(viewLifecycleOwner, Observer { speakersAdapter.addAll(it) if (it.isEmpty()) rootView.sessionDetailSpeakersContainer.isVisible = false else rootView.speakersProgressBar.isVisible = false }) val currentSession = sessionViewModel.session.value if (currentSession == null) sessionViewModel.loadSession(safeArgs.sessionId) else makeSessionView(currentSession) val currentSpeakers = sessionViewModel.speakersUnderSession.value if (currentSpeakers == null) sessionViewModel.loadSpeakersUnderSession(safeArgs.sessionId) else { speakersAdapter.addAll(currentSpeakers) if (currentSpeakers.isEmpty()) rootView.sessionDetailSpeakersContainer.isVisible = false else rootView.speakersProgressBar.isVisible = false } val layoutManager = LinearLayoutManager(context) layoutManager.orientation = HORIZONTAL rootView.speakersUnderSessionRecycler.layoutManager = layoutManager rootView.speakersUnderSessionRecycler.adapter = speakersAdapter rootView.sessionDetailAbstract.movementMethod = LinkMovementMethod.getInstance() return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val speakerClickListener = object : SpeakerClickListener { override fun onClick(speakerId: Long) { findNavController(rootView).navigate(SessionFragmentDirections.actionSessionToSpeaker(speakerId)) } } speakersAdapter.apply { onSpeakerClick = speakerClickListener } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onDestroyView() { super.onDestroyView() speakersAdapter.onSpeakerClick = null } override fun onDestroy() { super.onDestroy() Utils.setNewHeaderColor(activity, resources.getColor(R.color.colorPrimaryDark), resources.getColor(R.color.colorPrimary)) } private fun makeSessionView(session: Session) { when (session.title.isNullOrBlank()) { true -> rootView.sessionDetailName.isVisible = false false -> { rootView.sessionDetailName.text = session.title setToolbar(activity, session.title) } } val type = session.sessionType if (type == null) { rootView.sessionDetailType.isVisible = false } else { rootView.sessionDetailType.text = getString(R.string.type_name, type.name) } val locationInfo = session.microlocation if (locationInfo == null) { rootView.sessionDetailLocationInfoContainer.isVisible = false rootView.sessionDetailLocationContainer.isVisible = false } else { rootView.sessionDetailInfoLocation.text = locationInfo.name rootView.sessionDetailLocation.text = locationInfo.name if (locationInfo.latitude.isNullOrBlank() || locationInfo.longitude.isNullOrBlank()) { rootView.sessionDetailLocationImageMap.isVisible = false } else { rootView.sessionDetailLocationContainer.setOnClickListener { startMap(locationInfo.latitude, locationInfo.longitude) } rootView.sessionDetailLocationImageMap.setOnClickListener { startMap(locationInfo.latitude, locationInfo.longitude) } Picasso.get() .load(sessionViewModel.loadMap(locationInfo.latitude, locationInfo.longitude)) .placeholder(R.drawable.ic_map_black) .error(R.drawable.ic_map_black) .into(rootView.sessionDetailLocationImageMap) } } when (session.language.isNullOrBlank()) { true -> rootView.sessionDetailLanguageContainer.isVisible = false false -> rootView.sessionDetailLanguage.text = session.language } when (session.startsAt.isNullOrBlank()) { true -> rootView.sessionDetailStartTime.isVisible = false false -> { val formattedStartTime = EventUtils.getEventDateTime(session.startsAt) val formattedTime = EventUtils.getFormattedTime(formattedStartTime) val formattedDate = EventUtils.getFormattedDate(formattedStartTime) val timezone = EventUtils.getFormattedTimeZone(formattedStartTime) rootView.sessionDetailStartTime.text = "$formattedTime $timezone/ $formattedDate" } } when (session.endsAt.isNullOrBlank()) { true -> rootView.sessionDetailEndTime.isVisible = false false -> { val formattedEndTime = EventUtils.getEventDateTime(session.endsAt) val formattedTime = EventUtils.getFormattedTime(formattedEndTime) val formattedDate = EventUtils.getFormattedDate(formattedEndTime) val timezone = EventUtils.getFormattedTimeZone(formattedEndTime) rootView.sessionDetailEndTime.text = "- $formattedTime $timezone/ $formattedDate" } } if (session.startsAt.isNullOrBlank() && session.endsAt.isNullOrBlank()) rootView.sessionDetailTimeContainer.isVisible = false else rootView.sessionDetailTimeContainer.setOnClickListener { saveSessionToCalendar(session) } val description = session.longAbstract ?: session.shortAbstract when (description.isNullOrBlank()) { true -> rootView.sessionDetailAbstractContainer.isVisible = false false -> { rootView.sessionDetailAbstract.text = description.stripHtml() val sessionAbstractClickListener = View.OnClickListener { rootView.sessionDetailAbstract.toggle() rootView.sessionDetailAbstractSeeMore.text = if (rootView.sessionDetailAbstract.isExpanded) getString(R.string.see_less) else getString(R.string.see_more) } rootView.sessionDetailAbstract.post { if (rootView.sessionDetailAbstract.lineCount > LINE_COUNT_ABSTRACT) { rootView.sessionDetailAbstractSeeMore.isVisible = true rootView.sessionDetailAbstract.setOnClickListener(sessionAbstractClickListener) rootView.sessionDetailAbstractSeeMore.setOnClickListener(sessionAbstractClickListener) } } } } val track = session.track when (track == null) { true -> rootView.sessionDetailTrackContainer.isVisible = false false -> { rootView.sessionDetailTrack.text = track.name val trackColor = Color.parseColor(track.color) rootView.sessionDetailTrackIcon.setColorFilter(trackColor) Utils.setNewHeaderColor(activity, trackColor) } } when (session.signupUrl.isNullOrBlank()) { true -> rootView.sessionDetailSignUpButton.isVisible = false false -> rootView.sessionDetailSignUpButton.setOnClickListener { context?.let { Utils.openUrl(it, session.signupUrl) } } } } private fun saveSessionToCalendar(session: Session) { val intent = Intent(Intent.ACTION_INSERT) intent.type = "vnd.android.cursor.item/event" intent.putExtra(CalendarContract.Events.TITLE, session.title) intent.putExtra(CalendarContract.Events.DESCRIPTION, session.shortAbstract) intent.putExtra(CalendarContract.Events.EVENT_LOCATION, session.microlocation?.name) if (session.startsAt != null && session.endsAt != null) { val formattedStartTime = EventUtils.getEventDateTime(session.startsAt) val timezone = EventUtils.getFormattedTimeZone(formattedStartTime) intent.putExtra(CalendarContract.Events.EVENT_TIMEZONE, timezone) intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, EventUtils.getTimeInMilliSeconds(session.startsAt, timezone)) intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, EventUtils.getTimeInMilliSeconds(session.endsAt, timezone)) } startActivity(intent) } private fun startMap(latitude: String, longitude: String) { val mapUrl = "geo:<$latitude>,<$longitude>?q=<$latitude>,<$longitude>" val mapIntent = Intent(Intent.ACTION_VIEW, Uri.parse(mapUrl)) val packageManager = activity?.packageManager if (packageManager != null && mapIntent.resolveActivity(packageManager) != null) { startActivity(mapIntent) } } }
apache-2.0
64f366cb05519d126dc49963cbead73e
45.61794
116
0.693344
5.253463
false
false
false
false
android/topeka
quiz/src/androidTest/java/com/google/samples/apps/topeka/SolveQuizUtil.kt
1
8477
/* * Copyright 2017 Google 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.google.samples.apps.topeka import android.app.Activity import android.content.pm.ActivityInfo import android.content.res.Configuration import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import androidx.test.espresso.Espresso.onData import androidx.test.espresso.Espresso.onView import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.action.ViewActions.typeText import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.hasSibling import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry import androidx.test.runner.lifecycle.Stage import android.text.TextUtils import android.view.View import android.widget.AdapterView import android.widget.GridView import android.widget.ListView import android.widget.SeekBar import com.google.samples.apps.topeka.quiz.R import com.google.samples.apps.topeka.model.quiz.AlphaPickerQuiz import com.google.samples.apps.topeka.model.quiz.FillBlankQuiz import com.google.samples.apps.topeka.model.quiz.FillTwoBlanksQuiz import com.google.samples.apps.topeka.model.quiz.OptionsQuiz import com.google.samples.apps.topeka.model.quiz.PickerQuiz import com.google.samples.apps.topeka.model.quiz.Quiz import com.google.samples.apps.topeka.model.quiz.QuizType import com.google.samples.apps.topeka.model.quiz.ToggleTranslateQuiz import com.google.samples.apps.topeka.model.quiz.TrueFalseQuiz import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.instanceOf import java.util.Arrays /** * Utility for quiz solving. */ object SolveQuizUtil { /** * Solves a given quiz. * @param quiz Quiz to solve. */ fun solveQuiz(quiz: Quiz<*>) { when (quiz.type) { QuizType.ALPHA_PICKER -> setAlphaPickerProgress(quiz as AlphaPickerQuiz) QuizType.PICKER -> setPickerProgress(quiz as PickerQuiz) QuizType.FILL_BLANK -> { val fillBlankQuiz = quiz as FillBlankQuiz var siblingText: String? = fillBlankQuiz.start if (TextUtils.isEmpty(siblingText)) { siblingText = fillBlankQuiz.end } var viewId = R.id.quiz_edit_text if (TextUtils.isEmpty(siblingText)) { siblingText = quiz.question viewId = R.id.quiz_content } typeAndCloseOnView(fillBlankQuiz.answer, siblingText, viewId) } QuizType.FILL_TWO_BLANKS -> { val (_, answer) = quiz as FillTwoBlanksQuiz typeAndCloseOnView(answer[0], R.id.quiz_edit_text) typeAndCloseOnView(answer[1], R.id.quiz_edit_text_two) } QuizType.FOUR_QUARTER -> testOptionsQuizWithType(quiz, GridView::class.java) QuizType.SINGLE_SELECT, QuizType.SINGLE_SELECT_ITEM, QuizType.MULTI_SELECT -> testOptionsQuizWithType(quiz, ListView::class.java) QuizType.TOGGLE_TRANSLATE -> { val toggleTranslateQuiz = quiz as ToggleTranslateQuiz toggleTranslateQuiz.answer.forEach { onData(equalTo(toggleTranslateQuiz.readableOptions[it])) .inAdapterView(allOf(instanceOf<Any>(AdapterView::class.java), withId(R.id.quiz_content), hasSiblingWith(quiz.question))) .perform(click()) } } QuizType.TRUE_FALSE -> { val (_, answer) = quiz as TrueFalseQuiz onView(allOf(isDescendantOfA(hasSibling(withText(quiz.question))), withText( if (answer) R.string.btn_true else R.string.btn_false))) .perform(click()) } } } private fun testOptionsQuizWithType(quiz: Quiz<*>, type: Class<out View>) { val stringOptionsQuiz = quiz as OptionsQuiz<*> stringOptionsQuiz.answer.forEach { onData(equalTo(stringOptionsQuiz.options[it])) .inAdapterView(allOf(instanceOf<Any>(type), withId(R.id.quiz_content), hasSiblingWith(quiz.question))) .perform(click()) } } private fun setAlphaPickerProgress(quiz: AlphaPickerQuiz) { onView(allOf(isDescendantOfA(hasSibling(withText(quiz.question))), withId(R.id.seekbar))) .perform(object : ViewAction { override fun getConstraints(): Matcher<View>? { return ViewMatchers.isAssignableFrom(SeekBar::class.java) } override fun getDescription() = "Set progress on AlphaPickerQuizView" override fun perform(uiController: UiController, view: View) { val alphabet = Arrays.asList(*InstrumentationRegistry.getTargetContext() .resources .getStringArray(R.array.alphabet)) (view as SeekBar).progress = alphabet.indexOf(quiz.answer) } }) } private fun setPickerProgress(pickerQuiz: PickerQuiz) { onView(allOf(isDescendantOfA(hasSibling(withText(pickerQuiz.question))), withId(R.id.seekbar))) .perform(click()) .perform(object : ViewAction { override fun getConstraints(): Matcher<View>? { return isAssignableFrom(SeekBar::class.java) } override fun getDescription() = "Set progress on PickerQuizView" override fun perform(uiController: UiController, view: View) { (view as SeekBar).progress = pickerQuiz.answer } }) } private fun typeAndCloseOnView(answer: String?, siblingText: String?, viewId: Int) { onView(allOf(withId(viewId), hasSiblingWith(siblingText))) .perform(typeText(answer), closeSoftKeyboard()) } private fun typeAndCloseOnView(answer: String?, viewId: Int) { onView(withId(viewId)).perform(typeText(answer), closeSoftKeyboard()) } private fun hasSiblingWith(text: String?): Matcher<View> { return hasSibling(withText(text)) } fun rotate() { val activity = getCurrentActivity()!! val currentOrientation = activity.resources.configuration.orientation if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) rotateToPortrait(activity) else rotateToLandscape(activity) } private fun rotateToLandscape(activity: Activity) { activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } private fun rotateToPortrait(activity: Activity) { activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } private fun getCurrentActivity(): Activity? { var resumedActivity: Activity? = null getInstrumentation().runOnMainSync { resumedActivity = ActivityLifecycleMonitorRegistry.getInstance() .getActivitiesInStage(Stage.RESUMED).first() } return resumedActivity } }
apache-2.0
6c45cb77c4c7f7b3ec748807f0ccf9d8
40.758621
97
0.65601
4.891518
false
true
false
false
hanks-zyh/KotlinExample
src/Utilss.kt
1
287
/** * Created by hanks on 16/3/15. */ object Utilss { fun isEmpty(string: String?): Boolean { return string != null && string.length == 0 } fun isWeakEmpty(string: String): Boolean { return isEmpty(string) && string.trim { it <= ' ' }.length == 0 } }
apache-2.0
518d71ed3aae4a87b57c781785afd523
21.076923
71
0.56446
3.5875
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/dialogs/RenderersDialog.kt
1
4956
/***************************************************************************** * RenderersDialog.java * * Copyright © 2017 VLC authors and VideoLAN * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.dialogs import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.libvlc.RendererItem import org.videolan.vlc.PlaybackService import org.videolan.vlc.R import org.videolan.vlc.RendererDelegate import org.videolan.vlc.databinding.DialogRenderersBinding import org.videolan.vlc.databinding.ItemRendererBinding import org.videolan.vlc.gui.DiffUtilAdapter import org.videolan.vlc.gui.helpers.SelectorViewHolder import org.videolan.vlc.gui.helpers.UiTools const private val TAG = "VLC/RenderersDialog" @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class RenderersDialog : DialogFragment() { private var renderers = RendererDelegate.renderers.value private lateinit var mBinding: DialogRenderersBinding private val mAdapter = RendererAdapter() private val mClickHandler = RendererClickhandler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) RendererDelegate.renderers.observe(this, Observer { if (it !== null) { renderers = it mAdapter.update(it) } }) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = LayoutInflater.from(requireContext()) mBinding = DialogRenderersBinding.inflate(inflater, null) val dialog = Dialog(requireContext()) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(mBinding.root) return dialog } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { setStyle(DialogFragment.STYLE_NO_FRAME, 0) mBinding = DialogRenderersBinding.inflate(inflater, container, false) return mBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { mBinding.holder = mClickHandler; mBinding.renderersList.layoutManager = LinearLayoutManager(view.context) mBinding.renderersList.adapter = mAdapter mBinding.renderersDisconnect.isEnabled = PlaybackService.hasRenderer() mBinding.renderersDisconnect.setTextColor(ContextCompat.getColor(view.context, if (PlaybackService.hasRenderer()) R.color.orange800 else R.color.grey400)) mAdapter.update(renderers) } private inner class RendererAdapter : DiffUtilAdapter<RendererItem, SelectorViewHolder<ItemRendererBinding>>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SelectorViewHolder<ItemRendererBinding> { val binding = ItemRendererBinding.inflate(LayoutInflater.from(parent.context), parent, false) binding.clicHandler = mClickHandler return SelectorViewHolder(binding) } override fun onBindViewHolder(holder: SelectorViewHolder<ItemRendererBinding>, position: Int) { holder.binding.renderer = renderers[position] if (renderers[position] == PlaybackService.renderer.value) holder.binding.rendererName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.orange800)) } override fun getItemCount() = dataset.size override fun onUpdateFinished() {} } inner class RendererClickhandler { fun connect(item: RendererItem?) { PlaybackService.renderer.value = item dismissAllowingStateLoss() item?.run { activity?.window?.findViewById<View>(R.id.audio_player_container)?.let { UiTools.snacker(it, getString(R.string.casting_connected_renderer, displayName)) } } } } }
gpl-2.0
eb12673454faf256da1c9b2adb755ed6
40.991525
162
0.721695
4.95005
false
false
false
false
apollo-rsps/apollo
game/plugin/skills/fishing/src/org/apollo/game/plugin/skills/fishing/FishingTool.kt
1
1166
package org.apollo.game.plugin.skills.fishing import org.apollo.game.model.Animation import org.apollo.game.plugin.api.Definitions /** * A tool used to gather [Fish] from a [FishingSpot]. */ enum class FishingTool( val message: String, val id: Int, animation: Int, val bait: Int = -1, val baitName: String? = null ) { LOBSTER_CAGE("You attempt to catch a lobster...", id = 301, animation = 619), SMALL_NET("You cast out your net...", id = 303, animation = 620), BIG_NET("You cast out your net...", id = 305, animation = 620), HARPOON("You start harpooning fish...", id = 311, animation = 618), FISHING_ROD("You attempt to catch a fish...", id = 307, animation = 622, bait = 313, baitName = "feathers"), FLY_FISHING_ROD("You attempt to catch a fish...", id = 309, animation = 622, bait = 314, baitName = "fishing bait"); /** * The [Animation] played when fishing with this tool. */ val animation: Animation = Animation(animation) /** * The name of this tool, formatted so it can be inserted into a message. */ val formattedName by lazy { Definitions.item(id).name.toLowerCase() } }
isc
4d732c8c8bea392e256e6186a5ed5c9f
35.46875
120
0.64837
3.491018
false
false
false
false
BjoernPetersen/JMusicBot
src/main/kotlin/net/bjoernpetersen/musicbot/api/auth/User.kt
1
4440
package net.bjoernpetersen.musicbot.api.auth import net.bjoernpetersen.musicbot.api.auth.BotUser.hasPassword import net.bjoernpetersen.musicbot.api.player.QueueEntry import org.mindrot.jbcrypt.BCrypt import java.util.Locale /** * Represents a user of the MusicBot. * * This is a sealed class with exactly three implementations: * * - [GuestUser] * - [FullUser] * - [BotUser] * * ## Identification * * Users are identified by their [name]. Names are required to be unique across all users. * * Before comparing names, they are converted to lower-case using the [US locale][Locale.US]. * This also means there can't be two users using the same name with different capitalization. * * ## Password * * Neither the password nor the password hash of a user is directly accessible. * To test if a given password is correct, the [hasPassword] method must be used. */ sealed class User { /** * The name of the user. May be composed of any unicode characters. */ abstract val name: String /** * A set of permissions this user has. */ abstract val permissions: Set<Permission> /** * A function to test whether this user has the specified password. * * @param password the plain-text password * @return whether the password is correct */ abstract fun hasPassword(password: String): Boolean } /** * Guest users are temporary users who are only held in memory during one bot session. * When the bot is closed, all guest users are lost. * * All new users are initially guest users, who can then be upgraded to [full users][FullUser] by * providing a real password. * * ## Authentication * * Guests don't need to provide a password in order to lower the barrier for bot usage. * In lieu of a password, clients send some unique [identifier][id] like an UUID or an installation * ID which is then used the same way passwords are for [full users][FullUser]. * * Optimally, the [id] should be reproducible by the client and **only** the one client it came from. * * ## Limitations * * Due to the questionable security of guest "passwords", all guest users have exactly the * permissions defined by [DefaultPermissions]. * * @param name a name which identifies the user * @param id some unique identifier (see `Authentication`) */ data class GuestUser( override val name: String, private val id: String ) : User() { override fun hasPassword(password: String): Boolean { check(!id.isBlank()) return id == password } override val permissions: Set<Permission> = DefaultPermissions.value override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is GuestUser) return false if (name.toId() != other.name.toId()) return false return true } override fun hashCode(): Int { return name.toId().hashCode() } } /** * A registered, permanent, full user. * * Note that [hash] may be empty if the user is constructed from a token. * * @param name a name which identifies the user * @param permissions the permissions of the user * @param hash the password hash of the user, or an empty string */ data class FullUser( override val name: String, override val permissions: Set<Permission>, private val hash: String ) : User() { override fun hasPassword(password: String): Boolean { check(!hash.isBlank()) return BCrypt.checkpw(password, hash) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is FullUser) return false if (name.toId() != other.name.toId()) return false return true } override fun hashCode(): Int { return name.toId().hashCode() } } /** * A special user which can be used for automated actions. * * For example, if a [QueueEntry] is created by a plugin and no user is available * to associate it with, this user may be used. * * This user is only intended for automatic actions, it doesn't have any permissions and * its [hasPassword] method doesn't match anything. */ object BotUser : User() { override val name: String = "MusicBot" override val permissions: Set<Permission> = emptySet() override fun hasPassword(password: String): Boolean = false } /** * Creates an ID from a user's name. */ fun String.toId(): String = trim().toLowerCase(Locale.US)
mit
7eda71774918ee6d96a34064bb86fc01
28.798658
101
0.683784
4.111111
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/tcp/aio/AbstractAioTcpConnection.kt
1
17071
package com.fireflysource.net.tcp.aio import com.fireflysource.common.coroutine.consumeAll import com.fireflysource.common.exception.UnknownTypeException import com.fireflysource.common.func.Callback import com.fireflysource.common.io.* import com.fireflysource.common.sys.Result import com.fireflysource.common.sys.Result.createFailedResult import com.fireflysource.common.sys.Result.discard import com.fireflysource.common.sys.SystemLogger import com.fireflysource.net.AbstractConnection import com.fireflysource.net.tcp.TcpConnection import com.fireflysource.net.tcp.TcpCoroutineDispatcher import com.fireflysource.net.tcp.buffer.* import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED import kotlinx.coroutines.channels.ChannelResult import kotlinx.coroutines.launch import java.io.IOException import java.net.InetSocketAddress import java.nio.ByteBuffer import java.nio.channels.AsynchronousSocketChannel import java.nio.channels.ClosedChannelException import java.nio.channels.InterruptedByTimeoutException import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer /** * @author Pengtao Qiu */ abstract class AbstractAioTcpConnection( id: Int, maxIdleTime: Long, private val socketChannel: AsynchronousSocketChannel, dispatcher: CoroutineDispatcher, inputBufferSize: Int, private val aioTcpCoroutineDispatcher: TcpCoroutineDispatcher = AioTcpCoroutineDispatcher(id, dispatcher) ) : AbstractConnection(id, System.currentTimeMillis(), maxIdleTime), TcpConnection, TcpCoroutineDispatcher by aioTcpCoroutineDispatcher { companion object { private val log = SystemLogger.create(AbstractAioTcpConnection::class.java) private val timeUnit = TimeUnit.SECONDS } private val isInputShutdown: AtomicBoolean = AtomicBoolean(false) private val isOutputShutdown: AtomicBoolean = AtomicBoolean(false) private val socketChannelClosed: AtomicBoolean = AtomicBoolean(false) private val closeRequest: AtomicBoolean = AtomicBoolean(false) private val closeCallbacks: MutableList<Callback> = mutableListOf() private val outputMessageHandler = OutputMessageHandler() private val inputMessageHandler = InputMessageHandler(inputBufferSize) private val closeResultChannel: Channel<Consumer<Result<Void>>> = Channel(UNLIMITED) private inner class OutputMessageHandler { private val outputMessageChannel: Channel<OutputMessage> = Channel(UNLIMITED) private var writeTimeout = maxIdleTime init { writeJob() } fun sendOutputMessage(output: OutputMessage) = outputMessageChannel.trySend(output) private fun writeJob() = coroutineScope.launch { while (true) { handleOutputMessage(outputMessageChannel.receive()) } }.invokeOnCompletion { cause -> val e = cause ?: ClosedChannelException() outputMessageChannel.consumeAll { message -> when (message) { is OutputBuffer -> message.result.accept(createFailedResult(-1, e)) is OutputBufferList -> message.result.accept(createFailedResult(-1, e)) is OutputBuffers -> message.result.accept(createFailedResult(-1, e)) is ShutdownOutput -> message.result.accept(createFailedResult(e)) else -> { } } } closeResultChannel.consumeAll { it.accept(Result.SUCCESS) } } private suspend fun handleOutputMessage(output: OutputMessage) { when (output) { is OutputDataMessage -> writeBuffers(output) is ShutdownOutput -> shutdownOutputAndClose(output) is SetWriteTimeout -> if (output.timeout > 0) { writeTimeout = output.timeout log.info("Set write timeout: $writeTimeout, id: $id") } else -> throw UnknownTypeException("Unknown output message. $output") } } private suspend fun write(output: OutputDataMessage): Long = when (output) { is OutputBuffer -> socketChannel.writeAwait(output.buffer, writeTimeout, timeUnit).toLong() is OutputBufferList -> socketChannel.writeAwait( output.buffers, output.getCurrentOffset(), output.getCurrentLength(), writeTimeout, timeUnit ) is OutputBuffers -> socketChannel.writeAwait( output.buffers, output.getCurrentOffset(), output.getCurrentLength(), writeTimeout, timeUnit ) } private suspend fun writeBuffers(output: OutputDataMessage): Boolean { lastWrittenTime = System.currentTimeMillis() var totalLength = 0L var success = true var exception: Exception? = null while (output.hasRemaining()) { try { val writtenLength = write(output) if (writtenLength < 0) { success = false exception = ClosedChannelException() break } else { writtenBytes += writtenLength totalLength += writtenLength } } catch (e: InterruptedByTimeoutException) { log.warn { "The TCP connection writing timeout. id: $id" } success = false exception = e break } catch (e: Exception) { log.warn { "The TCP connection writing exception. ${e.message} id: $id" } success = false exception = e break } } fun complete() { when (output) { is OutputBuffer -> output.result.accept(Result(true, totalLength.toInt(), null)) is OutputBufferList -> output.result.accept(Result(true, totalLength, null)) is OutputBuffers -> output.result.accept(Result(true, totalLength, null)) } } if (success) { log.debug { "TCP connection writes buffers total length: $totalLength" } complete() } else { shutdownOutputAndClose() failed(output, exception) } return success } private fun failed(outputBuffers: OutputDataMessage, exception: Exception?) { when (outputBuffers) { is OutputBuffer -> outputBuffers.result.accept(Result(false, -1, exception)) is OutputBufferList -> outputBuffers.result.accept(Result(false, -1, exception)) is OutputBuffers -> outputBuffers.result.accept(Result(false, -1, exception)) } } private fun shutdownOutputAndClose(output: ShutdownOutput) { shutdownOutputAndClose() output.result.accept(Result.SUCCESS) } private fun shutdown() { if (isOutputShutdown.compareAndSet(false, true)) { try { socketChannel.shutdownOutput() } catch (e: ClosedChannelException) { log.warn { "The channel closed. $id" } } catch (e: IOException) { log.warn { "Shutdown output exception. $id" } } } } private fun shutdownOutputAndClose() { if (isClosed) return [email protected]() log.debug { "TCP connection shutdown output. id $id, out: $isOutputShutdown, in: $isInputShutdown, socket: ${!socketChannel.isOpen}" } if (isShutdownInput) { closeNow() } } } private inner class InputMessageHandler(inputBufferSize: Int) { private val inputMessageChannel: Channel<InputMessage> = Channel(UNLIMITED) private val inputBuffer = BufferUtils.allocateDirect(inputBufferSize) private var readTimeout = maxIdleTime init { readJob() } fun sendInputMessage(input: InputMessage): ChannelResult<Unit> { if (input is ShutdownInput) { [email protected]() } return inputMessageChannel.trySend(input) } private fun readJob() = coroutineScope.launch { while (true) { handleInputMessage(inputMessageChannel.receive()) } }.invokeOnCompletion { cause -> val e = cause ?: ClosedChannelException() inputMessageChannel.consumeAll { message -> if (message is InputBuffer) { message.bufferFuture.completeExceptionally(e) } } closeResultChannel.consumeAll { it.accept(Result.SUCCESS) } } private suspend fun handleInputMessage(input: InputMessage) { when (input) { is InputBuffer -> readBuffers(input) is ShutdownInput -> shutdownInputAndClose() is SetReadTimeout -> if (input.timeout > 0) { readTimeout = input.timeout log.info("Set read timeout: $readTimeout, id: $id") } } } private suspend fun readBuffers(input: InputBuffer): Boolean { lastReadTime = System.currentTimeMillis() var success = true var exception: Exception? = null var length = 0 try { val pos = inputBuffer.flipToFill() length = socketChannel.readAwait(inputBuffer, readTimeout, timeUnit) inputBuffer.flipToFlush(pos) if (length < 0) { success = false exception = ClosedChannelException() } else { readBytes += length } } catch (e: InterruptedByTimeoutException) { log.warn { "The TCP connection reading timeout. id: $id" } success = false exception = e } catch (e: Exception) { log.warn { "The TCP connection reading exception. ${e.message} id: $id" } success = false exception = e } if (success) { log.debug { "TCP connection reads buffers total length: $length" } inputBuffer.copy().also { input.bufferFuture.complete(it) } } else { shutdownInputAndClose() failed(input, exception) } BufferUtils.clear(inputBuffer) return success } private fun failed(input: InputMessage, e: Exception?) { if (input is InputBuffer) { input.bufferFuture.completeExceptionally(e) } } private fun shutdown() { if (isInputShutdown.compareAndSet(false, true)) { try { socketChannel.shutdownInput() } catch (e: ClosedChannelException) { log.warn { "The channel closed. $id" } } catch (e: IOException) { log.warn { "Shutdown input exception. $id" } } } } private fun shutdownInputAndClose() { if (isClosed) { return } [email protected]() log.debug { "TCP connection shutdown input. id $id, out: $isOutputShutdown, in: $isInputShutdown, socket: ${!socketChannel.isOpen}" } if (isShutdownOutput) { closeNow() } else { [email protected]() } } } override fun read(): CompletableFuture<ByteBuffer> { val future = CompletableFuture<ByteBuffer>() if (inputMessageHandler.sendInputMessage(InputBuffer(future)).isFailure) { future.completeExceptionally(ClosedChannelException()) } return future } override fun setReadTimeout(timeout: Long) { inputMessageHandler.sendInputMessage(SetReadTimeout(timeout)) } override fun write(byteBuffer: ByteBuffer, result: Consumer<Result<Int>>): TcpConnection { if (outputMessageHandler.sendOutputMessage(OutputBuffer(byteBuffer, result)).isFailure) { result.accept(createFailedResult(-1, ClosedChannelException())) } return this } override fun write( byteBuffers: Array<ByteBuffer>, offset: Int, length: Int, result: Consumer<Result<Long>> ): TcpConnection { if (outputMessageHandler.sendOutputMessage(OutputBuffers(byteBuffers, offset, length, result)).isFailure) { result.accept(createFailedResult(-1L, ClosedChannelException())) } return this } override fun write( byteBufferList: List<ByteBuffer>, offset: Int, length: Int, result: Consumer<Result<Long>> ): TcpConnection { if (outputMessageHandler.sendOutputMessage( OutputBufferList( byteBufferList, offset, length, result ) ).isFailure ) { result.accept(createFailedResult(-1L, ClosedChannelException())) } return this } override fun setWriteTimeout(timeout: Long) { outputMessageHandler.sendOutputMessage(SetWriteTimeout(timeout)) } override fun flush(result: Consumer<Result<Void>>): TcpConnection { result.accept(Result.SUCCESS) return this } override fun getBufferSize(): Int = 0 override fun onClose(callback: Callback): TcpConnection { closeCallbacks.add(callback) return this } override fun close(result: Consumer<Result<Void>>): TcpConnection { if (closeRequest.compareAndSet(false, true)) { if (isClosed) { result.accept(Result.SUCCESS) } else { closeResultChannel.trySend(result) outputMessageHandler.sendOutputMessage(ShutdownOutput { if (inputMessageHandler.sendInputMessage(ShutdownInput).isFailure) { result.accept(createFailedResult(ClosedChannelException())) } }) } } else { result.accept(Result.SUCCESS) } return this } override fun close() { close(discard()) } override fun shutdownInput(): TcpConnection { inputMessageHandler.sendInputMessage(ShutdownInput) return this } override fun shutdownOutput(): TcpConnection { outputMessageHandler.sendOutputMessage(ShutdownOutput(discard())) return this } override fun isShutdownInput(): Boolean = isInputShutdown.get() override fun isShutdownOutput(): Boolean = isOutputShutdown.get() override fun closeNow(): TcpConnection { if (socketChannelClosed.compareAndSet(false, true)) { closeTime = System.currentTimeMillis() try { socketChannel.close() } catch (e: Exception) { log.warn { "Close socket channel exception. ${e.message} id: $id" } } closeCallbacks.forEach { try { it.call() } catch (e: Exception) { log.warn { "The TCP connection close callback exception. ${e.message} id: $id" } } } try { coroutineScope.cancel(CancellationException("Cancel TCP coroutine exception. id: $id")) } catch (e: Throwable) { log.warn { "Cancel TCP coroutine exception. ${e.message} id: $id" } } closeResultChannel.consumeAll { it.accept(Result.SUCCESS) } log.info { "The TCP connection close success. id: $id, out: $isOutputShutdown, in: $isInputShutdown, socket: ${!socketChannel.isOpen}" } } return this } override fun isClosed(): Boolean = socketChannelClosed.get() override fun isInvalid(): Boolean = closeRequest.get() || isShutdownInput || isShutdownOutput || socketChannelClosed.get() override fun getLocalAddress(): InetSocketAddress = socketChannel.localAddress as InetSocketAddress override fun getRemoteAddress(): InetSocketAddress = socketChannel.remoteAddress as InetSocketAddress }
apache-2.0
3f2f520da3fadd97441bec152a897ded
37.192394
148
0.593463
5.323043
false
false
false
false
alpha-cross/ararat
library/src/main/java/org/akop/ararat/core/CrosswordStateReader.kt
2
3726
// Copyright (c) Akop Karapetyan // // 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 org.akop.ararat.core import java.io.Closeable import java.io.IOException import java.io.InputStream import java.io.ObjectInputStream class CrosswordStateReader @Throws(IOException::class) constructor(stream: InputStream) : Closeable { private val inStream = ObjectInputStream(stream) @Throws(IOException::class) fun read(): CrosswordState { if (inStream.readInt() != CrosswordStateWriter.MAGIC_NUMBER) { throw IllegalArgumentException("Magic number mismatch") } val version = inStream.readByte().toInt() if (version > CrosswordStateWriter.VERSION_CURRENT) { throw IllegalArgumentException("State version $version not supported") } return readState(version) } @Throws(IOException::class, ClassNotFoundException::class) private fun readState(version: Int): CrosswordState { val width = inStream.readInt() val height = inStream.readInt() val state = CrosswordState(width, height) if (version <= 2) { val squareCounts = inStream.readLong() state.squaresSolved = (squareCounts and -0x1000000000000L).ushr(48).toShort() state.squaresCheated = (squareCounts and 0xffff00000000L).ushr(32).toShort() state.squaresWrong = (squareCounts and 0xffff0000L).ushr(16).toShort() state.squaresUnknown = 0 state.squareCount = (squareCounts and 0xffffL).toShort() } else { state.squaresSolved = inStream.readShort() state.squaresCheated = inStream.readShort() state.squaresWrong = inStream.readShort() state.squaresUnknown = inStream.readShort() state.squareCount = inStream.readShort() } state.playTimeMillis = inStream.readLong() state.lastPlayed = inStream.readLong() state.selection = inStream.readInt() if (version <= 1) { (inStream.readObject() as CharArray) .forEachIndexed { i, c -> state.charMatrix[i / width][i % width] = if (c != '\u0000') c.toString() else null } } else { @Suppress("UNCHECKED_CAST") (inStream.readObject() as Array<String?>) .forEachIndexed { i, c -> state.charMatrix[i / width][i % width] = c } } (inStream.readObject() as IntArray) .forEachIndexed { i, a -> state.attrMatrix[i / width][i % width] = a } return state } @Throws(IOException::class) override fun close() { inStream.close() } }
mit
3a18c8e06183a5b76ba2f9475eab8dcb
39.5
108
0.660762
4.669173
false
false
false
false
Kerr1Gan/ShareBox
share/src/main/java/com/ethan/and/ui/dialog/EditNameDialog.kt
1
2315
package com.ethan.and.ui.dialog import android.app.Activity import android.content.Context import android.os.Build import android.preference.PreferenceManager import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.RelativeLayout.CENTER_IN_PARENT import com.flybd.sharebox.PreferenceInfo import com.flybd.sharebox.R /** * Created by KerriGan on 2017/6/11. */ class EditNameDialog(context: Context, activity: Activity) : CloseBottomSheetDialog(context, activity) { override fun onCreateView(): View? { var container = RelativeLayout(context) fullScreenLayout(container) var parent = super.onCreateView() as ViewGroup var vg = layoutInflater.inflate(R.layout.dialog_edit_name, parent, false) var parm = LinearLayout.LayoutParams(-1, -2) var value = TypedValue() context.resources.getValue(R.dimen.edit_name_dialog_margin_bottom, value, true) parm.bottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value.float, context.resources.displayMetrics).toInt() parent.addView(vg, parm) var params = RelativeLayout.LayoutParams(-1, -2) params.addRule(CENTER_IN_PARENT) parent.layoutParams = params container.addView(parent, params) setTitle(context.getString(R.string.edit_name), container) init(container) return container } override fun onViewCreated(view: View?): Boolean { super.onViewCreated(view) return fullScreenBehavior() } private fun init(vg: ViewGroup) { val editName = vg.findViewById<View>(R.id.edit_name) as EditText var name = PreferenceManager.getDefaultSharedPreferences(context). getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL) editName.setText(name) vg.findViewById<View>(R.id.btn_edit).setOnClickListener { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putString(PreferenceInfo.PREF_DEVICE_NAME, editName.text.toString()) .commit() dismiss() } } }
apache-2.0
b9cc569ea542b5e87915de97058d6221
31.166667
104
0.687257
4.486434
false
false
false
false
genobis/tornadofx
src/main/java/tornadofx/Collections.kt
1
10463
@file:Suppress("unused") package tornadofx import javafx.beans.WeakListener import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.collections.ObservableSet import javafx.collections.SetChangeListener import tornadofx.FX.IgnoreParentBuilder.No import tornadofx.FX.IgnoreParentBuilder.Once import java.lang.ref.WeakReference import java.util.* /** * Moves the given **T** item to the specified index */ fun <T> MutableList<T>.move(item: T, newIndex: Int) { check(newIndex in 0 until size) val currentIndex = indexOf(item) if (currentIndex < 0) return removeAt(currentIndex) add(newIndex, item) } /** * Moves the given item at the `oldIndex` to the `newIndex` */ fun <T> MutableList<T>.moveAt(oldIndex: Int, newIndex: Int) { check(oldIndex in 0 until size) check(newIndex in 0 until size) val item = this[oldIndex] removeAt(oldIndex) add(newIndex, item) } /** * Moves all items meeting a predicate to the given index */ fun <T> MutableList<T>.moveAll(newIndex: Int, predicate: (T) -> Boolean) { check(newIndex in 0 until size) val split = partition(predicate) clear() addAll(split.second) addAll(if (newIndex >= size) size else newIndex, split.first) } /** * Moves the given element at specified index up the **MutableList** by one increment * unless it is at the top already which will result in no movement */ fun <T> MutableList<T>.moveUpAt(index: Int) { if (index == 0) return if (index !in 0 until size) throw Exception("Invalid index $index for MutableList of size $size") val newIndex = index + 1 val item = this[index] removeAt(index) add(newIndex, item) } /** * Moves the given element **T** up the **MutableList** by one increment * unless it is at the bottom already which will result in no movement */ fun <T> MutableList<T>.moveDownAt(index: Int) { if (index == size - 1) return if (index !in indices) throw Exception("Invalid index $index for MutableList of size $size") val newIndex = index - 1 val item = this[index] removeAt(index) add(newIndex, item) } /** * Moves the given element **T** up the **MutableList** by an index increment * unless it is at the top already which will result in no movement. * Returns a `Boolean` indicating if move was successful */ fun <T> MutableList<T>.moveUp(item: T): Boolean { val currentIndex = indexOf(item) if (currentIndex == -1) return false val newIndex = (currentIndex - 1) if (currentIndex <= 0) return false remove(item) add(newIndex, item) return true } /** * Moves the given element **T** up the **MutableList** by an index increment * unless it is at the bottom already which will result in no movement. * Returns a `Boolean` indicating if move was successful */ fun <T> MutableList<T>.moveDown(item: T): Boolean { val currentIndex = indexOf(item) if (currentIndex == -1) return false val newIndex = (currentIndex + 1) if (newIndex >= size) return false remove(item) add(newIndex, item) return true } /** * Moves first element **T** up an index that satisfies the given **predicate**, unless its already at the top */ inline fun <T> MutableList<T>.moveUp(crossinline predicate: (T) -> Boolean) = find(predicate)?.let { moveUp(it) } /** * Moves first element **T** down an index that satisfies the given **predicate**, unless its already at the bottom */ inline fun <T> MutableList<T>.moveDown(crossinline predicate: (T) -> Boolean) = find(predicate)?.let { moveDown(it) } /** * Moves all **T** elements up an index that satisfy the given **predicate**, unless they are already at the top */ inline fun <T> MutableList<T>.moveUpAll(crossinline predicate: (T) -> Boolean) = asSequence().withIndex() .filter { predicate.invoke(it.value) } .forEach { moveUpAt(it.index) } /** * Moves all **T** elements down an index that satisfy the given **predicate**, unless they are already at the bottom */ inline fun <T> MutableList<T>.moveDownAll(crossinline predicate: (T) -> Boolean) = asSequence().withIndex() .filter { predicate.invoke(it.value) } .forEach { moveDownAt(it.index) } fun <T> MutableList<T>.moveToTopWhere(predicate: (T) -> Boolean) { asSequence().filter(predicate).toList().asSequence().forEach { remove(it) add(0, it) } } fun <T> MutableList<T>.moveToBottomWhere(predicate: (T) -> Boolean) { val end = size - 1 asSequence().filter(predicate).toList().asSequence().forEach { remove(it) add(end, it) } } /** * Swaps the position of two items at two respective indices */ fun <T> MutableList<T>.swap(indexOne: Int, indexTwo: Int) { Collections.swap(this, indexOne, indexTwo) } /** * Swaps the index position of two items */ fun <T> MutableList<T>.swap(itemOne: T, itemTwo: T) = swap(indexOf(itemOne), indexOf(itemTwo)) /** * Bind this list to the given observable list by converting them into the correct type via the given converter. * Changes to the observable list are synced. */ fun <SourceType, TargetType> MutableList<TargetType>.bind(sourceList: ObservableList<SourceType>, converter: (SourceType) -> TargetType): ListConversionListener<SourceType, TargetType> { val ignoringParentConverter: (SourceType) -> TargetType = { FX.ignoreParentBuilder = Once try { converter(it) } finally { FX.ignoreParentBuilder = No } } val listener = ListConversionListener(this, ignoringParentConverter) (this as? ObservableList<TargetType>)?.setAll(sourceList.map(ignoringParentConverter)) ?: run { clear() addAll(sourceList.map(ignoringParentConverter)) } sourceList.removeListener(listener) sourceList.addListener(listener) return listener } /** * Bind this list to the given observable list by converting them into the correct type via the given converter. * Changes to the observable list are synced. */ fun <SourceType, TargetType> MutableList<TargetType>.bind(sourceSet: ObservableSet<SourceType>, converter: (SourceType) -> TargetType): SetConversionListener<SourceType, TargetType> { val ignoringParentConverter: (SourceType) -> TargetType = { FX.ignoreParentBuilder = Once try { converter(it) } finally { FX.ignoreParentBuilder = No } } val listener = SetConversionListener(this, ignoringParentConverter) if (this is ObservableList<*>) { sourceSet.forEach { source -> val converted = ignoringParentConverter(source) listener.sourceToTarget[source] = converted } (this as ObservableList<TargetType>).setAll(listener.sourceToTarget.values) } else { clear() addAll(sourceSet.map(ignoringParentConverter)) } sourceSet.removeListener(listener) sourceSet.addListener(listener) return listener } /** * Listens to changes on a list of SourceType and keeps the target list in sync by converting * each object into the TargetType via the supplied converter. */ class ListConversionListener<SourceType, TargetType>(targetList: MutableList<TargetType>, val converter: (SourceType) -> TargetType) : ListChangeListener<SourceType>, WeakListener { internal val targetRef: WeakReference<MutableList<TargetType>> = WeakReference(targetList) override fun onChanged(change: ListChangeListener.Change<out SourceType>) { val list = targetRef.get() if (list == null) { change.list.removeListener(this) } else { while (change.next()) { if (change.wasPermutated()) { list.subList(change.from, change.to).clear() list.addAll(change.from, change.list.subList(change.from, change.to).map(converter)) } else { if (change.wasRemoved()) { list.subList(change.from, change.from + change.removedSize).clear() } if (change.wasAdded()) { list.addAll(change.from, change.addedSubList.map(converter)) } } } } } override fun wasGarbageCollected() = targetRef.get() == null override fun hashCode() = targetRef.get()?.hashCode() ?: 0 override fun equals(other: Any?): Boolean { if (this === other) { return true } val ourList = targetRef.get() ?: return false if (other is ListConversionListener<*, *>) { val otherList = other.targetRef.get() return ourList === otherList } return false } } /** * Listens to changes on a set of SourceType and keeps the target list in sync by converting * each object into the TargetType via the supplied converter. */ class SetConversionListener<SourceType, TargetType>(targetList: MutableList<TargetType>, val converter: (SourceType) -> TargetType) : SetChangeListener<SourceType>, WeakListener { internal val targetRef: WeakReference<MutableList<TargetType>> = WeakReference(targetList) internal val sourceToTarget = HashMap<SourceType, TargetType>() override fun onChanged(change: SetChangeListener.Change<out SourceType>) { val list = targetRef.get() if (list == null) { change.set.removeListener(this) sourceToTarget.clear() } else { if (change.wasRemoved()) { list.remove(sourceToTarget[change.elementRemoved]) sourceToTarget.remove(change.elementRemoved) } if (change.wasAdded()) { val converted = converter(change.elementAdded) sourceToTarget[change.elementAdded] = converted list.add(converted) } } } override fun wasGarbageCollected() = targetRef.get() == null override fun hashCode() = targetRef.get()?.hashCode() ?: 0 override fun equals(other: Any?): Boolean { if (this === other) { return true } val ourList = targetRef.get() ?: return false if (other is SetConversionListener<*, *>) { val otherList = other.targetRef.get() return ourList === otherList } return false } } fun <T> ObservableList<T>.invalidate() { if (isNotEmpty()) this[0] = this[0] }
apache-2.0
fe1f58cefdb5851ac656262c146bab0c
33.421053
186
0.656791
4.270612
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsLint.kt
1
1290
package org.rust.ide.inspections import com.intellij.psi.PsiElement import org.rust.lang.core.psi.ext.RsDocAndAttributeOwner import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.queryAttributes import org.rust.lang.core.psi.ext.superMods import org.rust.lang.core.psi.ext.ancestors /** * Rust lints. */ enum class RsLint( val id: String, val defaultLevel: RsLintLevel = RsLintLevel.WARN ) { NonSnakeCase("non_snake_case"), NonCamelCaseTypes("non_camel_case_types"), NonUpperCaseGlobals("non_upper_case_globals"); /** * Returns the level of the lint for the given PSI element. */ fun levelFor(el: PsiElement) = explicitLevel(el) ?: superModsLevel(el) ?: defaultLevel private fun explicitLevel(el: PsiElement) = el.ancestors .filterIsInstance<RsDocAndAttributeOwner>() .flatMap { it.queryAttributes.metaItems } .filter { it.metaItemArgs?.metaItemList.orEmpty().any { it.text == id } } .mapNotNull { RsLintLevel.valueForId(it.identifier.text) } .firstOrNull() private fun superModsLevel(el: PsiElement) = el.ancestors .filterIsInstance<RsMod>() .lastOrNull() ?.superMods ?.mapNotNull { explicitLevel(it) }?.firstOrNull() }
mit
eb8523b4980e5105bf340b3fcd1bad6c
30.463415
81
0.685271
3.760933
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/util/Constants.kt
1
1334
package treehou.se.habit.util import java.util.HashSet import se.treehou.ng.ohcommunicator.connector.models.OHItem object Constants { // TODO remove when support for multiple servers. val PREFERENCE_SERVER = "server" val MY_OPENHAB_URL = "https://myopenhab.org:443" val MY_OPENHAB_URL_COMPARATOR = "myopenhab.org" val GCM_SENDER_ID = "737820980945" val FIREABASE_DEBUG_KEY_ACTIVITY = "Activity" val FIREABASE_DEBUG_KEY_FRAGMENT = "Fragment" // NotificationDB to speech. val PREF_REGISTRATION_SERVER = "notification_to_speech" val DEFAULT_NOTIFICATION_TO_SPEACH = false val PREF_INIT_SETUP = "init_setup" val MIN_TEXT_ADDON = 50 val MAX_TEXT_ADDON = 200 val DEFAULT_TEXT_ADDON = 100 val SUPPORT_SWITCH: MutableSet<String> = mutableSetOf() val SUPPORT_INC_DEC: MutableSet<String> = mutableSetOf() init { SUPPORT_SWITCH.add(OHItem.TYPE_GROUP) SUPPORT_SWITCH.add(OHItem.TYPE_SWITCH) SUPPORT_SWITCH.add(OHItem.TYPE_STRING) SUPPORT_SWITCH.add(OHItem.TYPE_NUMBER) SUPPORT_SWITCH.add(OHItem.TYPE_CONTACT) SUPPORT_SWITCH.add(OHItem.TYPE_COLOR) } init { SUPPORT_SWITCH.add(OHItem.TYPE_GROUP) SUPPORT_INC_DEC.add(OHItem.TYPE_NUMBER) SUPPORT_INC_DEC.add(OHItem.TYPE_DIMMER) } }
epl-1.0
6929167c423e0b88c7570077aef071d9
25.68
60
0.684408
3.586022
false
false
false
false
Shynixn/AstralEdit
astraledit-api/src/main/java/com/github/shynixn/astraledit/api/business/enumeration/ChatColor.kt
1
3730
@file:Suppress("unused") package com.github.shynixn.astraledit.api.business.enumeration /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ enum class ChatColor( /** * Unique code. */ val code: Char, /** * Unique int code. */ val internalCode: Int, /** * Is color being used for formatting. */ val isFormatting: Boolean = false, /** * Internal string description of the color. */ private val internalString: String = String(charArrayOf('§', code))) { /** * Black. */ BLACK('0', 0), /** * Dark_Blue. */ DARK_BLUE('1', 1), /** * Dark_Green. */ DARK_GREEN('2', 2), /** * Dark_Aqua. */ DARK_AQUA('3', 3), /** * Dark_Red. */ DARK_RED('4', 4), /** * Dark_Purple. */ DARK_PURPLE('5', 5), /** * Gold. */ GOLD('6', 6), /** * Gray. */ GRAY('7', 7), /** * Dark Gray. */ DARK_GRAY('8', 8), /** * Blue. */ BLUE('9', 9), /** * Green. */ GREEN('a', 10), /** * Aqua. */ AQUA('b', 11), /** * Red. */ RED('c', 12), /** * Light_Purple. */ LIGHT_PURPLE('d', 13), /** * Yellow. */ YELLOW('e', 14), /** * White. */ WHITE('f', 15), /** * Magic. */ MAGIC('k', 16, true), /** * Bold. */ BOLD('l', 17, true), /** * Strikethrough. */ STRIKETHROUGH('m', 18, true), /** * Underline. */ UNDERLINE('n', 19, true), /** * Italic. */ ITALIC('o', 20, true), /** * Reset. */ RESET('r', 21); /** * Returns the string code. */ override fun toString(): String { return this.internalString } companion object { /** * Translates the given [colorCodeChar] in the given [text] to the color code chars of minecraft. */ fun translateChatColorCodes(colorCodeChar: Char, text: String): String { val letters = text.toCharArray() for (i in 0 until letters.size - 1) { if (letters[i] == colorCodeChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(letters[i + 1]) > -1) { letters[i] = 167.toChar() letters[i + 1] = Character.toLowerCase(letters[i + 1]) } } return String(letters) } } }
apache-2.0
7ab9a94b47350b4778c943322aac2b59
22.024691
119
0.524537
3.917017
false
false
false
false
ohmae/mmupnp
mmupnp/src/main/java/net/mm2d/upnp/ControlPoints.kt
1
1300
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp import net.mm2d.upnp.empty.EmptyAction import net.mm2d.upnp.empty.EmptyControlPoint import net.mm2d.upnp.empty.EmptyDevice import net.mm2d.upnp.empty.EmptyService import net.mm2d.upnp.empty.EmptySsdpMessage /** * Provide EmptyObject. * * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object ControlPoints { /** * Returns the ControlPoint's Empty Object. * * @return ControlPoint's Empty Object */ fun emptyControlPoint(): ControlPoint = EmptyControlPoint /** * Returns the Device's Empty Object. * * @return Device's Empty Object */ fun emptyDevice(): Device = EmptyDevice /** * Returns the Service's Empty Object. * * @return Service's Empty Object */ fun emptyService(): Service = EmptyService /** * Returns the Action's Empty Object. * * @return Action's Empty Object */ fun emptyAction(): Action = EmptyAction /** * Returns the SsdpMessage's Empty Object. * * @return SsdpMessage's Empty Object */ fun emptySsdpMessage(): SsdpMessage = EmptySsdpMessage }
mit
316017cc6db68972db0ecfc30f5b8a90
21.928571
61
0.656542
3.93865
false
false
false
false
is00hcw/anko
dsl/static/src/supportV4/SupportDimensions.kt
2
1308
/* * 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. */ @file:Suppress("NOTHING_TO_INLINE") @file:JvmMultifileClass @file:JvmName("SupportDimensionsKt") package org.jetbrains.anko.support.v4 import android.support.v4.app.Fragment import org.jetbrains.anko.* public inline fun Fragment.dip(value: Int): Int = activity.dip(value) public inline fun Fragment.dip(value: Float): Int = activity.dip(value) public inline fun Fragment.sp(value: Int): Int = activity.sp(value) public inline fun Fragment.sp(value: Float): Int = activity.sp(value) public inline fun Fragment.px2dip(px: Int): Float = activity.px2dip(px) public inline fun Fragment.px2sp(px: Int): Float = activity.px2sp(px) public inline fun Fragment.dimen(resource: Int): Int = activity.dimen(resource)
apache-2.0
5d59e33133cade42f95bade716e84d29
34.378378
79
0.756116
3.633333
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/api/output/dto/Queries.kt
1
661
package com.github.ivan_osipov.clabo.api.output.dto object Queries { val EDIT_MESSAGE_TEXT = "editMessageText" val GET_UPDATES = "getUpdates" val DELETE_MESSAGE = "deleteMessage" val ANSWER_CALLBACK_QUERY = "answerCallbackQuery" val FORWARD_MESSAGE = "forwardMessage" val EDIT_MESSAGE_REPLY_MARKUP = "editMessageReplyMarkup" val EDIT_MESSAGE_CAPTION = "editMessageCaption" val GET_ME: String = "getMe" val SEND_MESSAGE: String = "sendMessage" val GET_CHAT: String = "getChat" val SEND_PHOTO: String = "sendPhoto" val SEND_AUDIO: String = "sendAudio" val SEND_DOCUMENT: String = "sendDocument" }
apache-2.0
b88739415e95d4d32c64b8bc0ddabe93
20.354839
60
0.694402
3.734463
false
false
false
false
cashapp/sqldelight
extensions/coroutines-extensions/src/commonTest/kotlin/app/cash/sqldelight/coroutines/TestDb.kt
1
4472
package app.cash.sqldelight.coroutines import app.cash.sqldelight.Query import app.cash.sqldelight.TransacterImpl import app.cash.sqldelight.coroutines.TestDb.Companion.TABLE_EMPLOYEE import app.cash.sqldelight.coroutines.TestDb.Companion.TABLE_MANAGER import app.cash.sqldelight.db.QueryResult import app.cash.sqldelight.db.SqlCursor import app.cash.sqldelight.db.SqlDriver import co.touchlab.stately.concurrency.AtomicLong import co.touchlab.stately.concurrency.value expect suspend fun testDriver(): SqlDriver class TestDb( val db: SqlDriver, ) : TransacterImpl(db) { var aliceId = AtomicLong(0) var bobId = AtomicLong(0) var eveId = AtomicLong(0) init { db.execute(null, "PRAGMA foreign_keys=ON", 0) db.execute(null, CREATE_EMPLOYEE, 0) aliceId.value = employee(Employee("alice", "Alice Allison")) bobId.value = employee(Employee("bob", "Bob Bobberson")) eveId.value = employee(Employee("eve", "Eve Evenson")) db.execute(null, CREATE_MANAGER, 0) manager(eveId.value, aliceId.value) } fun <T : Any> createQuery(key: String, query: String, mapper: (SqlCursor) -> T): Query<T> { return object : Query<T>(mapper) { override fun <R> execute(mapper: (SqlCursor) -> R): QueryResult<R> { return db.executeQuery(null, query, mapper, 0, null) } override fun addListener(listener: Listener) { db.addListener(listener, arrayOf(key)) } override fun removeListener(listener: Listener) { db.removeListener(listener, arrayOf(key)) } } } fun notify(key: String) { db.notifyListeners(arrayOf(key)) } fun close() { db.close() } fun employee(employee: Employee): Long { db.execute( 0, """ |INSERT OR FAIL INTO $TABLE_EMPLOYEE (${Employee.USERNAME}, ${Employee.NAME}) |VALUES (?, ?) | """.trimMargin(), 2, ) { bindString(0, employee.username) bindString(1, employee.name) } notify(TABLE_EMPLOYEE) // last_insert_rowid is connection-specific, so run it in the transaction thread/connection return transactionWithResult { val mapper: (SqlCursor) -> Long = { it.next() it.getLong(0)!! } db.executeQuery(2, "SELECT last_insert_rowid()", mapper, 0).value } } fun manager( employeeId: Long, managerId: Long, ): Long { db.execute( 1, """ |INSERT OR FAIL INTO $TABLE_MANAGER (${Manager.EMPLOYEE_ID}, ${Manager.MANAGER_ID}) |VALUES (?, ?) | """.trimMargin(), 2, ) { bindLong(0, employeeId) bindLong(1, managerId) } notify(TABLE_MANAGER) // last_insert_rowid is connection-specific, so run it in the transaction thread/connection return transactionWithResult { val mapper: (SqlCursor) -> Long = { it.next() it.getLong(0)!! } db.executeQuery(2, "SELECT last_insert_rowid()", mapper, 0).value } } companion object { const val TABLE_EMPLOYEE = "employee" const val TABLE_MANAGER = "manager" val CREATE_EMPLOYEE = """ |CREATE TABLE $TABLE_EMPLOYEE ( | ${Employee.ID} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | ${Employee.USERNAME} TEXT NOT NULL UNIQUE, | ${Employee.NAME} TEXT NOT NULL |) """.trimMargin() val CREATE_MANAGER = """ |CREATE TABLE $TABLE_MANAGER ( | ${Manager.ID} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | ${Manager.EMPLOYEE_ID} INTEGER NOT NULL UNIQUE REFERENCES $TABLE_EMPLOYEE(${Employee.ID}), | ${Manager.MANAGER_ID} INTEGER NOT NULL REFERENCES $TABLE_EMPLOYEE(${Employee.ID}) |) """.trimMargin() } } object Manager { const val ID = "id" const val EMPLOYEE_ID = "employee_id" const val MANAGER_ID = "manager_id" val SELECT_MANAGER_LIST = """ |SELECT e.${Employee.NAME}, m.${Employee.NAME} |FROM $TABLE_MANAGER AS manager |JOIN $TABLE_EMPLOYEE AS e |ON manager.$EMPLOYEE_ID = e.${Employee.ID} |JOIN $TABLE_EMPLOYEE AS m |ON manager.$MANAGER_ID = m.${Employee.ID} | """.trimMargin() } data class Employee(val username: String, val name: String) { companion object { const val ID = "id" const val USERNAME = "username" const val NAME = "name" const val SELECT_EMPLOYEES = "SELECT $USERNAME, $NAME FROM $TABLE_EMPLOYEE" val MAPPER = { cursor: SqlCursor -> Employee(cursor.getString(0)!!, cursor.getString(1)!!) } } }
apache-2.0
fe7f506ace66f2db57d3c02283f0c801
27.125786
99
0.639311
3.77384
false
false
false
false
martin-nordberg/KatyDOM
Katydid-Samples/src/main/kotlin/js/katydid/samples/sudokusolver/SudokuSolverAppState.kt
1
12598
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package js.katydid.samples.sudokusolver //--------------------------------------------------------------------------------------------------------------------- /** * A structured description of one change to the puzzle board. */ data class BoardChange( val description: String, val cellValueSet: String, val candidatesRemoved: List<String> ) //--------------------------------------------------------------------------------------------------------------------- /** * One of the 81 individual cells of the board. */ class Cell { /** * The state of a cell as far as whether it has been defined or solved. */ enum class State { /** Not yet set to a value. */ UNSET, /** Set to a value as part of defining the starting point of the puzzle. */ DEFINED, /** Set to a value by the user solving the puzzle. */ GUESSED, /** Set to a value by the computer solving the puzzle. */ SOLVED } lateinit var block: CellGroup val candidates = mutableSetOf(0, 1, 2, 3, 4, 5, 6, 7, 8) lateinit var column: CellGroup var diagonal0: CellGroup? = null var diagonal1: CellGroup? = null lateinit var row: CellGroup var state: State = State.UNSET var value: Int? = null //// /** * @return the name of the cell: R1C1 to R9C9. Adds the value if set, e.g. R2C5#7. */ val name: String get() { val v = value return if (v != null) "${row.name}${column.name}#${v + 1}" else "${row.name}${column.name}" } //// /** * Removes a [candidate] (0..8) from the possibilities for this cell. */ fun removeCandidate(candidate: Int): Boolean { if (candidates.remove(candidate)) { row.removeCellCandidate(this, candidate) column.removeCellCandidate(this, candidate) block.removeCellCandidate(this, candidate) diagonal0?.removeCellCandidate(this, candidate) diagonal1?.removeCellCandidate(this, candidate) return true } return false } /** * Sets the value of this cell to [newValue] and the state of the cell to [newState]. Adjusts all candidates * affected by the change. */ fun setValue(newValue: Int, newState: State): List<String> { for (c in candidates) { removeCandidate(c) } value = newValue state = newState val result = mutableListOf<String>() for (cell in row.cells) { if (cell.removeCandidate(newValue)) { result.add("${cell.name}#${newValue + 1}") } } for (cell in column.cells) { if (cell.removeCandidate(newValue)) { result.add("${cell.name}#${newValue + 1}") } } for (cell in block.cells) { if (cell.removeCandidate(newValue)) { result.add("${cell.name}#${newValue + 1}") } } for (cell in diagonal0?.cells ?: listOf()) { if (cell.removeCandidate(newValue)) { result.add("${cell.name}#${newValue + 1}") } } for (cell in diagonal1?.cells ?: listOf()) { if (cell.removeCandidate(newValue)) { result.add("${cell.name}#${newValue + 1}") } } return result } } //--------------------------------------------------------------------------------------------------------------------- /** * A row, column, block, or diagonal containing nine cells. */ class CellGroup( val type: Type, val index: Int, val cells: List<Cell> ) { enum class Type { ROW, COLUMN, BLOCK, DIAGNONAL; val abbreviation: String get() = when (this) { ROW -> "R" COLUMN -> "C" BLOCK -> "Block" DIAGNONAL -> "Diag" } } val cellsWithCandidate: List<MutableList<Cell>> init { cellsWithCandidate = listOf( ArrayList(cells), ArrayList(cells), ArrayList(cells), ArrayList(cells), ArrayList(cells), ArrayList(cells), ArrayList(cells), ArrayList(cells), ArrayList(cells) ) } val name get() = "${type.abbreviation}${index + 1}" fun removeCellCandidate(cell: Cell, candidate: Int) { cellsWithCandidate[candidate].remove(cell) } } //--------------------------------------------------------------------------------------------------------------------- class Board( val isXSudoku: Boolean ) { private val c: List<List<Cell>> = listOf( listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()), listOf(Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell(), Cell()) ) val rows = listOf( CellGroup(CellGroup.Type.ROW, 0, listOf(c[0][0], c[0][1], c[0][2], c[0][3], c[0][4], c[0][5], c[0][6], c[0][7], c[0][8])), CellGroup(CellGroup.Type.ROW, 1, listOf(c[1][0], c[1][1], c[1][2], c[1][3], c[1][4], c[1][5], c[1][6], c[1][7], c[1][8])), CellGroup(CellGroup.Type.ROW, 2, listOf(c[2][0], c[2][1], c[2][2], c[2][3], c[2][4], c[2][5], c[2][6], c[2][7], c[2][8])), CellGroup(CellGroup.Type.ROW, 3, listOf(c[3][0], c[3][1], c[3][2], c[3][3], c[3][4], c[3][5], c[3][6], c[3][7], c[3][8])), CellGroup(CellGroup.Type.ROW, 4, listOf(c[4][0], c[4][1], c[4][2], c[4][3], c[4][4], c[4][5], c[4][6], c[4][7], c[4][8])), CellGroup(CellGroup.Type.ROW, 5, listOf(c[5][0], c[5][1], c[5][2], c[5][3], c[5][4], c[5][5], c[5][6], c[5][7], c[5][8])), CellGroup(CellGroup.Type.ROW, 6, listOf(c[6][0], c[6][1], c[6][2], c[6][3], c[6][4], c[6][5], c[6][6], c[6][7], c[6][8])), CellGroup(CellGroup.Type.ROW, 7, listOf(c[7][0], c[7][1], c[7][2], c[7][3], c[7][4], c[7][5], c[7][6], c[7][7], c[7][8])), CellGroup(CellGroup.Type.ROW, 8, listOf(c[8][0], c[8][1], c[8][2], c[8][3], c[8][4], c[8][5], c[8][6], c[8][7], c[8][8])) ) val columns = listOf( CellGroup(CellGroup.Type.COLUMN, 0, listOf(c[0][0], c[1][0], c[2][0], c[3][0], c[4][0], c[5][0], c[6][0], c[7][0], c[8][0])), CellGroup(CellGroup.Type.COLUMN, 1, listOf(c[0][1], c[1][1], c[2][1], c[3][1], c[4][1], c[5][1], c[6][1], c[7][1], c[8][1])), CellGroup(CellGroup.Type.COLUMN, 2, listOf(c[0][2], c[1][2], c[2][2], c[3][2], c[4][2], c[5][2], c[6][2], c[7][2], c[8][2])), CellGroup(CellGroup.Type.COLUMN, 3, listOf(c[0][3], c[1][3], c[2][3], c[3][3], c[4][3], c[5][3], c[6][3], c[7][3], c[8][3])), CellGroup(CellGroup.Type.COLUMN, 4, listOf(c[0][4], c[1][4], c[2][4], c[3][4], c[4][4], c[5][4], c[6][4], c[7][4], c[8][4])), CellGroup(CellGroup.Type.COLUMN, 5, listOf(c[0][5], c[1][5], c[2][5], c[3][5], c[4][5], c[5][5], c[6][5], c[7][5], c[8][5])), CellGroup(CellGroup.Type.COLUMN, 6, listOf(c[0][6], c[1][6], c[2][6], c[3][6], c[4][6], c[5][6], c[6][6], c[7][6], c[8][6])), CellGroup(CellGroup.Type.COLUMN, 7, listOf(c[0][7], c[1][7], c[2][7], c[3][7], c[4][7], c[5][7], c[6][7], c[7][7], c[8][7])), CellGroup(CellGroup.Type.COLUMN, 8, listOf(c[0][8], c[1][8], c[2][8], c[3][8], c[4][8], c[5][8], c[6][8], c[7][8], c[8][8])) ) val blocks = listOf( CellGroup(CellGroup.Type.BLOCK, 0, listOf(c[0][0], c[0][1], c[0][2], c[1][0], c[1][1], c[1][2], c[2][0], c[2][1], c[2][2])), CellGroup(CellGroup.Type.BLOCK, 1, listOf(c[0][3], c[0][4], c[0][5], c[1][3], c[1][4], c[1][5], c[2][3], c[2][4], c[2][5])), CellGroup(CellGroup.Type.BLOCK, 2, listOf(c[0][6], c[0][7], c[0][8], c[1][6], c[1][7], c[1][8], c[2][6], c[2][7], c[2][8])), CellGroup(CellGroup.Type.BLOCK, 3, listOf(c[3][0], c[3][1], c[3][2], c[4][0], c[4][1], c[4][2], c[5][0], c[5][1], c[5][2])), CellGroup(CellGroup.Type.BLOCK, 4, listOf(c[3][3], c[3][4], c[3][5], c[4][3], c[4][4], c[4][5], c[5][3], c[5][4], c[5][5])), CellGroup(CellGroup.Type.BLOCK, 5, listOf(c[3][6], c[3][7], c[3][8], c[4][6], c[4][7], c[4][8], c[5][6], c[5][7], c[5][8])), CellGroup(CellGroup.Type.BLOCK, 6, listOf(c[6][0], c[6][1], c[6][2], c[7][0], c[7][1], c[7][2], c[8][0], c[8][1], c[8][2])), CellGroup(CellGroup.Type.BLOCK, 7, listOf(c[6][3], c[6][4], c[6][5], c[7][3], c[7][4], c[7][5], c[8][3], c[8][4], c[8][5])), CellGroup(CellGroup.Type.BLOCK, 8, listOf(c[6][6], c[6][7], c[6][8], c[7][6], c[7][7], c[7][8], c[8][6], c[8][7], c[8][8])) ) val diagonals = if (isXSudoku) listOf( CellGroup(CellGroup.Type.DIAGNONAL, 0, listOf(c[0][0], c[1][1], c[2][2], c[3][3], c[4][4], c[5][5], c[6][6], c[7][7], c[8][8])), CellGroup(CellGroup.Type.DIAGNONAL, 1, listOf(c[8][0], c[7][1], c[6][2], c[5][3], c[4][4], c[3][5], c[2][6], c[1][7], c[0][8])) ) else listOf() val units = if (isXSudoku) listOf( rows[0], rows[1], rows[2], rows[3], rows[4], rows[5], rows[6], rows[7], rows[8], columns[0], columns[1], columns[2], columns[3], columns[4], columns[5], columns[6], columns[7], columns[8], blocks[0], blocks[1], blocks[2], blocks[3], blocks[4], blocks[5], blocks[6], blocks[7], blocks[8], diagonals[0], diagonals[1] ) else listOf( rows[0], rows[1], rows[2], rows[3], rows[4], rows[5], rows[6], rows[7], rows[8], columns[0], columns[1], columns[2], columns[3], columns[4], columns[5], columns[6], columns[7], columns[8], blocks[0], blocks[1], blocks[2], blocks[3], blocks[4], blocks[5], blocks[6], blocks[7], blocks[8] ) init { for (row in rows) { for (cell in row.cells) { cell.row = row } } for (column in columns) { for (cell in column.cells) { cell.column = column } } for (block in blocks) { for (cell in block.cells) { cell.block = block } } if (diagonals.isNotEmpty()) { for (cell in diagonals[0].cells) { cell.diagonal0 = diagonals[0] } for (cell in diagonals[1].cells) { cell.diagonal1 = diagonals[1] } } } } //--------------------------------------------------------------------------------------------------------------------- /** Behavioral settings for how the board is defined and updated. */ data class SudokuSolverSettings( val isXSudoku: Boolean = false, val isSolvedAutomatically: Boolean = true, val isUserSolving: Boolean = false ) //--------------------------------------------------------------------------------------------------------------------- /** Top-level model for this application. */ data class SudokuSolverAppState( val board: Board = Board(false), val changes: List<BoardChange> = listOf(), val settings: SudokuSolverSettings = SudokuSolverSettings() ) //---------------------------------------------------------------------------------------------------------------------
apache-2.0
a49b87f1738065decd0a1f28bb5f5e37
32.152632
119
0.444277
3.251097
false
false
false
false
jitsi/jicofo
jicofo/src/main/kotlin/org/jitsi/jicofo/ConferenceConfig.kt
1
4720
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2020 - present 8x8, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo import com.typesafe.config.ConfigObject import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.jitsi.config.JitsiConfig.Companion.legacyConfig import org.jitsi.config.JitsiConfig.Companion.newConfig import org.jitsi.metaconfig.config import java.time.Duration import java.util.TreeMap @SuppressFBWarnings(value = ["BX_UNBOXING_IMMEDIATELY_REBOXED"], justification = "False positive.") class ConferenceConfig private constructor() { val conferenceStartTimeout: Duration by config { "org.jitsi.focus.IDLE_TIMEOUT".from(legacyConfig) "jicofo.conference.initial-timeout".from(newConfig) } val enableAutoOwner: Boolean by config { "org.jitsi.jicofo.DISABLE_AUTO_OWNER".from(legacyConfig).transformedBy { !it } "jicofo.conference.enable-auto-owner".from(newConfig) } fun enableAutoOwner(): Boolean = enableAutoOwner val maxSsrcsPerUser: Int by config { "org.jitsi.jicofo.MAX_SSRC_PER_USER".from(legacyConfig) "jicofo.conference.max-ssrcs-per-user".from(newConfig) } val maxSsrcGroupsPerUser: Int by config { "jicofo.conference.max-ssrc-groups-per-user".from(newConfig) } val singleParticipantTimeout: Duration by config { "org.jitsi.jicofo.SINGLE_PARTICIPANT_TIMEOUT".from(legacyConfig) "jicofo.conference.single-participant-timeout".from(newConfig) } val minParticipants: Int by config { "jicofo.conference.min-participants".from(newConfig) } val maxAudioSenders: Int by config { "jicofo.conference.max-audio-senders".from(newConfig) } val maxVideoSenders: Int by config { "jicofo.conference.max-video-senders".from(newConfig) } val useSsrcRewriting: Boolean by config { "jicofo.conference.use-ssrc-rewriting".from(newConfig) } val useJsonEncodedSources: Boolean by config { "jicofo.conference.use-json-encoded-sources".from(newConfig) } val useRandomSharedDocumentName: Boolean by config { "jicofo.conference.shared-document.use-random-name".from(newConfig) } fun useRandomSharedDocumentName(): Boolean = useRandomSharedDocumentName private val sourceSignalingDelays: TreeMap<Int, Int> by config { "jicofo.conference.source-signaling-delays".from(newConfig) .convertFrom<ConfigObject> { cfg -> TreeMap(cfg.entries.associate { it.key.toInt() to it.value.unwrapped() as Int }) } } /** * Get the number of milliseconds to delay signaling of Jingle sources given a certain [conferenceSize]. */ fun getSourceSignalingDelayMs(conferenceSize: Int) = sourceSignalingDelays.floorEntry(conferenceSize)?.value ?: 0 val reinviteMethod: ReinviteMethod by config { "jicofo.conference.reinvite-method".from(newConfig) } val multiStreamBackwardCompat: Boolean by config { "jicofo.conference.enable-multi-stream-backward-compat".from(newConfig) } /** * Whether to strip simulcast streams when signaling receivers. This option requires that jitsi-videobridge * uses the first SSRC in the SIM group as the target SSRC when rewriting streams, as this is the only SSRC * signaled to receivers. * * As an example, if a sender advertises simulcast with the following source groups: * SIM(1, 2, 3), FID(1, 4), FID(2, 5), FID(3, 6) * * If this option is enabled jicofo removes sources 2, 3, 5 and 6 when signaling to receivers of the stream. * This leaves just FID(1, 4), and assumes that jitsi-videobridge will use those two SSRCs for the rewritten stream. * * If the option is disabled, all sources are signaled to receivers. Lib-jitsi-meet has similar logic to strip * simulcast from remote streams. */ val stripSimulcast: Boolean by config { "jicofo.conference.strip-simulcast".from(newConfig) } fun stripSimulcast() = stripSimulcast companion object { @JvmField val config = ConferenceConfig() } }
apache-2.0
ac2086757708ad153f9d42d9fdc35568
37.064516
120
0.708475
4.1331
false
true
false
false
panpf/sketch
sample/src/main/java/com/github/panpf/sketch/sample/ui/setting/SettingsViewModel.kt
1
14087
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.ui.setting import android.app.Application import android.graphics.ColorSpace import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.widget.ImageView.ScaleType import android.widget.ImageView.ScaleType.MATRIX import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.CreationExtras import com.github.panpf.sketch.resize.Precision import com.github.panpf.sketch.resize.Scale import com.github.panpf.sketch.sample.model.ListSeparator import com.github.panpf.sketch.sample.model.MultiSelectMenu import com.github.panpf.sketch.sample.model.SwitchMenuFlow import com.github.panpf.sketch.sample.prefsService import com.github.panpf.sketch.sample.ui.base.LifecycleAndroidViewModel import com.github.panpf.sketch.sample.ui.setting.Page.COMPOSE_LIST import com.github.panpf.sketch.sample.ui.setting.Page.LIST import com.github.panpf.sketch.sample.ui.setting.Page.NONE import com.github.panpf.sketch.sample.ui.setting.Page.ZOOM import com.github.panpf.sketch.sketch import com.github.panpf.sketch.util.Logger.Level import com.github.panpf.tools4j.io.ktx.formatFileSize import kotlinx.coroutines.flow.merge import kotlinx.coroutines.launch class SettingsViewModel(application1: Application, val page: Page) : LifecycleAndroidViewModel(application1) { class Factory(val application: Application, val page: Page) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T { @Suppress("UNCHECKED_CAST") return SettingsViewModel(application, page) as T } } val menuListData = MutableLiveData<List<Any>>() private val prefsService = application1.prefsService init { val states = listOfNotNull( prefsService.showMimeTypeLogoInLIst.sharedFlow, prefsService.showProgressIndicatorInList.sharedFlow, prefsService.saveCellularTrafficInList.sharedFlow, prefsService.pauseLoadWhenScrollInList.sharedFlow, prefsService.resizePrecision.sharedFlow, prefsService.resizeScale.sharedFlow, prefsService.longImageResizeScale.sharedFlow, prefsService.otherImageResizeScale.sharedFlow, prefsService.inPreferQualityOverSpeed.sharedFlow, prefsService.bitmapQuality.sharedFlow, if (VERSION.SDK_INT >= VERSION_CODES.O) prefsService.colorSpace.sharedFlow else null, prefsService.ignoreExifOrientation.sharedFlow, prefsService.disabledMemoryCache.sharedFlow, prefsService.disabledResultCache.sharedFlow, prefsService.disabledDownloadCache.sharedFlow, prefsService.disallowReuseBitmap.sharedFlow, prefsService.showDataFromLogo.sharedFlow, prefsService.showTileBoundsInHugeImagePage.sharedFlow, prefsService.logLevel.sharedFlow, ) viewModelScope.launch { merge(*states.toTypedArray()).collect { updateList() } } updateList() } private fun updateList() { menuListData.postValue(buildList { when (page) { LIST -> { add(ListSeparator("List")) addAll(makeRecyclerListMenuList()) addAll(makeListMenuList()) add(ListSeparator("Decode")) addAll(makeDecodeMenuList()) } COMPOSE_LIST -> { add(ListSeparator("List")) addAll(makeListMenuList()) add(ListSeparator("Decode")) addAll(makeDecodeMenuList()) } ZOOM -> { add(ListSeparator("Zoom")) addAll(makeZoomMenuList()) add(ListSeparator("Decode")) addAll(makeDecodeMenuList()) } NONE -> { add(ListSeparator("List")) addAll(makeRecyclerListMenuList()) addAll(makeListMenuList()) add(ListSeparator("Decode")) addAll(makeDecodeMenuList()) add(ListSeparator("Zoom")) addAll(makeZoomMenuList()) } } add(ListSeparator("Cache")) addAll(makeCacheMenuList()) add(ListSeparator("Other")) addAll(makeOtherMenuList()) }) } private fun makeRecyclerListMenuList(): List<Any> = buildList { add( SwitchMenuFlow( title = "MimeType Logo", data = prefsService.showMimeTypeLogoInLIst, desc = "Displays the image type in the lower right corner of the ImageView" ) ) add( SwitchMenuFlow( title = "Progress Indicator", data = prefsService.showProgressIndicatorInList, desc = "A black translucent mask is displayed on the ImageView surface to indicate progress" ) ) add( SwitchMenuFlow( title = "Show Data From Logo", data = prefsService.showDataFromLogo, desc = "A different color triangle is displayed in the lower right corner of the ImageView according to DataFrom" ) ) } private fun makeListMenuList(): List<Any> = buildList { add( SwitchMenuFlow( title = "Save Cellular Traffic", data = prefsService.saveCellularTrafficInList, desc = "Mobile cell traffic does not download pictures" ) ) add( SwitchMenuFlow( title = "Pause Load When Scrolling", data = prefsService.pauseLoadWhenScrollInList, desc = "No image is loaded during list scrolling to improve the smoothness" ) ) add( MultiSelectMenu( title = "Resize Precision", desc = null, values = Precision.values().map { it.name }.plus(listOf("LongImageClipMode")), getValue = { prefsService.resizePrecision.value }, onSelect = { _, value -> prefsService.resizePrecision.value = value } ) ) add( MultiSelectMenu( title = "Resize Scale", desc = null, values = Scale.values().map { it.name }.plus(listOf("LongImageMode")), getValue = { prefsService.resizeScale.value }, onSelect = { _, value -> prefsService.resizeScale.value = value } ) ) if (prefsService.resizeScale.value == "LongImageMode") { add( MultiSelectMenu( title = "Long Image Resize Scale", desc = "Only Resize Scale is LongImageMode", values = Scale.values().map { it.name }, getValue = { prefsService.longImageResizeScale.value }, onSelect = { _, value -> prefsService.longImageResizeScale.value = value } ) ) add( MultiSelectMenu( title = "Other Image Resize Scale", desc = "Only Resize Scale is LongImageMode", values = Scale.values().map { it.name }, getValue = { prefsService.otherImageResizeScale.value }, onSelect = { _, value -> prefsService.otherImageResizeScale.value = value } ) ) } } private fun makeZoomMenuList(): List<Any> = buildList { add( MultiSelectMenu( title = "Scale Type", desc = null, values = ScaleType.values().filter { it != MATRIX }.map { it.name }, getValue = { prefsService.scaleType.value }, onSelect = { _, value -> prefsService.scaleType.value = value } ) ) add( SwitchMenuFlow( title = "Scroll Bar", desc = null, data = prefsService.scrollBarEnabled, ) ) add( SwitchMenuFlow( title = "Read Mode", data = prefsService.readModeEnabled, desc = "Long images are displayed in full screen by default" ) ) add( SwitchMenuFlow( title = "Show Tile Bounds", desc = "Overlay the state and area of the tile on the View", data = prefsService.showTileBoundsInHugeImagePage, ) ) } private fun makeDecodeMenuList(): List<Any> = buildList { add( MultiSelectMenu( title = "Bitmap Quality", desc = null, values = listOf("Default", "LOW", "HIGH"), getValue = { prefsService.bitmapQuality.value }, onSelect = { _, value -> prefsService.bitmapQuality.value = value } ) ) if (VERSION.SDK_INT >= VERSION_CODES.O) { val items = listOf("Default").plus(ColorSpace.Named.values().map { it.name }) add( MultiSelectMenu( title = "Color Space", desc = null, values = items, getValue = { prefsService.colorSpace.value }, onSelect = { _, value -> prefsService.colorSpace.value = value } ) ) } if (VERSION.SDK_INT <= VERSION_CODES.M) { add( SwitchMenuFlow( title = "inPreferQualityOverSpeed", desc = null, data = prefsService.inPreferQualityOverSpeed ) ) } add( SwitchMenuFlow( title = "Exif Orientation", desc = null, data = prefsService.ignoreExifOrientation, reverse = true ) ) } private fun makeCacheMenuList(): List<Any> = buildList { val sketch = application1.sketch add( SwitchMenuFlow( title = "Memory Cache", desc = "%s/%s(Long Click Clean)".format( sketch.memoryCache.size.formatFileSize(0, false, true), sketch.memoryCache.maxSize.formatFileSize(0, false, true) ), data = prefsService.disabledMemoryCache, reverse = true, onLongClick = { sketch.memoryCache.clear() updateList() } ) ) add( SwitchMenuFlow( title = "Result Cache", desc = "%s/%s(Long Click Clean)".format( sketch.resultCache.size.formatFileSize(0, false, true), sketch.resultCache.maxSize.formatFileSize(0, false, true) ), data = prefsService.disabledResultCache, reverse = true, onLongClick = { sketch.resultCache.clear() updateList() } ) ) add( SwitchMenuFlow( title = "Download Cache", desc = "%s/%s(Long Click Clean)".format( sketch.downloadCache.size.formatFileSize(0, false, true), sketch.downloadCache.maxSize.formatFileSize(0, false, true) ), data = prefsService.disabledDownloadCache, reverse = true, onLongClick = { sketch.downloadCache.clear() updateList() } ) ) add( SwitchMenuFlow( title = "Bitmap Pool", desc = "%s/%s(Long Click Clean)".format( sketch.bitmapPool.size.formatFileSize(0, false, true), sketch.bitmapPool.maxSize.formatFileSize(0, false, true) ), data = prefsService.disallowReuseBitmap, reverse = true, onLongClick = { sketch.bitmapPool.clear() updateList() } ) ) } private fun makeOtherMenuList(): List<Any> = buildList { add( MultiSelectMenu( title = "Logger Level", desc = if (application1.sketch.logger.level <= Level.DEBUG) "DEBUG and below will reduce UI fluency" else "", values = Level.values().map { it.name }, getValue = { application1.sketch.logger.level.toString() }, onSelect = { _, value -> application1.sketch.logger.level = Level.valueOf(value) prefsService.logLevel.value = value } ) ) } }
apache-2.0
a33d10a044895a80b500915b81137f68
37.23913
129
0.543458
5.14103
false
false
false
false
teamblueridge/PasteIt
app/src/main/kotlin/org/teamblueridge/pasteitapp/MainActivity.kt
1
12608
package org.teamblueridge.pasteitapp import android.Manifest import android.app.Activity import android.app.ProgressDialog import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.text.Html import android.text.method.LinkMovementMethod import android.util.Log import android.util.Patterns import android.view.Menu import android.view.MenuItem import android.view.WindowManager import android.view.inputmethod.InputMethodManager import android.widget.ArrayAdapter import android.widget.ProgressBar import com.pawegio.kandroid.runAsync import com.pawegio.kandroid.runOnUiThread import com.pawegio.kandroid.toast import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.fragment_paste.* import kotlinx.android.synthetic.main.spinner_item.* import org.teamblueridge.utils.NetworkUtil import java.io.* import java.net.ConnectException import java.net.URL import javax.net.ssl.HttpsURLConnection class MainActivity : AppCompatActivity() { private var mReceivedIntent: Intent? = null private var mReceivedAction: String? = null private val TAG = "TeamBlueRidge" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) // Set-up the paste fragment and give it a name so we can track it if (savedInstanceState == null) { fragmentManager.beginTransaction() .add(R.id.container, CreatePasteFragment(), "PasteFragment") .commit() } // Set-up up navigation fragmentManager.addOnBackStackChangedListener { /* Check if we have anything on the stack. If we do, we need to have the back button * display in in the ActionBar */ if (fragmentManager.backStackEntryCount > 0) { supportActionBar!!.setHomeButtonEnabled(true) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } else { supportActionBar!!.setHomeButtonEnabled(false) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = this.window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.statusBarColor = ContextCompat.getColor(this, R.color.blue_700) } } public override fun onStart() { super.onStart() mReceivedIntent = intent mReceivedAction = mReceivedIntent!!.action if (mReceivedAction == Intent.ACTION_VIEW || mReceivedAction == Intent.ACTION_EDIT) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat .requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 0) } if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { loadFile() } else { toast(getString(R.string.request_permissions)) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 0) loadFile() } mReceivedAction = Intent.ACTION_DEFAULT } else { paste_content_edittext.setText(mReceivedIntent!!.getStringExtra(Intent.EXTRA_TEXT)) } // Check if the "languages" file exists if (File("languages").exists()) { populateSpinner() } else { val prefs = PreferenceManager.getDefaultSharedPreferences(this@MainActivity) ApiHandler().getLanguages(this as Activity, UploadDownloadUrlPrep().prepUrl(prefs, UploadDownloadUrlPrep.DOWNLOAD_LANGS)); populateSpinner() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_paste -> { val view = this.currentFocus if (view != null) { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } prepForPaste() true } R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) true } R.id.action_list -> true android.R.id.home -> { fragmentManager.popBackStack() true } else -> super.onOptionsItemSelected(item) } /** * Does some preparation before finally calling the UploadPaste ASyncTask */ fun prepForPaste() { val languages = ApiHandler().getLanguages(applicationContext) val chosenLang = languages.getKeyByValue(language_spinner.selectedItem) ?: return if (!paste_content_edittext.text.toString().isEmpty()) { if (NetworkUtil.isConnectedToNetwork(this)) { if (chosenLang != "0") { val success = doPaste(if (!chosenLang.isEmpty()) chosenLang else "text") if (success) toast(getString(R.string.paste_toast)) paste_name_edittext.setText("") paste_content_edittext.setText("") } else { toast(getString(R.string.invalid_language)) } } else { toast(getString(R.string.no_network)) } } else { toast(getString(R.string.paste_no_text)) } } fun <K, V> Map<K, V>.getKeyByValue(value: V): K? { for ((k, v) in this) if (v == value) return k return null } /** * Uploads the paste to the server then receives the URL of the paste and displays it in the * Paste URL Label. * * @param receivedLanguage Language to upload the paste in */ fun doPaste(receivedLanguage: String): Boolean { val httpUserAgent = ("Paste It v${getString(R.string.version_name)}" + ", an Android app for pasting to Stikked (https://goo.gl/LmVtEC)") val prefs = PreferenceManager.getDefaultSharedPreferences(this@MainActivity) val pDialogUpload = ProgressDialog(this@MainActivity) val language = if (!receivedLanguage.isEmpty()) receivedLanguage else "text" val title = paste_name_edittext.text.toString() val text = paste_content_edittext.text.toString() val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager //Ensure username is set, if not, default to "mobile user" val mUserName = if (!prefs.getString("pref_name", "").isEmpty()) prefs.getString("pref_name", "") else "Mobile User " + getString(R.string.version_name) pDialogUpload.setMessage(getString(R.string.paste_upload)) pDialogUpload.isIndeterminate = false pDialogUpload.setCancelable(true) runOnUiThread { pDialogUpload.show() } var success: Boolean = false runAsync { // HTTP Header data if (!NetworkUtil.isHostAvailable(this, prefs.getString("pref_domain", ""))) { pDialogUpload.cancel() runOnUiThread { toast("Unable to reach paste server. Check settings and try again.") } return@runAsync } val url = URL(UploadDownloadUrlPrep().prepUrl(prefs, UploadDownloadUrlPrep.UPLOAD_PASTE)) val urlConnection = url.openConnection() as HttpsURLConnection urlConnection.requestMethod = "POST" urlConnection.doInput = true urlConnection.doOutput = true urlConnection.setRequestProperty("User-Agent", httpUserAgent) val builder = Uri.Builder() .appendQueryParameter("title", title) .appendQueryParameter("text", text) .appendQueryParameter("name", mUserName) .appendQueryParameter("lang", language) val query = builder.build().encodedQuery urlConnection.outputStream.use { val writer = BufferedWriter(OutputStreamWriter(it, "UTF-8")) writer.write(query) writer.flush() writer.close() it.close() } //Get the URL of the paste val urlStringBuilder = StringBuilder() BufferedReader(InputStreamReader(urlConnection.inputStream)) .forEachLine { urlStringBuilder.append(it) } val pasteUrl = urlStringBuilder.toString() pDialogUpload.dismiss() if (Patterns.WEB_URL.matcher(pasteUrl).matches()) clipboard.primaryClip = ClipData.newPlainText("PasteIt", pasteUrl) val labelText: CharSequence val toastText: String if (Patterns.WEB_URL.matcher(pasteUrl).matches()) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { labelText = Html.fromHtml("<a href=\"$pasteUrl\">$pasteUrl</a>", Html.FROM_HTML_MODE_LEGACY) } else { labelText = Html.fromHtml("<a href=\"$pasteUrl\">$pasteUrl</a>") } toastText = "" success = true } else if (pasteUrl == "Invalid API key") { toastText = getString(R.string.invalid_api_key) labelText = "" success = false } else { Log.e(TAG, "Bad URL: URL received was $pasteUrl") labelText = getString(R.string.invalid_url) toastText = "" success = false } runOnUiThread { paste_url_label.text = labelText if (success) { paste_url_label.movementMethod = LinkMovementMethod.getInstance() } else { toast(toastText) } } } return success } /** * Loads the file being opened and puts it into the paste content EditText. */ fun loadFile() { val pDialogFileLoad = ProgressDialog(this@MainActivity) pDialogFileLoad.setMessage(getString(R.string.file_load)) pDialogFileLoad.isIndeterminate = true pDialogFileLoad.setCancelable(false) pDialogFileLoad.show() runAsync { mReceivedAction = intent.action val receivedText = mReceivedIntent!!.data val inputStream = contentResolver.openInputStream(receivedText) val reader = BufferedReader(InputStreamReader(inputStream)) val stringBuilder = StringBuilder() reader.forEachLine { stringBuilder.append(it + "\n") } inputStream.close() runOnUiThread { paste_content_edittext.setText(stringBuilder.toString()) } } pDialogFileLoad.dismiss() } /** * Populates the spinner for language selection using the arrays of languages generated by * the API handler. */ fun populateSpinner() { val languages = ApiHandler().getLanguages(applicationContext) val prefs = PreferenceManager.getDefaultSharedPreferences(this@MainActivity) val positionListPref = prefs.getString("pref_default_language", "text") val adapter = ArrayAdapter(applicationContext, R.layout.spinner_item, languages.values.toList()) adapter.setDropDownViewResource(R.layout.spinner_dropdown_item) language_spinner.adapter = adapter language_spinner.setSelection(languages.keys.toList().indexOf(positionListPref)) } }
gpl-3.0
d335e1e30f2f978edafc2c70b93bf44c
39.938312
112
0.620955
5.017111
false
false
false
false
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/plugin/listeners/BanConnectionListener.kt
1
3844
package com.projectcitybuild.plugin.listeners import com.projectcitybuild.core.SpigotListener import com.projectcitybuild.features.bans.usecases.AuthoriseConnectionUseCase import com.projectcitybuild.modules.datetime.formatter.DateTimeFormatter import com.projectcitybuild.modules.errorreporting.ErrorReporter import com.projectcitybuild.modules.logger.PlatformLogger import com.projectcitybuild.platforms.bungeecord.extensions.add import kotlinx.coroutines.runBlocking import net.md_5.bungee.api.ChatColor import net.md_5.bungee.api.chat.TextComponent import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.player.AsyncPlayerPreLoginEvent import java.time.format.FormatStyle import javax.inject.Inject class BanConnectionListener @Inject constructor( private val authoriseConnectionUseCase: AuthoriseConnectionUseCase, private val logger: PlatformLogger, private val dateTimeFormatter: DateTimeFormatter, private val errorReporter: ErrorReporter, ) : SpigotListener { @EventHandler(priority = EventPriority.HIGHEST) fun onAsyncPreLogin(event: AsyncPlayerPreLoginEvent) { // Events cannot be mutated (i.e. we cannot kick the connecting player) inside a // suspended function due to the way the code compiles, so we need to block. // Blocking isn't actually a problem here, because the event is already asynchronous // // See https://github.com/Shynixn/MCCoroutine/issues/43 runBlocking { runCatching { val ban = authoriseConnectionUseCase.getBan( uuid = event.uniqueId, ip = event.address.toString(), ) ?: return@runCatching val message = when (ban) { is AuthoriseConnectionUseCase.Ban.UUID -> TextComponent() .add("You are currently banned.\n\n") { it.color = ChatColor.RED it.isBold = true } .add("Reason: ") { it.color = ChatColor.GRAY } .add(ban.value.reason ?: "No reason provided") { it.color = ChatColor.WHITE } .add("\n") .add("Expires: ") { it.color = ChatColor.GRAY } .add((ban.value.expiresAt?.let { dateTimeFormatter.convert(it, FormatStyle.SHORT) } ?: "Never") + "\n\n") { it.color = ChatColor.WHITE } .add("Appeal @ https://projectcitybuild.com") { it.color = ChatColor.AQUA } is AuthoriseConnectionUseCase.Ban.IP -> TextComponent() .add("You are currently IP banned.\n\n") { it.color = ChatColor.RED it.isBold = true } .add("Reason: ") { it.color = ChatColor.GRAY } .add(ban.value.reason.ifEmpty { "No reason provided" }) { it.color = ChatColor.WHITE } .add("\n") .add("\n\n") .add("Appeal @ https://projectcitybuild.com") { it.color = ChatColor.AQUA } } event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, message.toLegacyText()) }.onFailure { throwable -> throwable.message?.let { logger.fatal(it) } throwable.printStackTrace() errorReporter.report(throwable) // If something goes wrong, better not to let players in event.disallow( AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "An error occurred while contacting the PCB authentication server. Please try again later" ) } } } }
mit
4f8689c7cc904e0b8bfa6e4edb85d359
47.05
160
0.600416
5.077939
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/ResizeNearest.kt
1
8754
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDIndex import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.enums.ImageResizeMethod import org.nd4j.linalg.api.buffer.DataType import org.nd4j.linalg.factory.Nd4j import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum import java.lang.IllegalArgumentException /** * A port of resize.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/resize.py#L195 * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["ResizeNearest"],frameworkName = "onnx") class ResizeNearest : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { // Parameter docs below are from the onnx operator docs: // https://github.com/onnx/onnx/blob/master/docs/Operators.md#resize var inputVariable = sd.getVariable(op.inputsToOp[0]) val inputShape = sd.shape(inputVariable) val roi = sd.getVariable(op.inputsToOp[1]) val scales = sd.getVariable(op.inputsToOp[2]) val sizes = sizes(sd,op) /** * * If coordinate_transformation_mode is "half_pixel", x_original = (x_resized + 0.5) / scale - 0.5, if coordinate_transformation_mode is "pytorch_half_pixel", x_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0, if coordinate_transformation_mode is "align_corners", x_original = x_resized * (length_original - 1) / (length_resized - 1), if coordinate_transformation_mode is "asymmetric", x_original = x_resized / scale, if coordinate_transformation_mode is "tf_crop_and_resize", x_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1). */ val coordTransformationMode = attributes.getOrDefault("coordinate_transformation_mode","half_pixel") as String val extrapolationValue = attributes.getOrDefault("extrapolation_value",0.0) as Double /** * Three interpolation modes: nearest (default), linear and cubic. The "linear" mode includes linear * interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). * The "cubic" mode includes cubic interpolation for 1D tensor * and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor). */ val mode = attributes.getOrDefault("mode","nearest") as String val outputVarName = outputNames[0] val outputSize = outputSize(sd, op, inputVariable, scales, sizes,inputShape) outputSize!!.setShape(2) //switch to NWHC (tensorflow format) and then back to NCHW (onnx format) inputVariable = sd.permute(inputVariable,0,2,3,1) var result: SDVariable? = null when (coordTransformationMode) { "tf_crop_and_resize" -> { val indices = mutableListOf<Int>() val rank = inputVariable.arr.rank() for(i in 2 until rank) { indices.add(i - 2,i) indices.add(i,i + rank) } val boxes = sd.expandDims(sd.gather(roi,indices.toIntArray(),0),0) val boxIndices = sd.range(0.0,inputVariable.shape[0] as Double,1.0, DataType.INT64) result = sd.image().cropAndResize(inputVariable,boxes,boxIndices,outputSize,extrapolationValue) } "align_corners" -> { result = invokeResize(mode, sd, inputVariable, outputSize, true, false) } "asymmetric" -> { result = invokeResize(mode, sd, inputVariable, outputSize, false, false) } else -> { when(mode) { "nearest" -> { result = sd.image().imageResize(inputVariable,outputSize,false,false,ImageResizeMethod.ResizeNearest) } "cubic" -> { result = sd.image().imageResize(inputVariable,outputSize,false,false,ImageResizeMethod.ResizeBicubic) } "linear" -> { result = sd.image().imageResize(inputVariable,outputSize,false,false,ImageResizeMethod.ResizeBilinear) } } if(result == null) { throw IllegalArgumentException("Illegal mode found $mode") } } } val finalOutput = sd.permute(outputVarName,result,0,3,1,2) return mapOf(finalOutput.name() to listOf(finalOutput)) } fun invokeResize( type: String, sd: SameDiff, input: SDVariable, size: SDVariable, alignCorners: Boolean, halfPixelCenters: Boolean ): SDVariable? { return when (type) { "linear" -> { val height = size.arr.getInt(0) val width = size.arr.getInt(1) sd.image().resizeBiLinear(input,height,width, alignCorners, halfPixelCenters) } "cubic" -> { sd.image().resizeBiCubic(input,size,alignCorners,halfPixelCenters) } else -> { sd.image().imageResize(input,size,true,true,ImageResizeMethod.ResizeNearest) } } } fun outputSize( sd: SameDiff, op: SameDiffOp, input: SDVariable, scales: SDVariable, sizes: SDVariable, inputVariableShape: SDVariable ): SDVariable? { var ret: SDVariable? = null ret = if(op.inputsToOp.size == 3) { val heightWidthScale = scales.get(SDIndex.interval(2,-1)) val subGet = inputVariableShape.get(SDIndex.interval(2,-1)) val heightWidthShape = sd.castTo(subGet,heightWidthScale.dataType()) val scaled = sd.castTo(sd.math.mul(heightWidthScale,heightWidthShape),DataType.INT32) scaled } else { sizes.get(SDIndex.interval(2, 1,input.rank().arr.getInt(0))) } if(ret.shape.size < 2) { var newRet = sd.zero(null,DataType.INT32,2) ret = newRet.add(ret.arr.getInt(0).toDouble()) } return ret.castTo(DataType.INT32) } fun alignCornersFor(coordTransformationMode: String): Boolean { //note this includes the coordTransformationMode == "asymmetric" return coordTransformationMode == "align_corners" } fun sizes(sd: SameDiff,op: SameDiffOp): SDVariable { if(op.inputsToOp.size == 4) return sd.getVariable(op.inputsToOp[3]) else return sd.constant(Nd4j.empty()) } }
apache-2.0
9ffb6c31538369754a8e6910b7ad3c11
42.557214
203
0.622458
4.139007
false
false
false
false
exponent/exponent
packages/expo-image/android/src/main/java/expo/modules/image/events/ImageLoadEventsManager.kt
2
2189
package expo.modules.image.events import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.target.Target import com.bumptech.glide.request.transition.Transition import com.facebook.react.modules.network.ProgressListener import com.facebook.react.uimanager.events.Event import com.facebook.react.uimanager.events.RCTEventEmitter class ImageLoadEventsManager(private val mViewId: Int, private val mEventEmitter: RCTEventEmitter?) : CustomTarget<BitmapFactory.Options?>(), RequestListener<Drawable?>, ProgressListener { private var mBitmapFactoryOptions: BitmapFactory.Options? = null private var mDataSource: DataSource? = null private var mModel: Any? = null fun onLoadStarted() { dispatch(ImageLoadStartEvent(mViewId)) } override fun onProgress(bytesWritten: Long, contentLength: Long, done: Boolean) { dispatch(ImageProgressEvent(mViewId, bytesWritten, contentLength, done)) } override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Drawable?>, isFirstResource: Boolean): Boolean { dispatch(ImageErrorEvent(mViewId, e)) return false } override fun onResourceReady(resource: BitmapFactory.Options, transition: Transition<in BitmapFactory.Options?>?) { mBitmapFactoryOptions = resource onResourceReady() } override fun onResourceReady(resource: Drawable?, model: Any, target: Target<Drawable?>, dataSource: DataSource, isFirstResource: Boolean): Boolean { mModel = model mDataSource = dataSource onResourceReady() return false } private fun onResourceReady() { if (mModel != null && mDataSource != null && mBitmapFactoryOptions != null) { dispatch(ImageLoadEvent(mViewId, mModel!!, mDataSource!!, mBitmapFactoryOptions!!)) } } override fun onLoadCleared(placeholder: Drawable?) = Unit // do nothing private fun dispatch(event: Event<*>) { if (mEventEmitter != null) { event.dispatch(mEventEmitter) } } }
bsd-3-clause
66930576300983256711813562664df1
37.403509
188
0.768387
4.579498
false
false
false
false
AndroidX/androidx
compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/IconButtonSamples.kt
3
4437
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.samples import androidx.annotation.Sampled import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.outlined.Lock import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledIconButton import androidx.compose.material3.FilledIconToggleButton import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.FilledTonalIconToggleButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconToggleButton import androidx.compose.material3.OutlinedIconButton import androidx.compose.material3.OutlinedIconToggleButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.tooling.preview.Preview @Preview @Sampled @Composable fun IconButtonSample() { IconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } @Preview @Sampled @Composable fun IconToggleButtonSample() { var checked by remember { mutableStateOf(false) } IconToggleButton(checked = checked, onCheckedChange = { checked = it }) { if (checked) { Icon(Icons.Filled.Lock, contentDescription = "Localized description") } else { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun FilledIconButtonSample() { FilledIconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun FilledIconToggleButtonSample() { var checked by remember { mutableStateOf(false) } FilledIconToggleButton(checked = checked, onCheckedChange = { checked = it }) { if (checked) { Icon(Icons.Filled.Lock, contentDescription = "Localized description") } else { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun FilledTonalIconButtonSample() { FilledTonalIconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun FilledTonalIconToggleButtonSample() { var checked by remember { mutableStateOf(false) } FilledTonalIconToggleButton(checked = checked, onCheckedChange = { checked = it }) { if (checked) { Icon(Icons.Filled.Lock, contentDescription = "Localized description") } else { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun OutlinedIconButtonSample() { OutlinedIconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun OutlinedIconToggleButtonSample() { var checked by remember { mutableStateOf(false) } OutlinedIconToggleButton(checked = checked, onCheckedChange = { checked = it }) { if (checked) { Icon(Icons.Filled.Lock, contentDescription = "Localized description") } else { Icon(Icons.Outlined.Lock, contentDescription = "Localized description") } } }
apache-2.0
76c9d13ba57035b048a353feedf24100
31.625
88
0.738337
4.428144
false
false
false
false
TeamWizardry/LibrarianLib
modules/glitter/src/main/kotlin/com/teamwizardry/librarianlib/glitter/bindings/PathBinding.kt
1
2262
package com.teamwizardry.librarianlib.glitter.bindings import com.teamwizardry.librarianlib.math.Easing import com.teamwizardry.librarianlib.glitter.ParticlePath import com.teamwizardry.librarianlib.glitter.ParticleSystem import com.teamwizardry.librarianlib.glitter.ReadParticleBinding public class PathBinding @JvmOverloads constructor( /** * The lifetime binding for the particle. Generally [ParticleSystem.lifetime] */ override val lifetime: ReadParticleBinding, /** * The age binding for the particle. Generally [ParticleSystem.age] */ override val age: ReadParticleBinding, /** * The multiplier for the normalized age. If this value is > 1 the movement will loop, and if this value is < 1 * the movement will end before the end of the path. */ override val timescale: ReadParticleBinding? = null, /** * The time offset for the normalized age. Applied before the [timescale], so regardless of [timescale]'s value, * if the offset is 0.5, the animation will begin halfway along the path */ override val offset: ReadParticleBinding? = null, /** * The path object to use for the positioning. */ @JvmField public val path: ParticlePath, /** * The start value to interpolate from. */ @JvmField public var origin: ReadParticleBinding = ConstantBinding(*DoubleArray(path.value.size) { 0.0 }), /** * The end value to interpolate to. */ @JvmField public var target: ReadParticleBinding = ConstantBinding(*DoubleArray(path.value.size) { 1.0 }), /** * The easing to use when generating values for the binding. */ override val easing: Easing = Easing.linear ): AbstractTimeBinding(lifetime, age, timescale, offset, easing) { override val contents: DoubleArray = DoubleArray(path.value.size) init { lifetime.require(1) age.require(1) timescale?.require(1) offset?.require(1) } override fun load(particle: DoubleArray) { super.load(particle) path.computePosition(particle, time * easing.ease(time.toFloat())) for (i in contents.indices) { contents[i] = origin.contents[i] + (target.contents[i] * path.value[i]) } } }
lgpl-3.0
b962ef40eb8a1627b1f02a77662dd32d
36.098361
116
0.683466
4.366795
false
false
false
false