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
vovagrechka/fucking-everything
shared-idea/src/main/java/shared-idea.kt
1
13886
package vgrechka.idea import com.intellij.execution.ExecutionManager import com.intellij.execution.Executor import com.intellij.execution.ExecutorRegistry import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.actions.ChooseRunConfigurationPopup import com.intellij.execution.actions.ExecutorProvider import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.filters.TextConsoleBuilderFactory import com.intellij.execution.impl.ConsoleViewImpl import com.intellij.execution.impl.ConsoleViewUtil import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.ui.* import com.intellij.execution.ui.actions.CloseAction import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.unscramble.AnnotateStackTraceAction import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import javax.swing.JPanel import vgrechka.* import java.io.PrintWriter import java.io.StringWriter import java.util.* import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.TimeUnit import kotlin.concurrent.thread //val Project.bullshitter by AttachedComputedShit(::Bullshitter) class Bullshitter(val project: Project, val title: String? = null) { val consoleView: ConsoleView by relazy { var newConsoleView by notNullOnce<ConsoleView>() ApplicationManager.getApplication().invokeAndWait { val bullshitterID = UUID.randomUUID().toString() clog("Creating bullshitter for project ${project.name}: $bullshitterID") val builder = TextConsoleBuilderFactory.getInstance().createBuilder(project) newConsoleView = builder.console val toolbarActions = DefaultActionGroup() val consoleComponent = MyConsolePanel(newConsoleView, toolbarActions) val bullshitterDescr = object : RunContentDescriptor(newConsoleView, null, consoleComponent, title ?: "Bullshitter", null) { override fun isContentReuseProhibited(): Boolean { return true } } val executor = DefaultRunExecutor.getRunExecutorInstance() for (action in newConsoleView.createConsoleActions()) { toolbarActions.add(action) } val console = newConsoleView as ConsoleViewImpl ConsoleViewUtil.enableReplaceActionForConsoleViewEditor(console.editor) console.editor.settings.isCaretRowShown = true toolbarActions.add(AnnotateStackTraceAction(console.editor, console.hyperlinks)) toolbarActions.add(CloseAction(executor, bullshitterDescr, project)) ExecutionManager.getInstance(project).contentManager.showRunContent(executor, bullshitterDescr) newConsoleView.allowHeavyFilters() ExecutionManager.getInstance(project).contentManager val con = project.messageBus.connect() con.subscribe(RunContentManager.TOPIC, object:RunContentWithExecutorListener { override fun contentSelected(descriptor: RunContentDescriptor?, executor: Executor) { if (descriptor == bullshitterDescr) { clog("Bullshitter selected: $bullshitterID") } } override fun contentRemoved(descriptor: RunContentDescriptor?, executor: Executor) { if (descriptor == bullshitterDescr) { clog("Bullshitter removed: $bullshitterID") con.disconnect() relazy.reset(this@Bullshitter::consoleView) } } }) } newConsoleView } fun mumble(s: String) { mumbleNoln(s + "\n") } fun mumbleNoln(s: String) { consoleView.print(s, ConsoleViewContentType.NORMAL_OUTPUT) } fun bark(s: String) { consoleView.print(s + "\n", ConsoleViewContentType.ERROR_OUTPUT) } fun bark(e: Throwable) { e.printStackTrace() val stringWriter = StringWriter() e.printStackTrace(PrintWriter(stringWriter)) bark(stringWriter.toString()) } private class MyConsolePanel(consoleView: ExecutionConsole, toolbarActions: ActionGroup) : JPanel(BorderLayout()) { init { val toolbarPanel = JPanel(BorderLayout()) toolbarPanel.add(ActionManager.getInstance() .createActionToolbar("PLACE?", toolbarActions, false) .component) add(toolbarPanel, BorderLayout.WEST) add(consoleView.component, BorderLayout.CENTER) } } } fun openFile(project: Project, path: String, line: Int): Boolean { val file = LocalFileSystem.getInstance().findFileByPath(path) ?: return false NonProjectFileWritingAccessProvider.allowWriting(file) val descriptor = OpenFileDescriptor(project, file) val editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true) ?: bitch("f1924b93-fc47-4c88-8d7a-75c94e67e481") val position = LogicalPosition(line - 1, 0) editor.caretModel.removeSecondaryCarets() editor.caretModel.moveToLogicalPosition(position) editor.scrollingModel.scrollToCaret(ScrollType.CENTER) editor.selectionModel.removeSelection() IdeFocusManager.getGlobalInstance().requestFocus(editor.contentComponent, true) return true } object IDEAPile { fun showErrorBalloonForDebugToolWindow(project: Project, fullMessage: String) { val toolWindowManager = ToolWindowManager.getInstance(project) val toolWindowId = ToolWindowId.DEBUG if (toolWindowManager.canShowNotification(toolWindowId)) { toolWindowManager.notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, null) } else { throw Exception("UIUtil.toHtml is no longer on classpath. Move freaking IDEA-related sub-projects out of FE") // Messages.showErrorDialog(project, UIUtil.toHtml(fullMessage), "") } } fun getVirtualFileByPath(path: String): VirtualFile? { return LocalFileSystem.getInstance().findFileByPath(path) } fun runConfiguration(project: Project, configurationName: String, debug: Boolean = false) { later { val res = getRunningContentDescriptors(project, configurationName, debug) val candy = when (res) { is IDEAPile.GetRunningDescriptorsResult.Poop -> bitch(res.error) is IDEAPile.GetRunningDescriptorsResult.Candy -> res } if (candy.descriptors.isNotEmpty()) { ExecutionUtil.restart(candy.descriptors.first()) } else { ExecutionUtil.runConfiguration(candy.config, getRunExecutor(debug)) } } } sealed class GetRunningDescriptorsResult { class Poop(val error: String) : GetRunningDescriptorsResult() class Candy(val config: RunnerAndConfigurationSettings, val descriptors: List<RunContentDescriptor>) : GetRunningDescriptorsResult() } fun getRunningContentDescriptorsFromNonUIThread(project: Project, configurationName: String, debug: Boolean = false): GetRunningDescriptorsResult { val queue = ArrayBlockingQueue<GetRunningDescriptorsResult>(1) later { val res = getRunningContentDescriptors(project, configurationName, debug) queue.add(res) } return queue.poll(1, TimeUnit.SECONDS) ?: bitch("Sick of waiting for running content descriptors from UI thread") } fun getRunningContentDescriptors(project: Project, configurationName: String, debug: Boolean = false): GetRunningDescriptorsResult { val executor = getRunExecutor(debug) val executorProvider = ExecutorProvider {executor} val list = ChooseRunConfigurationPopup.createSettingsList(project, executorProvider, false) for (item in list) { val config = item.value if (config is RunnerAndConfigurationSettings) { if (config.name == configurationName) { val runningDescriptors = ExecutionManagerImpl.getInstance(project).getRunningDescriptors {it == config} return GetRunningDescriptorsResult.Candy(config, runningDescriptors) } } } return GetRunningDescriptorsResult.Poop("No fucking run configuration `$configurationName` in `${project.name}`") } private fun getRunExecutor(debug: Boolean): Executor { val executorToolWindowID = when { debug -> ToolWindowId.DEBUG else -> ToolWindowId.RUN } val executor = ExecutorRegistry.getInstance().getExecutorById(executorToolWindowID) return executor } fun errorDialog(msg: String) { later {Messages.showErrorDialog(msg, "Shit Didn't Work")} } fun errorDialog(e: Throwable) { later {Messages.showErrorDialog(e.stackTraceString, "Shit Didn't Work")} } fun infoDialog(message: String) { later {Messages.showInfoMessage(message, "Read This Shit")} } fun showingErrorOnException(block: () -> Unit) { try { block() } catch (e: Throwable ) { IDEAPile.errorDialog(e) } } fun later(block: () -> Unit) { ApplicationManager.getApplication().invokeLater(block) } class WaitRunConfigurationStatus(val project: Project, val configurationName: String, val debug: Boolean) { val pollInterval = 100L class Sick(msg: String) : Exception(msg) fun loopUntilTrueOrTimeout(timeout: Int, test: () -> Boolean): Boolean { // We don't want accidental infinite loop due to some bug in return logic, as that will render whole IDE hosed. // Approximate timeout is OK val numIterations = timeout / pollInterval check(numIterations in 1..300) {"fe6fbc28-db08-4754-a4b9-26b39cb7c5f2"} for (i in 1..numIterations) { Thread.sleep(pollInterval) if (test()) return true } return false } fun wait(timeout: Int, errorMessage: String, condition: (List<RunContentDescriptor>) -> Boolean) { val ok = loopUntilTrueOrTimeout(timeout) { val descriptors = (getRunningContentDescriptorsFromNonUIThread(project, configurationName, debug) as? GetRunningDescriptorsResult.Candy ?: bitch("d687999f-5597-45da-a282-637976a0bac4")) .descriptors condition(descriptors) } if (!ok) throw Sick(errorMessage) } } /** * Don't call this on UI thread * @throws something if failed */ fun waitForConfigurationToRunAndThenTerminate(project: Project, configurationName: String, debug: Boolean, runTimeout: Int, terminationTimeout: Int) { val wrcs = WaitRunConfigurationStatus(project, configurationName, debug) wrcs.wait(runTimeout, "Sick of waiting for this shit to run: $configurationName") {it.isNotEmpty()} wrcs.wait(terminationTimeout, "Sick of waiting for this shit to terminate: $configurationName") {it.isEmpty()} } /** * Don't call this on UI thread * @throws something if failed */ fun waitForConfigurationToTerminateAndThenRun(project: Project, configurationName: String, debug: Boolean, runTimeout: Int, terminationTimeout: Int) { val wrcs = WaitRunConfigurationStatus(project, configurationName, debug) wrcs.wait(terminationTimeout, "Sick of waiting for this shit to terminate: $configurationName") {it.isEmpty()} wrcs.wait(runTimeout, "Sick of waiting for this shit to run: $configurationName") {it.isNotEmpty()} } fun showProgressBalloon(project: Project?, messageType: MessageType, message: String) { IDEAPile.later { val ideFrame = WindowManager.getInstance().getIdeFrame(project) if (ideFrame != null) { val statusBar = ideFrame.statusBar as StatusBarEx statusBar.notifyProgressByBalloon(messageType, message, null, null) } } } fun revealingException(showInBalloon: ((Throwable) -> Boolean)? = null, block: () -> Unit) { val theShowInBalloon = showInBalloon ?: {false} try { block() } catch(e: Throwable) { if (theShowInBalloon(e)) showProgressBalloon(null, MessageType.ERROR, e.message ?: "No fucking message") else IDEAPile.later {IDEAPile.errorDialog(e)} } } fun threadRevealingException(showInBalloon: ((Throwable) -> Boolean)? = null, block: () -> Unit) { thread { revealingException(showInBalloon, block) } } }
apache-2.0
3fcde9cba0dd5db456bd9f4ba25de54f
38.787966
154
0.674924
4.961058
false
true
false
false
stefanmedack/cccTV
app/src/test/java/de/stefanmedack/ccctv/ui/detail/DetailViewModelTest.kt
1
3786
package de.stefanmedack.ccctv.ui.detail import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import de.stefanmedack.ccctv.repository.EventRepository import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.schedulers.Schedulers import org.amshove.kluent.When import org.amshove.kluent.any import org.amshove.kluent.calling import org.amshove.kluent.itReturns import org.junit.Before import org.junit.Test import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.MockitoAnnotations class DetailViewModelTest { @Mock private lateinit var repository: EventRepository @InjectMocks private lateinit var detailViewModel: DetailViewModel @Before fun setUp() { MockitoAnnotations.initMocks(this) RxAndroidPlugins.setInitMainThreadSchedulerHandler { _ -> Schedulers.trampoline() } When calling repository.isBookmarked(any()) itReturns Flowable.just(true) } @Test fun `bookmarking a not-bookmarked event should change bookmark state to true`() { val testEventId = "3" val isBookmarked = false When calling repository.isBookmarked(testEventId) itReturns Flowable.just(isBookmarked) When calling repository.changeBookmarkState(testEventId, isBookmarked) itReturns Completable.complete() detailViewModel.init(testEventId) detailViewModel.toggleBookmark() verify(repository).changeBookmarkState(testEventId, true) } @Test fun `un-bookmarking an event should change bookmark state to false`() { val testEventId = "3" val isBookmarked = true When calling repository.isBookmarked(testEventId) itReturns Flowable.just(isBookmarked) When calling repository.changeBookmarkState(testEventId, isBookmarked) itReturns Completable.complete() detailViewModel.init(testEventId) detailViewModel.toggleBookmark() verify(repository).changeBookmarkState(testEventId, false) } @Test fun `bookmarking an event after disposing the view model is ignored`() { val testEventId = "3" val isBookmarked = true When calling repository.isBookmarked(testEventId) itReturns Flowable.just(isBookmarked) When calling repository.changeBookmarkState(testEventId, isBookmarked) itReturns Completable.complete() detailViewModel.init(testEventId) reset(repository) detailViewModel.onCleared() detailViewModel.toggleBookmark() verifyNoMoreInteractions(repository) } @Test fun `saving playback position after a minimum playback time should be saved in repository`() { val testEventId = "3" detailViewModel.init(testEventId) detailViewModel.inputs.savePlaybackPosition(playedSeconds = 180, totalDurationSeconds = 2300) verify(repository).savePlayedSeconds(eventId = testEventId, seconds = 180) } @Test fun `saving playback position before the minimum playback time should delete saved playback position`() { val testEventId = "3" detailViewModel.init(testEventId) detailViewModel.inputs.savePlaybackPosition(playedSeconds = 30, totalDurationSeconds = 2300) verify(repository).deletePlayedSeconds(testEventId) } @Test fun `saving playback position when video is almost finished should delete saved playback position`() { val testEventId = "3" detailViewModel.init(testEventId) detailViewModel.inputs.savePlaybackPosition(playedSeconds = 2250, totalDurationSeconds = 2300) verify(repository).deletePlayedSeconds(testEventId) } }
apache-2.0
70e0af2232bc8df7dd1c041f26beb6c0
34.064815
111
0.743001
5.01457
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrame/ExistingInstanceThisRemapper.kt
4
3210
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core.stackFrame import com.intellij.debugger.engine.JavaValue import com.intellij.debugger.ui.impl.watch.ThisDescriptorImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.xdebugger.frame.XValue import com.intellij.xdebugger.frame.XValueChildrenList import org.jetbrains.kotlin.utils.getSafe import java.lang.reflect.Modifier // Very Dirty Work-around. // We should stop delegating to the Java stack frame and generate our trace elements from scratch. class ExistingInstanceThisRemapper( private val children: XValueChildrenList, private val index: Int, val value: XValue, private val size: Int ) { companion object { private val LOG = Logger.getInstance(this::class.java) private const val THIS_NAME = "this" fun find(children: XValueChildrenList): ExistingInstanceThisRemapper? { val size = children.size() for (i in 0 until size) { if (children.getName(i) == THIS_NAME) { val valueDescriptor = (children.getValue(i) as? JavaValue)?.descriptor if (valueDescriptor !is ThisDescriptorImpl) { return null } return ExistingInstanceThisRemapper( children, i, children.getValue(i), size ) } } return null } } fun remapName(newName: String) { val (names, _) = getLists() ?: return names[index] = newName } fun remove() { val (names, values) = getLists() ?: return names.removeAt(index) values.removeAt(index) } private fun getLists(): Lists? { if (children.size() != size) { throw IllegalStateException("Children list was modified") } var namesList: MutableList<Any?>? = null var valuesList: MutableList<Any?>? = null for (field in XValueChildrenList::class.java.declaredFields) { val mods = field.modifiers if (Modifier.isPrivate(mods) && Modifier.isFinal(mods) && !Modifier.isStatic(mods) && field.type == List::class.java) { @Suppress("UNCHECKED_CAST") val list = (field.getSafe(children) as? MutableList<Any?>)?.takeIf { it.size == size } ?: continue if (list[index] == THIS_NAME) { namesList = list } else if (list[index] === value) { valuesList = list } } if (namesList != null && valuesList != null) { return Lists(namesList, valuesList) } } @Suppress("UNNECESSARY_SAFE_CALL") LOG.error("Can't find name/value lists, existing fields: " + XValueChildrenList::class.java.declaredFields?.contentToString()) return null } private data class Lists(val names: MutableList<Any?>, val values: MutableList<Any?>) }
apache-2.0
8cebf04ea1a48d3eb67218303936e529
33.902174
134
0.588785
4.741507
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/liftOut/liftToAssignment/operatorFunWithTypeParam.kt
2
336
class TypeWithTypeParam<E> { var value: String = "" } operator fun <T> TypeWithTypeParam<T>.plusAssign(x: T) { value += x.toString() } fun foo(x: Int, y: Long?) { val foo: TypeWithTypeParam<Number?> = TypeWithTypeParam() <caret>when (x) { 3 -> foo += x 4 -> foo += y else -> foo += null } }
apache-2.0
30ba40e48d2043fdf7e5c0fd7abcde97
20.0625
61
0.550595
3.169811
false
false
false
false
smmribeiro/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/BaseXmlOutputter.kt
5
2228
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import org.jdom.DocType import org.jdom.ProcessingInstruction import java.io.IOException import java.io.Writer abstract class BaseXmlOutputter(protected val lineSeparator: String) { companion object { fun doesNameSuggestSensitiveInformation(name: String): Boolean { if (name.contains("password")) { val isRemember = name.contains("remember", ignoreCase = true) || name.contains("keep", ignoreCase = true) || name.contains("use", ignoreCase = true) || name.contains("save", ignoreCase = true) || name.contains("stored", ignoreCase = true) return !isRemember } return false } } /** * This handle printing the DOCTYPE declaration if one exists. * * @param docType `Document` whose declaration to write. * @param out `Writer` to use. */ @Throws(IOException::class) protected fun printDocType(out: Writer, docType: DocType) { val publicID = docType.publicID val systemID = docType.systemID val internalSubset = docType.internalSubset var hasPublic = false out.write("<!DOCTYPE ") out.write(docType.elementName) if (publicID != null) { out.write(" PUBLIC \"") out.write(publicID) out.write('"'.toInt()) hasPublic = true } if (systemID != null) { if (!hasPublic) { out.write(" SYSTEM") } out.write(" \"") out.write(systemID) out.write("\"") } if (internalSubset != null && !internalSubset.isEmpty()) { out.write(" [") out.write(lineSeparator) out.write(docType.internalSubset) out.write("]") } out.write(">") } @Throws(IOException::class) protected fun writeProcessingInstruction(out: Writer, pi: ProcessingInstruction, target: String) { out.write("<?") out.write(target) val rawData = pi.data if (rawData != null && !rawData.isEmpty()) { out.write(" ") out.write(rawData) } out.write("?>") } }
apache-2.0
89d480a60611b22a820af6d765df1f72
28.72
140
0.61535
4.141264
false
false
false
false
smmribeiro/intellij-community
plugins/completion-ml-ranking-models/src/com/jetbrains/completion/ml/ranker/ExperimentScalaMLRankingProvider.kt
12
760
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.completion.ml.ranker import com.intellij.completion.ml.ranker.ExperimentModelProvider import com.intellij.internal.ml.catboost.CatBoostJarCompletionModelProvider import com.intellij.lang.Language class ExperimentScalaMLRankingProvider : CatBoostJarCompletionModelProvider( CompletionRankingModelsBundle.message("ml.completion.experiment.model.scala"), "scala_features_exp", "scala_model_exp"), ExperimentModelProvider { override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("Scala", ignoreCase = true) == 0 override fun experimentGroupNumber(): Int = 13 }
apache-2.0
8fff0c84d204f7c93b30b7fb3896bdb5
53.357143
148
0.817105
4.606061
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceRcp.kt
1
1704
package com.cognifide.gradle.aem.instance.tasks import com.cognifide.gradle.aem.AemDefaultTask import com.cognifide.gradle.aem.common.instance.rcp.RcpClient import org.gradle.api.tasks.TaskAction open class InstanceRcp : AemDefaultTask() { private val notifier = common.notifier fun options(configurer: RcpClient.() -> Unit) { this.options = configurer } private var options: RcpClient.() -> Unit = {} @TaskAction fun run() = aem.rcp { aem.prop.string("instance.rcp.source")?.run { sourceInstance = aem.instance(this) } aem.prop.string("instance.rcp.target")?.run { targetInstance = aem.instance(this) } aem.prop.list("instance.rcp.paths")?.let { paths = it } aem.prop.string("instance.rcp.pathsFile")?.let { pathsFile = aem.project.file(it) } aem.prop.string("instance.rcp.workspace")?.let { workspace = it } aem.prop.string("instance.rcp.opts")?.let { opts = it } options() copy() val summary = summary() logger.info("RCP details: $summary") if (!summary.source.cmd && !summary.target.cmd) { notifier.lifecycle("RCP finished", "Copied ${summary.copiedPaths} JCR root(s) from instance ${summary.source.name} to ${summary.target.name}." + "Duration: ${summary.durationString}") } else { notifier.lifecycle("RCP finished", "Copied ${summary.copiedPaths} JCR root(s) between instances." + "Duration: ${summary.durationString}") } } init { description = "Copy JCR content from one instance to another." } companion object { const val NAME = "instanceRcp" } }
apache-2.0
8ea99ff780de9e4683b00042c294ab77
33.77551
156
0.629108
3.890411
false
false
false
false
mackristof/FollowMe
wear/src/main/java/org/mackristof/followme/fragment/DisplayFragment.kt
1
4053
package org.mackristof.followme.fragment import android.app.Fragment import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.res.ColorStateList import android.graphics.Color import android.os.Bundle import android.support.v4.content.LocalBroadcastManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ProgressBar import android.widget.TextView import org.mackristof.followme.* import java.text.SimpleDateFormat import java.util.* /** * Created by christophem on 29/07/2016. */ class DisplayFragment : Fragment() { private var mStatusView: TextView? = null private var mTimeView: TextView? = null private var mAccProgressBar: ProgressBar? = null private var broadcaster: LocalBroadcastManager? = null override fun onCreateView( inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.display_fragment, container, false)!! displayFragmentInstance = this mStatusView = view.findViewById(R.id.status) as TextView mTimeView = view.findViewById(R.id.time) as TextView mAccProgressBar = view.findViewById(R.id.acc) as ProgressBar mAccProgressBar?.progress = 0 broadcaster = LocalBroadcastManager.getInstance(this.context) broadcaster?.registerReceiver(LocationBroadcastReceiver(), IntentFilter(Constants.INTENT_LOCATION)) return view } override fun onStop(){ broadcaster?.unregisterReceiver(LocationBroadcastReceiver()) super.onStop() } override fun onPause(){ broadcaster?.unregisterReceiver(LocationBroadcastReceiver()) super.onPause() } override fun onResume(){ if (Utils.isServiceRunning(this.context, GpsService::class.java.name)){ broadcaster?.registerReceiver(LocationBroadcastReceiver(), IntentFilter(Constants.INTENT_LOCATION)) } super.onResume() } private class LocationBroadcastReceiver: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent!!.hasExtra(Constants.INTENT_LOCATION)){ val location: Location = intent.getParcelableExtra(Constants.INTENT_LOCATION) val displayedLoc = """ location : ${SimpleDateFormat("HH:mm:ss").format(location.timestamp)} ${String.format("%.1f",location.lat)}, ${String.format("%.1f",location.lon)} atl : ${String.format(".%1f",location.corAlt)}(${String.format("%.1f",location.alt)}) acc ${String.format("%.1f",location.acc)} nb Sats ${location.nbSats} """ DisplayFragment.getInstance().updateDisplay(location, displayedLoc) } else { DisplayFragment.getInstance().updateDisplay(null, intent.getStringExtra(Constants.INTENT_LOCATION_STATUS)) } } } private fun updateDisplay(location: Location?, status: String) { if (location !=null) { mTimeView!!.text = SimpleDateFormat("HH:mm:ss").format(location?.timestamp) if (location != null) { mAccProgressBar?.progress = if (location.acc < 10) 100 else if (location.acc < 50) 50 else 20 val color = if (location.acc < 10) Color.GREEN else if (location.acc < 50) Color.YELLOW else Color.RED mAccProgressBar?.setProgressTintList(ColorStateList.valueOf(color)) } } mStatusView?.text = status } companion object { private var displayFragmentInstance: DisplayFragment? = null fun getInstance(): DisplayFragment { if (displayFragmentInstance !=null) { return displayFragmentInstance as DisplayFragment } else { throw IllegalStateException("DisplayFragment instance is null") } } } }
apache-2.0
f00ef07517b389037bc5cf896d44429d
33.939655
122
0.68073
4.745902
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/permission/list/PermissionListFragmentViewModel.kt
1
2394
package sk.styk.martin.apkanalyzer.ui.permission.list import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import sk.styk.martin.apkanalyzer.manager.appanalysis.AppPermissionManager import sk.styk.martin.apkanalyzer.manager.navigationdrawer.NavigationDrawerModel import sk.styk.martin.apkanalyzer.util.coroutines.DispatcherProvider import javax.inject.Inject @HiltViewModel class PermissionListFragmentViewModel @Inject constructor( private val dispatcherProvider: DispatcherProvider, val permissionListAdapter: PermissionListAdapter, private val navigationDrawerModel: NavigationDrawerModel, private val appPermissionManager: AppPermissionManager, ) : ViewModel() { val openPermission = permissionListAdapter.openPermission private val isLoadingLiveData = MutableLiveData(true) val isLoading: LiveData<Boolean> = isLoadingLiveData private val loadingProgressLiveData = MutableLiveData<Int>() val loadingProgress: LiveData<Int> = loadingProgressLiveData private val loadingProgressMaxLiveData = MutableLiveData<Int>() val loadingProgressMax: LiveData<Int> = loadingProgressMaxLiveData init { viewModelScope.launch { appPermissionManager.observeAllPermissionData() .flowOn(dispatcherProvider.default()) .collect { when (it) { is AppPermissionManager.PermissionLoadingStatus.Loading -> { loadingProgressLiveData.value = it.currentProgress loadingProgressMaxLiveData.value = it.totalProgress isLoadingLiveData.value = true } is AppPermissionManager.PermissionLoadingStatus.Data -> { permissionListAdapter.permissions = it.localPermissionData isLoadingLiveData.value = false } } } } } fun onNavigationClick() = viewModelScope.launch { navigationDrawerModel.openDrawer() } }
gpl-3.0
094f64d283ab8d73837e2befa1de47ba
40.275862
90
0.677109
5.925743
false
false
false
false
AMARJITVS/NoteDirector
app/src/main/kotlin/com/amar/notesapp/fragments/PhotoFragment.kt
1
10752
package com.amar.NoteDirector.fragments import android.content.res.Configuration import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Color import android.graphics.Matrix import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.bumptech.glide.Priority import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.davemorrissey.labs.subscaleview.ImageSource import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView import com.simplemobiletools.commons.extensions.beGone import com.simplemobiletools.commons.extensions.beVisible import com.simplemobiletools.commons.extensions.toast import com.amar.NoteDirector.activities.ViewPagerActivity import com.amar.NoteDirector.extensions.config import com.amar.NoteDirector.extensions.getFileSignature import com.amar.NoteDirector.extensions.getRealPathFromURI import com.amar.NoteDirector.extensions.portrait import com.amar.NoteDirector.helpers.GlideRotateTransformation import com.amar.NoteDirector.helpers.MEDIUM import com.amar.NoteDirector.models.Medium import it.sephiroth.android.library.exif2.ExifInterface import kotlinx.android.synthetic.main.pager_photo_item.view.* import java.io.File import java.io.FileOutputStream import java.io.IOException class PhotoFragment : ViewPagerFragment() { lateinit var medium: Medium lateinit var view: ViewGroup private var isFragmentVisible = false private var wasInit = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { view = inflater.inflate(com.amar.NoteDirector.R.layout.pager_photo_item, container, false) as ViewGroup medium = arguments.getSerializable(MEDIUM) as Medium if (medium.path.startsWith("content://")) { val originalPath = medium.path medium.path = context.getRealPathFromURI(Uri.parse(medium.path)) ?: "" if (medium.path.isEmpty()) { var out: FileOutputStream? = null try { var inputStream = context.contentResolver.openInputStream(Uri.parse(originalPath)) val exif = ExifInterface() exif.readExif(inputStream, ExifInterface.Options.OPTION_ALL) val tag = exif.getTag(ExifInterface.TAG_ORIENTATION) val orientation = tag?.getValueAsInt(-1) ?: -1 inputStream = context.contentResolver.openInputStream(Uri.parse(originalPath)) val original = BitmapFactory.decodeStream(inputStream) val rotated = rotateViaMatrix(original, orientation) exif.setTagValue(ExifInterface.TAG_ORIENTATION, 1) exif.removeCompressedThumbnail() val file = File(context.externalCacheDir, Uri.parse(originalPath).lastPathSegment) out = FileOutputStream(file) rotated.compress(Bitmap.CompressFormat.JPEG, 100, out) medium.path = file.absolutePath } catch (e: Exception) { activity.toast(com.amar.NoteDirector.R.string.unknown_error_occurred) return view } finally { try { out?.close() } catch (e: IOException) { } } } } view.subsampling_view.setOnClickListener({ photoClicked() }) view.photo_view.apply { maximumScale = 8f mediumScale = 3f setOnOutsidePhotoTapListener { photoClicked() } setOnPhotoTapListener { _, _, _ -> photoClicked() } } loadImage() wasInit = true return view } override fun setMenuVisibility(menuVisible: Boolean) { super.setMenuVisibility(menuVisible) isFragmentVisible = menuVisible if (wasInit) { if (menuVisible) { addZoomableView() } else { view.subsampling_view.apply { recycle() beGone() background = ColorDrawable(Color.TRANSPARENT) } } } } private fun degreesForRotation(orientation: Int) = when (orientation) { 8 -> 270 3 -> 180 6 -> 90 else -> 0 } private fun rotateViaMatrix(original: Bitmap, orientation: Int): Bitmap { val degrees = degreesForRotation(orientation).toFloat() return if (degrees == 0f) { original } else { val matrix = Matrix() matrix.setRotate(degrees) Bitmap.createBitmap(original, 0, 0, original.width, original.height, matrix, true) } } private fun loadImage() { if (medium.isGif()) { val options = RequestOptions() .priority(if (isFragmentVisible) Priority.IMMEDIATE else Priority.LOW) .diskCacheStrategy(DiskCacheStrategy.DATA) Glide.with(this) .asGif() .load(medium.path) .transition(DrawableTransitionOptions.withCrossFade()) .apply(options) .into(view.photo_view) } else { loadBitmap() } } private fun loadBitmap(degrees: Float = 0f) { if (degrees == 0f) { val targetWidth = if (ViewPagerActivity.screenWidth == 0) Target.SIZE_ORIGINAL else ViewPagerActivity.screenWidth val targetHeight = if (ViewPagerActivity.screenHeight == 0) Target.SIZE_ORIGINAL else ViewPagerActivity.screenHeight val options = RequestOptions() .signature(medium.path.getFileSignature()) .format(DecodeFormat.PREFER_ARGB_8888) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .override(targetWidth, targetHeight) Glide.with(this) .asBitmap() .load(medium.path) .apply(options) .listener(object : RequestListener<Bitmap> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean) = false override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { if (isFragmentVisible) addZoomableView() return false } }).into(view.photo_view) } else { val options = RequestOptions() .diskCacheStrategy(DiskCacheStrategy.NONE) .transform(GlideRotateTransformation(context, degrees)) Glide.with(this) .asBitmap() .load(medium.path) .thumbnail(0.2f) .apply(options) .into(view.photo_view) } } private fun addZoomableView() { if ((medium.isImage()) && isFragmentVisible && view.subsampling_view.visibility == View.GONE) { view.subsampling_view.apply { //setBitmapDecoderClass(GlideDecoder::class.java) // causing random crashes on Android 7+ maxScale = 10f beVisible() setImage(ImageSource.uri(medium.path)) orientation = SubsamplingScaleImageView.ORIENTATION_USE_EXIF setOnImageEventListener(object : SubsamplingScaleImageView.OnImageEventListener { override fun onImageLoaded() { } override fun onReady() { background = ColorDrawable(if (context.config.darkBackground) Color.BLACK else context.config.backgroundColor) setDoubleTapZoomScale(getDoubleTapZoomScale()) } override fun onTileLoadError(e: Exception?) { } override fun onPreviewReleased() { } override fun onImageLoadError(e: Exception) { background = ColorDrawable(Color.TRANSPARENT) beGone() } override fun onPreviewLoadError(e: Exception?) { background = ColorDrawable(Color.TRANSPARENT) beGone() } }) } } } private fun getDoubleTapZoomScale(): Float { val bitmapOptions = BitmapFactory.Options() bitmapOptions.inJustDecodeBounds = true BitmapFactory.decodeFile(medium.path, bitmapOptions) val width = bitmapOptions.outWidth val height = bitmapOptions.outHeight val bitmapAspectRatio = height / (width).toFloat() if (context == null) return 2f return if (context.portrait && bitmapAspectRatio <= 1f) { ViewPagerActivity.screenHeight / height.toFloat() } else if (!context.portrait && bitmapAspectRatio >= 1f) { ViewPagerActivity.screenWidth / width.toFloat() } else { 2f } } fun refreshBitmap() { view.subsampling_view.beGone() loadBitmap() } fun rotateImageViewBy(degrees: Float) { view.subsampling_view.beGone() loadBitmap(degrees) } override fun onDestroyView() { super.onDestroyView() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && !activity.isDestroyed) { Glide.with(context).clear(view.photo_view) } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) loadImage() } private fun photoClicked() { listener?.fragmentClicked() } override fun fullscreenToggled(isFullscreen: Boolean) { } }
apache-2.0
fb5d9ce585121822b9588c8c279f2aea
36.859155
171
0.600446
5.255132
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/mangas/MangaCollectionImpl.kt
1
1309
package xyz.nulldev.ts.api.v2.java.impl.mangas import eu.kanade.tachiyomi.data.database.DatabaseHelper import xyz.nulldev.ts.api.v2.java.impl.util.DbMapper import xyz.nulldev.ts.api.v2.java.impl.util.ProxyList import xyz.nulldev.ts.api.v2.java.model.mangas.MangaCollection import xyz.nulldev.ts.api.v2.java.model.mangas.MangaModel import xyz.nulldev.ts.api.v2.java.model.mangas.Viewer import xyz.nulldev.ts.ext.kInstanceLazy class MangaCollectionImpl(override val id: List<Long>): MangaCollection, List<MangaModel> by ProxyList(id, { MangaCollectionProxy(it) }) { private val db: DatabaseHelper by kInstanceLazy() private val dbMapper = DbMapper( id, dbGetter = { db.getManga(it).executeAsBlocking() }, dbSetter = { db.insertManga(it).executeAsBlocking() } ) override var viewer: List<Viewer?> get() = dbMapper.mapGet { Viewer.values()[it.viewer] } set(value) = dbMapper.mapSet(value) { manga, viewer -> manga.viewer = viewer.ordinal } } class MangaCollectionProxy(override val id: Long): MangaModel { private val collection = MangaCollectionImpl(listOf(id)) override var viewer: Viewer? get() = collection.viewer[0] set(value) { collection.viewer = listOf(value) } }
apache-2.0
753cfb7ee475f2d6295308f270442602
35.388889
72
0.695951
3.626039
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/chatroom/messaging/reading/display/room_event/m_message/message.kt
1
5700
package koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message import javafx.geometry.Insets import javafx.scene.control.MenuItem import javafx.scene.layout.Priority import javafx.scene.text.Text import koma.Server import koma.gui.view.window.chatroom.messaging.reading.display.ViewNode import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.content.* import koma.gui.view.window.chatroom.messaging.reading.display.room_event.util.DatatimeView import koma.koma_app.AppStore import koma.matrix.NotificationResponse import koma.matrix.UserId import koma.matrix.event.room_message.MRoomMessage import koma.matrix.event.room_message.chat.* import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.MainScope import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import link.continuum.desktop.gui.* import link.continuum.desktop.gui.icon.avatar.AvatarView import link.continuum.desktop.gui.message.MessageCellContent import link.continuum.desktop.observable.MutableObservable import mu.KotlinLogging private val logger = KotlinLogging.logger {} @ExperimentalCoroutinesApi class MRoomMessageViewNode( private val store: AppStore ): MessageCellContent<MRoomMessage> { private val scope = MainScope() override val root = StackPane() private val userData = store.userData private var item: MRoomMessage? = null private val timeView = DatatimeView() private val avatarView = AvatarView(userData = userData) private val senderLabel = Text() private val senderId = MutableObservable<UserId>() private val contentBox = HBox(5.0) private var content: ViewNode? = null companion object { private val pad2 = Insets(2.0) } init { with(root) { padding = pad2 hbox(4.0) { minWidth = 1.0 prefWidth = 1.0 background = whiteBackGround padding = pad2 add(avatarView.root) vbox { spacing = 2.0 HBox.setHgrow(this, Priority.ALWAYS) hbox(spacing = 10.0) { HBox.setHgrow(this, Priority.ALWAYS) add(senderLabel) add(timeView.root) } add(contentBox) } } } senderId.flow() .flatMapLatest { store.userData.getNameUpdates(it) }.onEach { senderLabel.text = it }.launchIn(scope) } override fun update(message: MRoomMessage, server: Server) { item = message releaseContentNode() senderId.set(value = message.sender) timeView.updateTime(message.origin_server_ts) avatarView.updateUser(message.sender, server) senderLabel.fill = userData.getUserColor(message.sender) val c = getContentNode(message, server) content = c contentBox.children.apply { clear() add(c.node) } } fun update(message: NotificationResponse.Event, server: Server, msg: M_Message) { item = null releaseContentNode() senderId.set(value = message.sender) timeView.updateTime(message.origin_server_ts) avatarView.updateUser(message.sender, server) senderLabel.fill = userData.getUserColor(message.sender) val c = getContentNode(msg, server, message.sender) content = c contentBox.children.apply { clear() add(c.node) } } private val copyTextMenuItem = MenuItem("Copy text").apply { action { copyText() } } override fun menuItems(): List<MenuItem> { return (content?.menuItems?: listOf()) + copyTextMenuItem } fun copyText() { item?.content?.body?.let { clipboardPutString(it) } } private fun getContentNode(message: MRoomMessage, server: Server): ViewNode { val content = message.content val sender = message.sender return getContentNode(content, server, sender) } private fun getContentNode(content: M_Message?, server: Server, sender: UserId): ViewNode { return when(content) { is TextMessage -> store.uiPools.msgText.take().apply { update(content, server) } is NoticeMessage -> store.uiPools.msgNotice.take().apply{ update(content, server) } is EmoteMessage -> store.uiPools.msgEmote.take().apply{ update(content, sender, server) } is ImageMessage -> store.uiPools.msgImage.take().apply{ update(content, server) } is FileMessage -> MFileViewNode(content, server) else ->store.uiPools.msgText.take().apply { updatePlainText(content?.body.toString(), server) } } } private fun releaseContentNode() { val c = content?: return when (c) { is MEmoteViewNode -> store.uiPools.msgEmote.pushBack(c) is MNoticeViewNode -> store.uiPools.msgNotice.pushBack(c) is MTextViewNode -> store.uiPools.msgText.pushBack(c) is MImageViewNode -> store.uiPools.msgImage.pushBack(c) is MFileViewNode -> {} else -> error("Unexpected node $c") } } override fun toString(): String { val body=item?.content?.body return "MessageCell(time=${timeView.root}, body=$body)" } }
gpl-3.0
e3b95c86fb16682feb5fb9fb1e310617
34.625
95
0.631754
4.381245
false
false
false
false
npryce/snodge
common/src/main/com/natpryce/snodge/json/JsonMutagens.kt
1
3566
package com.natpryce.snodge.json import com.natpryce.jsonk.JsonArray import com.natpryce.jsonk.JsonBoolean import com.natpryce.jsonk.JsonElement import com.natpryce.jsonk.JsonNull import com.natpryce.jsonk.JsonNumber import com.natpryce.jsonk.JsonObject import com.natpryce.jsonk.JsonString import com.natpryce.jsonk.append import com.natpryce.jsonk.remove import com.natpryce.jsonk.removeProperty import com.natpryce.jsonk.replace import com.natpryce.jsonk.withProperty import com.natpryce.snodge.Mutagen import com.natpryce.snodge.combine import com.natpryce.snodge.filtered import com.natpryce.snodge.plus import com.natpryce.snodge.reflect.troublesomeClasses fun addArrayElement(newElement: JsonElement) = JsonMutagen { _, elementToMutate: JsonArray -> sequenceOf(lazy { elementToMutate.append(newElement) }) } fun addObjectProperty(newElement: JsonElement) = JsonMutagen { _, elementToMutate: JsonObject -> sequenceOf(lazy { elementToMutate.withProperty((elementToMutate.newProperty("x") to newElement)) }) } private fun JsonObject.newProperty(basename: String) = (sequenceOf(basename) + generateSequence(1, { it + 1 }).map { i -> "${basename}_$i" }) .filterNot { it in this } .first() fun removeJsonObjectProperty() = JsonMutagen { _, elementToMutate: JsonObject -> elementToMutate.keys.asSequence().map { key -> lazy { elementToMutate.removeProperty(key) } } } fun removeJsonArrayElement() = JsonMutagen { _, elementToMutate: JsonArray -> elementToMutate.indices.asSequence().map { i -> lazy { elementToMutate.remove(i) } } } fun removeJsonElement() = removeJsonObjectProperty() + removeJsonArrayElement() fun replaceJsonObjectProperty(replacement: JsonElement) = JsonMutagen { _, elementToMutate: JsonObject -> elementToMutate.keys.asSequence().map { key -> lazy { elementToMutate.withProperty(key to replacement) } } } fun replaceJsonArrayElement(replacement: JsonElement) = JsonMutagen { _, elementToMutate: JsonArray -> elementToMutate.indices.asSequence().map { i -> lazy { elementToMutate.replace(i, replacement) } } } fun replaceJsonElement(replacement: JsonElement) = replaceJsonObjectProperty(replacement) + replaceJsonArrayElement(replacement) fun reorderObjectProperties() = JsonMutagen { random, elementToMutate: JsonObject -> sequenceOf(lazy { JsonObject(elementToMutate.properties.toList().shuffled(random)) }) } fun reflectionMutagens(): Mutagen<JsonElement> = troublesomeClasses() .map { replaceJsonElement(JsonString(it)).filtered { it is JsonString } } .let { combine(it) } private val exampleElements = listOf( JsonNull, JsonBoolean(true), JsonBoolean(false), JsonNumber(99), JsonNumber(-99), JsonNumber(0.0), JsonNumber(1.0), JsonNumber(-1.0), JsonString("a string"), JsonArray(), JsonObject()) /** * @return Applies a default set of JSON mutations */ fun defaultJsonMutagens() = combine( combine(exampleElements.map { exampleElement -> combine( replaceJsonElement(exampleElement), addArrayElement(exampleElement), addObjectProperty(exampleElement) ) }), removeJsonElement(), reorderObjectProperties(), reflectionMutagens()) @Deprecated( message="renamed to defaultJsonMutagens", replaceWith = ReplaceWith("defaultJsonMutagens()", "defaultJsonMutagens")) fun allJsonMutagens() = defaultJsonMutagens()
apache-2.0
a58278bd8be430e1cd12041f196875e9
30.280702
105
0.717611
4.165888
false
false
false
false
hazuki0x0/YuzuBrowser
module/favicon/src/main/java/jp/hazuki/yuzubrowser/favicon/FaviconCacheIndex.kt
1
4228
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.favicon import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import java.io.File internal class FaviconCacheIndex(context: Context, dir: String) { private val mOpenHelper: MyOpenHelper init { val name = File(context.getDir(dir, Context.MODE_PRIVATE), DB_NAME).absolutePath mOpenHelper = MyOpenHelper.getInstance(context, name) } fun add(url: String, hash: Long) { val db = mOpenHelper.writableDatabase db.query(TABLE_NAME, arrayOf(COLUMN_ID, COLUMN_HASH), "$COLUMN_URL = ?", arrayOf(url), null, null, null, "1").use { c -> if (c.moveToFirst()) { if (hash != c.getLong(1)) { val values = ContentValues() values.put(COLUMN_HASH, hash) db.update(TABLE_NAME, values, COLUMN_ID + " = " + c.getLong(0), null) } } else { val values = ContentValues() values.put(COLUMN_URL, url) values.put(COLUMN_HASH, hash) db.insert(TABLE_NAME, null, values) } return } } fun remove(hash: Long) { val db = mOpenHelper.writableDatabase db.delete(TABLE_NAME, "$COLUMN_HASH = ?", arrayOf(java.lang.Long.toString(hash))) } operator fun get(url: String): Result { val db = mOpenHelper.readableDatabase return db.query(TABLE_NAME, arrayOf(COLUMN_HASH), "$COLUMN_URL = ?", arrayOf(url), null, null, null, "1").use { c -> if (c.moveToFirst()) { Result(true, c.getLong(0)) } else { Result(false, 0) } } } fun clear() { val db = mOpenHelper.writableDatabase db.delete(TABLE_NAME, null, null) } fun close() { mOpenHelper.close() } internal class Result(val exists: Boolean, val hash: Long) private class MyOpenHelper internal constructor(context: Context, name: String) : SQLiteOpenHelper(context, name, null, DB_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.beginTransaction() try { db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY" + ", " + COLUMN_URL + " TEXT NOT NULL UNIQUE" + ", " + COLUMN_HASH + " INTEGER" + ")") db.execSQL("CREATE UNIQUE INDEX url_index ON $TABLE_NAME($COLUMN_URL)") db.setTransactionSuccessful() } finally { db.endTransaction() } } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME") onCreate(db) } companion object { private var mOpenHelper: MyOpenHelper? = null fun getInstance(context: Context, name: String): MyOpenHelper { if (mOpenHelper == null) { mOpenHelper = MyOpenHelper(context, name) } return mOpenHelper!! } } } companion object { private const val DB_NAME = "indexTable" private const val DB_VERSION = 1 private const val TABLE_NAME = "hashTable" private const val COLUMN_ID = "_id" private const val COLUMN_URL = "url" private const val COLUMN_HASH = "hash" } }
apache-2.0
3b2798402b33cdf8d0959d858d93f939
33.373984
137
0.576159
4.399584
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/util/android/SimpleItemDecoration.kt
1
1148
package net.ketc.numeri.util.android import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View class SimpleItemDecoration(context: Context) : RecyclerView.ItemDecoration() { val divider: Drawable init { val attr: TypedArray = context.obtainStyledAttributes(arrayOf(android.R.attr.listDivider).toIntArray()) divider = attr.getDrawable(0) attr.recycle() } override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { super.onDraw(c, parent, state) val left = parent.paddingLeft val right = parent.width - parent.paddingRight for (i in 0..parent.childCount - 1) { val view: View = parent.getChildAt(i) val params = view.layoutParams as RecyclerView.LayoutParams val top = view.bottom + params.bottomMargin val bottom = top + divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(c) } } }
mit
f72e345cec30d473fdc156e688c441f7
33.818182
111
0.686411
4.484375
false
false
false
false
Litote/kmongo
kmongo-serialization/src/test/kotlin/Issue281Projection.kt
1
2779
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.issues import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import org.junit.Ignore import org.junit.Test import org.litote.kmongo.AllCategoriesKMongoBaseTest import org.litote.kmongo.projection import org.litote.kmongo.withDocumentClass import kotlin.test.assertEquals @Serializable data class MyDocumentClass( val identifiers: List<@Serializable(with = IdentifierSerializer::class) Identifier>, //... more fields, therefore the projection function makes sense ) data class Identifier(val namespace: String) object IdentifierSerializer : KSerializer<Identifier> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Identifier", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Identifier) { encoder.encodeString(value.namespace) } override fun deserialize(decoder: Decoder): Identifier { val string = decoder.decodeString() return Identifier(string) } } @Serializable data class MyDocumentClassProjection( val identifiers: List<@Serializable(with = IdentifierSerializer::class) Identifier>, ) /** * */ class Issue281Projection : AllCategoriesKMongoBaseTest<MyDocumentClass>() { @Test @Ignore fun `test projection`() { val c = MyDocumentClass(listOf(Identifier("namespace"))) col.insertOne(c) val p = col.projection(MyDocumentClass::identifiers) assertEquals("namespace", p.first()?.first()?.namespace) } @Test fun `test projection with custom class`() { val c = MyDocumentClass(listOf(Identifier("namespace"))) col.insertOne(c) val p = col.withDocumentClass<MyDocumentClassProjection>() .find() .projection(MyDocumentClass::identifiers) .toList() assertEquals("namespace", p.first().identifiers.first().namespace) } }
apache-2.0
96ae670d6e2c7f8f97411f79253ec1e6
32.493976
109
0.744512
4.742321
false
true
false
false
osfans/trime
app/src/main/java/com/osfans/trime/data/db/DatabaseDao.kt
1
1552
package com.osfans.trime.data.db import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update @Dao interface DatabaseDao { @Insert suspend fun insert(bean: DatabaseBean): Long @Update suspend fun update(bean: DatabaseBean) @Query("UPDATE ${DatabaseBean.TABLE_NAME} SET text=:newText WHERE id=:id") suspend fun updateText(id: Int, newText: String) @Query("UPDATE ${DatabaseBean.TABLE_NAME} SET pinned=:pinned WHERE id=:id") suspend fun updatePinned(id: Int, pinned: Boolean) @Delete suspend fun delete(bean: DatabaseBean) @Query("DELETE FROM ${DatabaseBean.TABLE_NAME} WHERE text=:text") suspend fun delete(text: String) @Query("DELETE FROM ${DatabaseBean.TABLE_NAME} WHERE id=:id") suspend fun delete(id: Int) @Delete suspend fun delete(beans: List<DatabaseBean>) @Query("DELETE FROM ${DatabaseBean.TABLE_NAME}") suspend fun deleteAll() @Query("DELETE FROM ${DatabaseBean.TABLE_NAME} WHERE NOT pinned") suspend fun deleteAllUnpinned() @Query("SELECT * FROM ${DatabaseBean.TABLE_NAME}") suspend fun getAll(): List<DatabaseBean> @Query("SELECT * FROM ${DatabaseBean.TABLE_NAME} WHERE id=:id LIMIT 1") suspend fun get(id: Int): DatabaseBean? @Query("SELECT * FROM ${DatabaseBean.TABLE_NAME} WHERE rowId=:rowId LIMIT 1") suspend fun get(rowId: Long): DatabaseBean? @Query("SELECT COUNT(*) FROM ${DatabaseBean.TABLE_NAME}") suspend fun itemCount(): Int }
gpl-3.0
4b753ba3dd00cd668b998e2b001c9c63
28.846154
81
0.703608
3.889724
false
false
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/database/ExerciseObject.kt
1
1280
package com.sonnyrodriguez.fittrainer.fittrainerbasic.database import android.arch.persistence.room.* import android.os.Parcel import android.os.Parcelable @Entity(tableName = "exercise") data class ExerciseObject(@ColumnInfo(name = "exercise_title") var title: String, @ColumnInfo(name = "exercise_muscle_group") var muscleGroupNumber: Int, @ColumnInfo(name = "exercise_image_list") var imageList: List<String>): Parcelable { @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) var id: Long = 0 constructor(source: Parcel) : this( source.readString(), source.readInt(), source.createStringArrayList() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(title) writeInt(muscleGroupNumber) writeStringList(imageList) } companion object { @JvmField val CREATOR: Parcelable.Creator<ExerciseObject> = object : Parcelable.Creator<ExerciseObject> { override fun createFromParcel(source: Parcel): ExerciseObject = ExerciseObject(source) override fun newArray(size: Int): Array<ExerciseObject?> = arrayOfNulls(size) } } }
apache-2.0
421b6a437b58fbb90e748c25ae445901
36.647059
113
0.667188
4.654545
false
true
false
false
artem-zinnatullin/RxUi
rxui-sample-kotlin/src/main/kotlin/com/artemzin/rxui/sample/kotlin/MainActivity.kt
1
782
package com.artemzin.rxui.sample.kotlin import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.ViewGroup import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers class MainActivity : AppCompatActivity() { lateinit var disposable: Disposable override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) val view = MainViewImpl(findViewById(android.R.id.content) as ViewGroup) val presenter = MainPresenter(authService = AuthService.Impl(), ioScheduler = Schedulers.io()) disposable = presenter.bind(view) } override fun onDestroy() { disposable.dispose() super.onDestroy() } }
mit
96a806f49469b4a148fde0e7fdec6f2f
27.962963
102
0.732737
4.682635
false
false
false
false
RocketChat/Rocket.Chat.Android
suggestions/src/main/java/chat/rocket/android/suggestions/strategy/trie/data/TrieNode.kt
2
1099
package chat.rocket.android.suggestions.strategy.trie.data import chat.rocket.android.suggestions.model.SuggestionModel internal class TrieNode( internal var data: Char, internal var parent: TrieNode? = null, internal var isLeaf: Boolean = false, internal var item: SuggestionModel? = null ) { val children = hashMapOf<Char, TrieNode>() fun getChild(c: Char): TrieNode? { children.forEach { if (it.key == c) return it.value } return null } fun getWords(): List<String> { val list = arrayListOf<String>() if (isLeaf) { list.add(toString()) } children.forEach { node -> node.value.let { list.addAll(it.getWords()) } } return list } fun getItems(): Sequence<SuggestionModel> = sequence { if (isLeaf) { yield(item!!) } children.forEach { node -> yieldAll(node.value.getItems()) } } override fun toString(): String = if (parent == null) "" else "${parent.toString()}$data" }
mit
ee4fa2d7d2f9d47b6f98c5765d76781a
23.977273
93
0.573248
4.276265
false
false
false
false
interedition/collatex
collatex-core/src/main/java/eu/interedition/collatex/dekker/TranspositionDetector.kt
1
7801
/* * Copyright (c) 2015 The Interedition Development Group. * * This file is part of CollateX. * * CollateX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.collatex.dekker import eu.interedition.collatex.VariantGraph import eu.interedition.collatex.simple.SimpleToken import eu.interedition.collatex.util.VariantGraphRanking import java.util.* import kotlin.Comparator import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.collections.LinkedHashMap import kotlin.math.abs /** * @author Ronald Haentjens Dekker */ class TranspositionDetector { fun detect(phraseMatchesWitnessOrder: List<List<Match>>?, base: VariantGraph): MutableList<List<Match>> { // if there are no phrase matches it is not possible // to detect transpositions, return an empty list if (phraseMatchesWitnessOrder!!.isEmpty()) { return ArrayList() } /* * We order the phrase matches in the topological order * of the graph (called rank). When the rank is equal * for two phrase matches, the witness order is used * to differentiate. */ val ranking = rankTheGraph(phraseMatchesWitnessOrder, base) val comp = Comparator { pm1:List<Match>, pm2: List<Match> -> val rank1 = ranking.apply(pm1[0].vertex) val rank2 = ranking.apply(pm2[0].vertex) val difference = rank1 - rank2 when { difference != 0 -> difference else -> { val index1 = phraseMatchesWitnessOrder.indexOf(pm1) val index2 = phraseMatchesWitnessOrder.indexOf(pm2) index1 - index2 } } } val phraseMatchesGraphOrder: List<List<Match>> = phraseMatchesWitnessOrder.sortedWith(comp) // Map 1 val phraseMatchToGraphIndex: MutableMap<List<Match>, Int> = HashMap() for (i in phraseMatchesGraphOrder.indices) { phraseMatchToGraphIndex[phraseMatchesGraphOrder[i]] = i } /* * We calculate the index for all the phrase matches * First in witness order, then in graph order */ val phraseMatchesWitnessIndex: MutableList<Int?> = ArrayList() val phraseMatchesGraphIndex: MutableList<Int?> = ArrayList() for (i in phraseMatchesWitnessOrder.indices) { phraseMatchesWitnessIndex.add(i) } for (phraseMatch in phraseMatchesWitnessOrder) { phraseMatchesGraphIndex.add(phraseMatchToGraphIndex[phraseMatch]) } // DEBUG // println(phraseMatchesGraphIndex) // println(phraseMatchesWitnessIndex) /* * Initialize result variables */ val nonTransposedPhraseMatches: MutableList<List<Match>> = ArrayList(phraseMatchesWitnessOrder) val transpositions: MutableList<List<Match>> = ArrayList() /* * loop here until the maximum distance == 0 */ while (true) { // Map 2 val phraseMatchToDistanceMap: MutableMap<List<Match>, Int> = LinkedHashMap() for (i in nonTransposedPhraseMatches.indices) { val graphIndex = phraseMatchesGraphIndex[i] val witnessIndex = phraseMatchesWitnessIndex[i] val distance = abs(graphIndex!! - witnessIndex!!) val phraseMatch = nonTransposedPhraseMatches[i] phraseMatchToDistanceMap[phraseMatch] = distance } val distanceList: List<Int> = ArrayList(phraseMatchToDistanceMap.values) // DEBUG // println(distanceList) if (distanceList.isEmpty() || Collections.max(distanceList) == 0) { break } // sort phrase matches on distance, size // TODO: order by 3) graph rank? // TODO: I have not yet found evidence/a use case that // TODO: indicates that it is needed. val comp2 = Comparator { pm1: List<Match>, pm2: List<Match> -> // first order by distance val distance1 = phraseMatchToDistanceMap[pm1]!! val distance2 = phraseMatchToDistanceMap[pm2]!! val difference = distance2 - distance1 when { difference != 0 -> difference else -> determineSize(pm1) - determineSize(pm2) } } val sortedPhraseMatches: MutableList<List<Match>> = ArrayList(nonTransposedPhraseMatches.sortedWith(comp2)) val transposedPhrase: List<Match> = sortedPhraseMatches.removeAt(0) val transposedIndex = phraseMatchToGraphIndex[transposedPhrase] val graphIndex = phraseMatchesGraphIndex.indexOf(transposedIndex) val transposedWithIndex = phraseMatchesWitnessIndex[graphIndex] val linkedTransposedPhrase = phraseMatchesGraphOrder[transposedWithIndex!!] addTransposition(phraseMatchToGraphIndex, phraseMatchesWitnessIndex, phraseMatchesGraphIndex, nonTransposedPhraseMatches, transpositions, transposedPhrase) val distance = phraseMatchToDistanceMap[transposedPhrase] if (distance == phraseMatchToDistanceMap[linkedTransposedPhrase] && distance!! > 1) { addTransposition(phraseMatchToGraphIndex, phraseMatchesWitnessIndex, phraseMatchesGraphIndex, nonTransposedPhraseMatches, transpositions, linkedTransposedPhrase) } } return transpositions } private fun addTransposition(phraseMatchToIndex: Map<List<Match>, Int>, phraseWitnessRanks: MutableList<Int?>, phraseGraphRanks: MutableList<Int?>, nonTransposedPhraseMatches: MutableList<List<Match>>, transpositions: MutableList<List<Match>>, transposedPhrase: List<Match>) { val indexToRemove = phraseMatchToIndex[transposedPhrase] nonTransposedPhraseMatches.remove(transposedPhrase) transpositions.add(transposedPhrase) phraseGraphRanks.remove(indexToRemove) phraseWitnessRanks.remove(indexToRemove) } private fun rankTheGraph(phraseMatches: List<List<Match>>, base: VariantGraph): VariantGraphRanking { // rank the variant graph val matchedVertices: MutableSet<VariantGraph.Vertex> = HashSet() for (phraseMatch in phraseMatches) { matchedVertices.add(phraseMatch[0].vertex) } return VariantGraphRanking.ofOnlyCertainVertices(base, matchedVertices) } /* * in case of an a, b / b, a transposition we have to determine whether a or b * stays put. the phrase with the most character stays still if the tokens are * not simple tokens the phrase with the most tokens stays put */ private fun determineSize(t: List<Match>): Int { val firstMatch = t[0] if (firstMatch.token !is SimpleToken) { return t.size } var charLength = 0 for (m in t) { val token = m.token as SimpleToken charLength += token.normalized.length } return charLength } }
gpl-3.0
42b05dd34820afe16feee9eb03cf60d4
42.344444
280
0.654403
4.570006
false
false
false
false
tonyofrancis/Fetch
fetch2core/src/main/java/com/tonyodev/fetch2core/FileResource.kt
1
3357
package com.tonyodev.fetch2core import android.os.Parcel import android.os.Parcelable import java.io.Serializable /** File Resource used by Fetch File Server to server content data. * */ class FileResource : Parcelable, Serializable { /** Unique File Resource Identifier. * Clients can request data from the server using the file resource id * example Url: fetchlocal://127.0.0.1:7428/84562 * */ var id: Long = 0L /** Content Length */ var length: Long = 0L /** The File Path. Can be a file or uri. */ var file: String = "" /** Unique Short name of the File Resource. * Clients can request data from the server using the file resource name * example Url: fetchlocal://127.0.0.1/:7428/text.txt * */ var name: String = "" /** * Set or get the extras for this file resource. Use this to * save and get custom key/value data for the file resource. * */ var extras: Extras = Extras.emptyExtras set(value) { field = value.copy() } /** The File Resource md5 checksum string. If Empty Fetch File Server will generate the md5 * checksum when added to a file server instance. * This is sent in the server response to the client.*/ var md5: String = "" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FileResource if (id != other.id) return false if (length != other.length) return false if (file != other.file) return false if (name != other.name) return false if (extras != other.extras) return false if (md5 != other.md5) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + length.hashCode() result = 31 * result + file.hashCode() result = 31 * result + name.hashCode() result = 31 * result + extras.hashCode() result = 31 * result + md5.hashCode() return result } override fun toString(): String { return "FileResource(id=$id, length=$length, file='$file'," + " name='$name', extras='$extras', md5='$md5')" } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeLong(id) dest.writeString(name) dest.writeLong(length) dest.writeString(file) dest.writeSerializable(HashMap(extras.map)) dest.writeString(md5) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<FileResource> { @Suppress("UNCHECKED_CAST") override fun createFromParcel(source: Parcel): FileResource { val fileResource = FileResource() fileResource.id = source.readLong() fileResource.name = source.readString() ?: "" fileResource.length = source.readLong() fileResource.file = source.readString() ?: "" fileResource.extras = Extras(source.readSerializable() as HashMap<String, String>) fileResource.md5 = source.readString() ?: "" return fileResource } override fun newArray(size: Int): Array<FileResource?> { return arrayOfNulls(size) } } }
apache-2.0
ae67d93e212fe69bc1cf468ba2ef1697
31.601942
95
0.610366
4.464096
false
false
false
false
AlexanderDashkov/hpcourse
csc/2016/vsv_1/src/handlers/ListRequestHandler.kt
3
1801
package handlers import communication.CommunicationProtos class ListRequestHandler(private val myReceivedTasks: MutableMap<Int, CommunicationProtos.ServerRequest>, private val myCompletedTasks: MutableMap<Int, Long>) { fun handle(request: CommunicationProtos.ListTasks): CommunicationProtos.ListTasksResponse { return listTask(myReceivedTasks, myCompletedTasks) } private fun listTask(receivedTasks: MutableMap<Int, CommunicationProtos.ServerRequest>, completedTasks: MutableMap<Int, Long>): CommunicationProtos.ListTasksResponse { val tasksResponseBuilder = CommunicationProtos.ListTasksResponse.newBuilder(); synchronized(receivedTasks, { println("List command blocked received task list") for ((id, request) in receivedTasks) { val result = if (completedTasks.containsKey(id)) completedTasks.get(id) else null tasksResponseBuilder.addTasks(getTaskDescription(id, request, result)) } }) println("List command released received task list lock") tasksResponseBuilder.setStatus(CommunicationProtos.Status.OK) return tasksResponseBuilder.build() } private fun getTaskDescription(id: Int, req: CommunicationProtos.ServerRequest, result: Long?): CommunicationProtos.ListTasksResponse.TaskDescription { val description = CommunicationProtos.ListTasksResponse.TaskDescription.newBuilder() .setClientId(req.clientId) .setTaskId(id) .setTask(req.submit.task) if (result != null) { description.result = result } return description.build() } }
gpl-2.0
64e808da8e3635dce3909190b226201b
44.025
106
0.661855
5.558642
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/lock/RPKLockServiceImpl.kt
1
8006
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.locks.bukkit.lock import com.rpkit.core.bukkit.extension.withDisplayName import com.rpkit.core.bukkit.extension.withLore import com.rpkit.core.bukkit.extension.withoutLoreMatching import com.rpkit.core.location.RPKBlockLocation import com.rpkit.core.service.Services import com.rpkit.locks.bukkit.RPKLocksBukkit import com.rpkit.locks.bukkit.database.table.RPKLockedBlockTable import com.rpkit.locks.bukkit.database.table.RPKPlayerGettingKeyTable import com.rpkit.locks.bukkit.database.table.RPKPlayerUnclaimingTable import com.rpkit.locks.bukkit.event.lock.RPKBukkitBlockLockEvent import com.rpkit.locks.bukkit.event.lock.RPKBukkitBlockUnlockEvent import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import org.bukkit.Material import org.bukkit.inventory.ItemStack import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.concurrent.CopyOnWriteArrayList import java.util.logging.Level class RPKLockServiceImpl(override val plugin: RPKLocksBukkit) : RPKLockService { override val lockItem: ItemStack = plugin.config.getItemStack("lock-item") ?: ItemStack(Material.IRON_INGOT).withDisplayName("Lock") val keyItem: ItemStack = plugin.config.getItemStack("key-item") ?: ItemStack(Material.IRON_INGOT).withDisplayName("Key") private data class LockedBlockKey( val world: String, val x: Int, val y: Int, val z: Int ) private val lockedBlocks = CopyOnWriteArrayList<LockedBlockKey>() private val unclaiming = CopyOnWriteArrayList<Int>() private val gettingKey = CopyOnWriteArrayList<Int>() private fun RPKBlockLocation.toLockedBlockKey() = LockedBlockKey(world, x, y, z) override fun isLocked(block: RPKBlockLocation): Boolean { return lockedBlocks.contains(block.toLockedBlockKey()) } override fun setLocked(block: RPKBlockLocation, locked: Boolean): CompletableFuture<Void> = runAsync { val lockedBlockTable = plugin.database.getTable(RPKLockedBlockTable::class.java) if (locked) { val event = RPKBukkitBlockLockEvent(block, true) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return@runAsync val lockedBlock = lockedBlockTable[event.block].join() if (lockedBlock == null) { lockedBlockTable.insert(RPKLockedBlock(block = event.block)).join() lockedBlocks.add(block.toLockedBlockKey()) } } else { val event = RPKBukkitBlockUnlockEvent(block, true) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return@runAsync val lockedBlock = lockedBlockTable[event.block].join() if (lockedBlock != null) { lockedBlockTable.delete(lockedBlock).join() lockedBlocks.remove(block.toLockedBlockKey()) } } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to set locked", exception) throw exception } private fun loadLockedBlocks() { plugin.database.getTable(RPKLockedBlockTable::class.java).getAll().thenAccept { blocks -> lockedBlocks.addAll(blocks.map { it.block.toLockedBlockKey() }) plugin.logger.info("Loaded locked blocks") } } override fun isClaiming(minecraftProfile: RPKMinecraftProfile): Boolean { val bukkitOfflinePlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID) val bukkitPlayer = bukkitOfflinePlayer.player ?: return false val item = bukkitPlayer.inventory.itemInMainHand val lockService = Services[RPKLockService::class.java] ?: return false if (item.isSimilar(lockService.lockItem)) { return true } return false } override fun isUnclaiming(minecraftProfile: RPKMinecraftProfile): Boolean { return minecraftProfile.id?.value?.let { unclaiming.contains(it) } ?: false } override fun setUnclaiming(minecraftProfile: RPKMinecraftProfile, unclaiming: Boolean): CompletableFuture<Void> { return runAsync { val playerUnclaimingTable = plugin.database.getTable(RPKPlayerUnclaimingTable::class.java) if (unclaiming) { val playerUnclaiming = playerUnclaimingTable[minecraftProfile].join() if (playerUnclaiming == null) { playerUnclaimingTable.insert(RPKPlayerUnclaiming(minecraftProfile = minecraftProfile)).join() minecraftProfile.id?.value?.let { this.unclaiming.add(it) } } } else { val playerUnclaiming = playerUnclaimingTable[minecraftProfile].join() if (playerUnclaiming != null) { playerUnclaimingTable.delete(playerUnclaiming).join() minecraftProfile.id?.value?.let { this.unclaiming.remove(it) } } } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to set unclaiming", exception) throw exception } } private fun loadUnclaiming() { plugin.database.getTable(RPKPlayerUnclaimingTable::class.java).getAll().thenAccept { unclaimingPlayers -> unclaiming.addAll(unclaimingPlayers.mapNotNull { it.minecraftProfile.id?.value }) plugin.logger.info("Loaded unclaiming players") } } override fun isGettingKey(minecraftProfile: RPKMinecraftProfile): Boolean { return minecraftProfile.id?.value?.let { gettingKey.contains(it) } ?: false } override fun setGettingKey(minecraftProfile: RPKMinecraftProfile, gettingKey: Boolean): CompletableFuture<Void> = runAsync { val playerGettingKeyTable = plugin.database.getTable(RPKPlayerGettingKeyTable::class.java) if (gettingKey) { val playerGettingKey = playerGettingKeyTable[minecraftProfile].join() if (playerGettingKey == null) { playerGettingKeyTable.insert(RPKPlayerGettingKey(minecraftProfile = minecraftProfile)).join() minecraftProfile.id?.value?.let { this.gettingKey.add(it) } } } else { val playerGettingKey = playerGettingKeyTable[minecraftProfile].join() if (playerGettingKey != null) { playerGettingKeyTable.delete(playerGettingKey).join() minecraftProfile.id?.value?.let { this.gettingKey.remove(it) } } } } private fun loadGettingKey() { plugin.database.getTable(RPKPlayerGettingKeyTable::class.java).getAll().thenAccept { playersGettingKey -> gettingKey.addAll(playersGettingKey.mapNotNull { it.minecraftProfile.id?.value}) plugin.logger.info("Loaded players getting key") } } override fun getKeyFor(block: RPKBlockLocation): ItemStack { return ItemStack(keyItem) .withLore(listOf("${block.world},${block.x},${block.y},${block.z}")) } override fun isKey(item: ItemStack): Boolean { val key = ItemStack(item) .withoutLoreMatching("\\w+,-?\\d+,-?\\d+,-?\\d+") return key.isSimilar(keyItem) } fun loadData() { loadLockedBlocks() loadGettingKey() loadUnclaiming() } }
apache-2.0
5f06272083bdf23b95e31889cf52b57a
42.281081
128
0.680365
4.585338
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/data/cache/CacheApi.kt
1
2266
/* * MIT License * * Copyright (c) 2017 YangBin * * 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 tech.summerly.quiet.data.cache import tech.summerly.quiet.AppContext import tech.summerly.quiet.module.common.bean.MusicType import tech.summerly.quiet.data.local.MusicDataBase import tech.summerly.quiet.data.local.entity.MusicUrl /** * author : Summer * date : 2017/10/18 */ object CacheApi { private val cacheDao by lazy { MusicDataBase.getInstance(AppContext.instance).cacheDao() } fun getMusicUrl(id: Long, type: MusicType): String? { val musicUrl = cacheDao.queryMusicUrl(id, type) ?: return null //网易云音乐播放链接缓存设置为10分钟失效 if (musicUrl.type == MusicType.NETEASE && System.currentTimeMillis() - musicUrl.timeUpdate > 1000 * 60 * 10) { return null } return musicUrl.url } fun cacheMusicUrl(id: Long, type: MusicType, url: String?) { if (url == null) { return } cacheDao.insertMusicUrl(MusicUrl( id = id, type = type, url = url, timeUpdate = System.currentTimeMillis() )) } }
gpl-2.0
1db0221698d91714da23ac753c5750d9
34.983871
84
0.684753
4.191729
false
false
false
false
thinkofdeath/alex
src/main/kotlin/uk/thinkofdeath/minecraft/alex/db/Blocks.kt
1
2682
/* * Copyright 2015 Matthew Collins * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.thinkofdeath.minecraft.alex.db import org.bukkit.DyeColor import org.bukkit.Material import org.bukkit.material.MaterialData import org.bukkit.material.Wool inline fun DB<org.bukkit.material.MaterialData>.reg(m: Material, d: Byte = 0, body: DB.RegBody.() -> Unit) { reg(MaterialData(m, d), body) } val blocks = registry<MaterialData> { // Defaults based on bukkit names for (m in Material.values()) { if (m.isBlock()) { val mat = MaterialData(m, 0) strToVal[m.name().toLowerCase().replace("_", "")] = mat valToStr[mat] = m.name().toNormalCase() } } reg(Wool(DyeColor.WHITE)) { +"Cloth" +"White Cloth" +"White Wool" +"Wool" } reg(Wool(DyeColor.ORANGE)) { +"Orange Cloth" +"Orange Wool" } reg(Wool(DyeColor.MAGENTA)) { +"Magenta Cloth" +"Magenta Wool" } reg(Wool(DyeColor.LIGHT_BLUE)) { +"Light Blue Cloth" +"Light Blue Wool" } reg(Wool(DyeColor.YELLOW)) { +"Yellow Cloth" +"Yellow Wool" } reg(Wool(DyeColor.LIME)) { +"Lime Cloth" +"Lime Wool" } reg(Wool(DyeColor.PINK)) { +"Pink Cloth" +"Pink Wool" } reg(Wool(DyeColor.GRAY)) { +"Grey Cloth" +"Gray Cloth" +"Grey Wool" +"Gray Wool" } reg(Wool(DyeColor.SILVER)) { +"Light Grey Wool" +"Light Grey Cloth" +"Silver Wool" +"Silver Cloth" +"Light Gray Cloth" +"Light Gray Wool" } reg(Wool(DyeColor.CYAN)) { +"Cyan Cloth" +"Cyan Wool" } reg(Wool(DyeColor.PURPLE)) { +"Purple Cloth" +"Purple Wool" } reg(Wool(DyeColor.BROWN)) { +"Brown Cloth" +"Brown Wool" } reg(Wool(DyeColor.GREEN)) { +"Green Cloth" +"Green Wool" } reg(Wool(DyeColor.RED)) { +"Red Cloth" +"Red Wool" } reg(Wool(DyeColor.BLACK)) { +"Black Cloth" +"Black Wool" } }
apache-2.0
3cac98e834e5bd3758c3f14bda9ba2fe
23.833333
108
0.569351
3.533597
false
false
false
false
t-yoshi/peca-android
common/src/main/java/org/peercast/core/common/PeerCastConfig.kt
1
1648
package org.peercast.core.common import kotlinx.coroutines.flow.SharedFlow abstract class PeerCastConfig { data class IniKey( val section: String, val key: String, val sectionIndex: Int = 0, ) data class OnChangeEvent( val key: IniKey, val value: String ) protected abstract val iniMap : Map<IniKey, String> abstract val changeEvent: SharedFlow<OnChangeEvent> inline operator fun <reified T> get(key: IniKey): T? { val v = getString(key) return when (T::class) { String::class -> v as T? Int::class -> v?.toIntOrNull() as T? Long::class -> v?.toLongOrNull() as T? Boolean::class -> v?.equals("Yes", true) as T? else -> throw NotImplementedError(T::class.java.name) } } inline operator fun <reified T> get(section: String, sectionIndex: Int, key: String): T? = get( IniKey(section, key, sectionIndex) ) inline operator fun <reified T> get(section: String, key: String): T? = get( IniKey(section, key) ) fun getString(key: IniKey) = iniMap[key] fun getSection(section: String) = iniMap.filter { it.key.section == section }.map { it.key } val sections get() = iniMap.entries.map { it.key.section }.distinct() operator fun contains(key: IniKey) = key in iniMap val port get() = get(KEY_PORT) ?: 7144 val preferredTheme get() = get(KEY_THEME) ?: "system" companion object { val KEY_PORT = IniKey("Server", "serverPort") val KEY_THEME = IniKey("Client", "preferredTheme") } }
gpl-3.0
218b10502b831cf146deb58ca07615a9
25.15873
99
0.599515
3.797235
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/adapter/ChatRoomAdapter.kt
1
1411
package org.miaowo.miaowo.adapter import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.ImageView import org.miaowo.miaowo.API import org.miaowo.miaowo.R import org.miaowo.miaowo.base.ListAdapter import org.miaowo.miaowo.base.ListHolder import org.miaowo.miaowo.data.bean.ChatRoom import org.miaowo.miaowo.handler.ChatHandler import org.miaowo.miaowo.other.BaseListTouchListener import org.miaowo.miaowo.other.setUserIcon /** * 聊天室列表 * Created by luqin on 17-4-7. */ class ChatRoomAdapter: ListAdapter<ChatRoom>( object : ListAdapter.ViewCreator<ChatRoom> { override fun createHolder(parent: ViewGroup, viewType: Int) = ListHolder(R.layout.list_chat, parent) override fun bindView(item: ChatRoom, holder: ListHolder, type: Int) { holder.find<ImageView>(R.id.icon)?.setUserIcon(item.users.firstOrNull { it.uid != API.user.uid }) } override fun setType(item: ChatRoom, position: Int): Int = 0 }) class ChatRoomListener(context: Context, val adapter: ChatRoomAdapter, val handler: ChatHandler): BaseListTouchListener(context) { override fun onClick(view: View?, position: Int): Boolean { val room = adapter.getItem(position) handler.changeRoom(room.roomId, room.users.firstOrNull { it.uid != API.user.uid }?.uid) return true } }
apache-2.0
5b0c5c931889d8f79ae5bfd9c983ce9e
34.948718
130
0.725196
3.880886
false
false
false
false
authzee/kotlin-guice
kotlin-guice/src/test/kotlin/dev/misfitlabs/kotlinguice4/KotlinBinderSpec.kt
1
8326
/* * Copyright (C) 2017 John Leacox * Copyright (C) 2017 Brian van de Boogaard * * 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 dev.misfitlabs.kotlinguice4 import com.google.inject.Guice import com.google.inject.Key import dev.misfitlabs.kotlinguice4.binder.annotatedWith import dev.misfitlabs.kotlinguice4.binder.to import java.util.concurrent.Callable import javax.inject.Inject import javax.inject.Singleton import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeInstanceOf import org.amshove.kluent.shouldEqual import org.amshove.kluent.shouldNotBe import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe /** * @author John Leacox */ object KotlinBinderSpec : Spek({ beforeEachTest { StaticInjectionObj.reset() } describe("KotlinBinder") { describe("#bindScope") { it("binds a custom scope using a scope annotation type parameter") { val scope = TestScope() val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bindScope<TestScoped>(scope) kotlinBinder.bind<A>().to<AImpl>().`in`<TestScoped>() } }) val a = injector.getInstance(A::class.java) a shouldBe injector.getInstance(A::class.java) scope.reset() a shouldNotBe injector.getInstance(A::class.java) } } describe("#bind") { it("binds source using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<A>().to(AImpl::class.java) } }) val a = injector.getInstance(A::class.java) a.get() shouldEqual "Impl of A" } it("binds a complex source using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<Callable<A>>().to(ACallable::class.java) } }) val a = injector.getInstance(key<Callable<A>>()) a.call().get() shouldEqual "Impl of A" } it("binds to a target using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<A>().to<AImpl>() } }) val a = injector.getInstance(A::class.java) a.get() shouldEqual "Impl of A" } it("binds to a complex target using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<Callable<A>>().to<TCallable<A>>() } }) val callable = injector.getInstance(key<Callable<A>>()) callable.call() shouldEqual null } it("binds with an annotation using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<A>().to<B>() kotlinBinder.bind<A>().annotatedWith<Annotated>().to<AImpl>() } }) val a = injector.getInstance(Key.get(A::class.java, Annotated::class.java)) a.get() shouldEqual "Impl of A" } it("binds to a provider using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<A>().toProvider<BProvider>() } }) val a = injector.getInstance(A::class.java) a shouldBeInstanceOf B::class.java } it("binds to a complex provider using a type parameter") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<Iterable<A>>().toProvider<TProvider<List<A>>>() } }) injector.getInstance(key<Iterable<A>>()) } it("binds in a scope") { val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<A>().to<AImpl>().`in`<Singleton>() } }) val a = injector.getInstance(A::class.java) a shouldBe injector.getInstance(A::class.java) } } describe("#bindConstant") { it("binds to a target using a type parameter and annotation") { class ClassWithConstant @Inject constructor(@Annotated val constant: Class<Nothing>) val injector = Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bindConstant().annotatedWith<Annotated>().to<Iterator<*>>() } }) val classWithConstant = injector.getInstance(ClassWithConstant::class.java) classWithConstant.constant shouldEqual Iterator::class.java } } describe("#requestStaticInjection") { it("injects static fields") { Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<String>().toInstance("Statically Injected") kotlinBinder.requestStaticInjection<StaticInjectionObj>() } }) StaticInjectionObj.staticInjectionSite shouldEqual "Statically Injected" } } describe("#getProvider") { it("get a provider for a simple type") { Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<A>().to<AImpl>() val provider = kotlinBinder.getProvider<A>() provider.toString() shouldEqual "Provider<dev.misfitlabs.kotlinguice4.A>" } }) } it("get a provider for an annotated key") { Guice.createInjector(object : KotlinModule() { override fun configure() { kotlinBinder.bind<Callable<A>>().to<TCallable<A>>() val provider = kotlinBinder.getProvider<Callable<A>>() provider.toString() shouldEqual "Provider<java.util.concurrent.Callable<dev.misfitlabs.kotlinguice4.A>>" } }) } } describe("#getMembersInjector") { it("injects member fields") { Guice.createInjector(object : KotlinModule() { override fun configure() { val membersInjector = kotlinBinder.getMembersInjector<AImpl>() membersInjector.toString() shouldEqual "MembersInjector<dev.misfitlabs.kotlinguice4.AImpl>" } }) } } } })
apache-2.0
0ae957b2972addd8bc35edaa918f6829
37.018265
104
0.530267
5.488464
false
true
false
false
carlphilipp/chicago-commutes
android-app/src/googleplay/kotlin/fr/cph/chicago/core/activity/BusBoundActivity.kt
1
9966
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.core.activity import android.annotation.SuppressLint import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.PolylineOptions import fr.cph.chicago.R import fr.cph.chicago.core.App import fr.cph.chicago.core.activity.station.BusStopActivity import fr.cph.chicago.core.adapter.BusBoundAdapter import fr.cph.chicago.core.model.BusPattern import fr.cph.chicago.core.model.BusStop import fr.cph.chicago.databinding.ActivityBusBoundBinding import fr.cph.chicago.service.BusService import fr.cph.chicago.util.GoogleMapUtil import fr.cph.chicago.util.Util import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import org.apache.commons.lang3.StringUtils import timber.log.Timber /** * Activity that represents the bus bound activity * * @author Carl-Philipp Harmant * @version 1 */ class BusBoundActivity : AppCompatActivity() { companion object { private val busService = BusService private val util: Util = Util } private lateinit var mapFragment: SupportMapFragment private lateinit var busRouteId: String private lateinit var busRouteName: String private lateinit var bound: String private lateinit var boundTitle: String private lateinit var adapter: BusBoundAdapter private lateinit var binding: ActivityBusBoundBinding private var busStops: List<BusStop> = listOf() @SuppressLint("CheckResult") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityBusBoundBinding.inflate(layoutInflater) if (!this.isFinishing) { setContentView(binding.root) busRouteId = intent.getStringExtra(getString(R.string.bundle_bus_route_id)) ?: StringUtils.EMPTY busRouteName = intent.getStringExtra(getString(R.string.bundle_bus_route_name)) ?: StringUtils.EMPTY bound = intent.getStringExtra(getString(R.string.bundle_bus_bound)) ?: StringUtils.EMPTY boundTitle = intent.getStringExtra(getString(R.string.bundle_bus_bound_title)) ?: StringUtils.EMPTY mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment adapter = BusBoundAdapter() binding.listView.setOnItemClickListener { _, _, position, _ -> val busStop = adapter.getItem(position) as BusStop val intent = Intent(applicationContext, BusStopActivity::class.java) val extras = with(Bundle()) { putString(getString(R.string.bundle_bus_stop_id), busStop.id.toString()) putString(getString(R.string.bundle_bus_stop_name), busStop.name) putString(getString(R.string.bundle_bus_route_id), busRouteId) putString(getString(R.string.bundle_bus_route_name), busRouteName) putString(getString(R.string.bundle_bus_bound), bound) putString(getString(R.string.bundle_bus_bound_title), boundTitle) putDouble(getString(R.string.bundle_bus_latitude), busStop.position.latitude) putDouble(getString(R.string.bundle_bus_longitude), busStop.position.longitude) this } intent.putExtras(extras) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } binding.listView.adapter = adapter binding.busFilter.addTextChangedListener(object : TextWatcher { private var busStopsFiltered: MutableList<BusStop> = mutableListOf() override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { busStopsFiltered = mutableListOf() } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { busStops .filter { busStop -> StringUtils.containsIgnoreCase(busStop.name, s) } .forEach { busStopsFiltered.add(it) } } override fun afterTextChanged(s: Editable) { adapter.updateBusStops(busStopsFiltered) adapter.notifyDataSetChanged() } }) val toolbar = binding.included.toolbar toolbar.title = "$busRouteId - $boundTitle" toolbar.navigationIcon = ContextCompat.getDrawable(this, R.drawable.ic_arrow_back_white_24dp) toolbar.setOnClickListener { finish() } busService.loadAllBusStopsForRouteBound(busRouteId, bound) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> busStops = result adapter.updateBusStops(result) adapter.notifyDataSetChanged() }, { throwable -> Timber.e(throwable, "Error while getting bus stops for route bound") util.showOopsSomethingWentWrong(binding.listView) }) // Preventing keyboard from moving background when showing up window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) } } public override fun onResume() { super.onResume() mapFragment.getMapAsync { googleMap -> with(googleMap) { moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(GoogleMapUtil.chicago, 7f, 0f, 0f))) uiSettings.isMyLocationButtonEnabled = false uiSettings.isZoomControlsEnabled = false uiSettings.isMapToolbarEnabled = false } busService.loadBusPattern(busRouteId, bound) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> if (result.direction != "error") { val center = result.busStopsPatterns.size / 2 val position = result.busStopsPatterns[center].position if (position.latitude == 0.0 && position.longitude == 0.0) { googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GoogleMapUtil.chicago, 10f)) } else { val latLng = LatLng(position.latitude, position.longitude) googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 7f)) googleMap.animateCamera(CameraUpdateFactory.zoomTo(9f), 500, null) } drawPattern(googleMap, result) } else { util.showSnackBar(binding.bellowLayout, R.string.message_error_could_not_load_path) } }, { throwable -> util.handleConnectOrParserException(throwable, binding.bellowLayout) Timber.e(throwable, "Error while getting bus patterns") }) } } private fun drawPattern(googleMap: GoogleMap, pattern: BusPattern) { val poly = PolylineOptions() .geodesic(true) .color(Color.BLACK) .width(App.instance.lineWidthGoogleMap) .addAll(pattern.busStopsPatterns.map { patternPoint -> LatLng(patternPoint.position.latitude, patternPoint.position.longitude) }) googleMap.addPolyline(poly) } public override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) busRouteId = savedInstanceState.getString(getString(R.string.bundle_bus_route_id)) ?: StringUtils.EMPTY busRouteName = savedInstanceState.getString(getString(R.string.bundle_bus_route_name)) ?: StringUtils.EMPTY bound = savedInstanceState.getString(getString(R.string.bundle_bus_bound)) ?: StringUtils.EMPTY boundTitle = savedInstanceState.getString(getString(R.string.bundle_bus_bound_title)) ?: StringUtils.EMPTY } public override fun onSaveInstanceState(savedInstanceState: Bundle) { if (::busRouteId.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_route_id), busRouteId) if (::busRouteName.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_route_name), busRouteName) if (::bound.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_bound), bound) if (::boundTitle.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_bound_title), boundTitle) super.onSaveInstanceState(savedInstanceState) } }
apache-2.0
3fbd4a5634019ebc3bdaf700d65cf328
46.232227
141
0.650612
5.035877
false
false
false
false
cjkent/kotlin-beans
src/main/kotlin/io/github/cjkent/kotlinbeans/Beans.kt
1
8579
package io.github.cjkent.kotlinbeans import org.joda.beans.Bean import org.joda.beans.BeanBuilder import org.joda.beans.ImmutableBean import org.joda.beans.MetaBean import org.joda.beans.MetaBeanProvider import org.joda.beans.MetaProperty import org.joda.beans.MetaProvider import org.joda.beans.Property import org.joda.beans.PropertyStyle import org.joda.beans.impl.BasicProperty import org.joda.beans.ser.SerDeserializer import org.joda.convert.StringConvert import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.util.HashMap import java.util.NoSuchElementException import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.javaType /** * Provides implementations of all [ImmutableBean] methods for Kotlin classes. * * A Kotlin class can become a Joda bean by implementing this interface. No function implementations are * needed as they are all provided by this interface. */ @MetaProvider(KotlinMetaBeanProvider::class) interface ImmutableData : ImmutableBean { override fun <R : Any> property(propertyName: String): Property<R> = metaBean().metaProperty<R>(propertyName).createProperty(this) override fun propertyNames(): Set<String> = metaBean().metaPropertyMap().keys override fun metaBean(): MetaBean = KotlinMetaBean.forType(this.javaClass.kotlin) } /** * [MetaBean] implementation for Kotlin classes that uses reflection. */ data class KotlinMetaBean(val beanClass: KClass<out ImmutableBean>) : MetaBean { private val propertyMap : Map<String, KProperty1<*, *>> private val metaPropertyMap : Map<String, MetaProperty<*>> private val aliasMap : Map<String?, String> init { propertyMap = beanClass.memberProperties.associateBy { it.name } metaPropertyMap = beanClass.memberProperties.associateBy({ it.name }, { KotlinMetaProperty(it, this) }) aliasMap = propertyMap .mapValues { (_, prop) -> alias(prop) } .filterValues { it != null } .map { (name, alias) -> alias to name } .toMap() } override fun isBuildable(): Boolean = true override fun metaPropertyCount(): Int = propertyMap.size override fun beanType(): Class<out Bean> = beanClass.java override fun metaPropertyIterable(): Iterable<MetaProperty<*>> = metaPropertyMap.values override fun metaPropertyExists(propertyName: String): Boolean = propertyMap.containsKey(propertyName) override fun metaPropertyMap(): Map<String, MetaProperty<*>> = metaPropertyMap @Suppress("UNCHECKED_CAST") override fun <R : Any> metaProperty(propertyName: String): MetaProperty<R> { val property = metaPropertyMap[propertyName] if (property != null) return property as MetaProperty<R> val alias = aliasMap[propertyName] if (alias != null) return metaProperty(alias) throw NoSuchElementException("No property found named $propertyName") } override fun beanName(): String = beanClass.java.name override fun builder(): BeanBuilder<out Bean> = KotlinBeanBuilder(this) private fun alias(property: KProperty1<*, *>): String? = property.annotations.filterIsInstance<Alias>().firstOrNull()?.value companion object { private val metaBeanCache: MutableMap<KClass<*>, KotlinMetaBean> = ConcurrentHashMap() fun <T : ImmutableBean> forType(type: KClass<T>): KotlinMetaBean { val cachedBean = metaBeanCache[type] if (cachedBean != null) return cachedBean val metaBean = KotlinMetaBean(type) metaBeanCache[type] = metaBean return metaBean } } } @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.PROPERTY) annotation class Alias(val value: String) /** * [MetaProperty] implementation for Kotlin properties that uses reflection. */ @Suppress("UNCHECKED_CAST") data class KotlinMetaProperty<T>(val property: KProperty<T>, val metaBean: KotlinMetaBean) : MetaProperty<T> { override fun metaBean(): MetaBean = metaBean override fun get(bean: Bean): T = property.getter.call(bean) override fun getString(bean: Bean): String = StringConvert.INSTANCE.convertToString(get(bean)) override fun getString(bean: Bean, stringConvert: StringConvert): String = stringConvert.convertToString(get(bean)) override fun annotations(): List<Annotation> = property.annotations override fun propertyGenericType(): Type = property.returnType.javaType override fun declaringType(): Class<*> = metaBean.beanType() override fun createProperty(bean: Bean): Property<T> = BasicProperty.of(bean, this) override fun <A : Annotation> annotation(annotation: Class<A>): A = annotations().find { it.javaClass == annotation } as A? ?: throw NoSuchElementException("No annotation found of type ${annotation.name}") override fun style(): PropertyStyle = PropertyStyle.IMMUTABLE override fun name(): String = property.name override fun propertyType(): Class<T> = property.returnType.javaType.let { type -> when (type) { is Class<*> -> type as Class<T> is ParameterizedType -> type.rawType as Class<T> else -> throw IllegalArgumentException("Unexpected type for return type ${property.returnType} of $property") } } // Unsupported mutator methods ------------------------------------------------- override fun set(bean: Bean, value: Any) { throw UnsupportedOperationException("set not supported for immutable beans") } override fun put(bean: Bean, value: Any): T { throw UnsupportedOperationException("put not supported for immutable beans") } override fun setString(bean: Bean, value: String) { throw UnsupportedOperationException("setString supported for immutable beans") } override fun setString(bean: Bean, value: String, stringConvert: StringConvert) { throw UnsupportedOperationException("setString supported for immutable beans") } } /** * [BeanBuilder] implementation for Kotlin classes. */ @Suppress("UNCHECKED_CAST") data class KotlinBeanBuilder<T : ImmutableBean>(val metaBean: KotlinMetaBean) : BeanBuilder<T> { private val propertyValues: MutableMap<String, Any> = HashMap() override fun <P> get(metaProperty: MetaProperty<P>): P? = get(metaProperty.name()) as P? override fun get(propertyName: String): Any? = propertyValues[propertyName] override fun set(metaProperty: MetaProperty<*>, value: Any): BeanBuilder<T> = set(metaProperty.name(), value) override fun set(propertyName: String, value: Any): BeanBuilder<T> { propertyValues[propertyName] = value return this } @Suppress("UNCHECKED_CAST") override fun build(): T { val primaryConstructor = metaBean.beanClass.constructors.toList()[0] // Filter out the constructor parameters if there is no corresponding argument. // Construction will fail if any of these parameters are non-optional (don't have default values) val constructorArgs = primaryConstructor.parameters .filter { propertyValues.contains(it.name) } .associateWith { propertyValues[it.name] } return primaryConstructor.callBy(constructorArgs) as T } } /** * [SerDeserializer] implementation for Kotlin classes. */ object KotlinSerDeserializer : SerDeserializer { @Suppress("UNCHECKED_CAST") override fun findMetaBean(beanType: Class<*>): MetaBean = KotlinMetaBean.forType(beanType.kotlin as KClass<out ImmutableBean>) override fun createBuilder(beanType: Class<*>, metaBean: MetaBean): BeanBuilder<*> = KotlinBeanBuilder<ImmutableBean>(metaBean as KotlinMetaBean) override fun findMetaProperty(beanType: Class<*>, metaBean: MetaBean, propertyName: String): MetaProperty<*> = metaBean.metaProperty<Any>(propertyName) override fun setValue(builder: BeanBuilder<*>, metaProp: MetaProperty<*>, value: Any) { builder.set(metaProp, value) } override fun build(beanType: Class<*>, builder: BeanBuilder<*>): Any = builder.build() } class KotlinMetaBeanProvider : MetaBeanProvider { override fun findMetaBean(cls: Class<*>): MetaBean? { if (!ImmutableBean::class.java.isAssignableFrom(cls)) return null @Suppress("UNCHECKED_CAST") return KotlinMetaBean.forType(cls.kotlin as KClass<out ImmutableBean>) } }
apache-2.0
fa4233ee5c1a69447d8cc5f6befe9bfa
37.299107
121
0.711971
4.527177
false
false
false
false
halawata13/ArtichForAndroid
app/src/main/java/net/halawata/artich/QiitaTagSelectionActivity.kt
2
4614
package net.halawata.artich import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.AdapterView import android.widget.ListView import android.widget.RelativeLayout import android.widget.TextView import net.halawata.artich.entity.QiitaTag import net.halawata.artich.enum.Media import net.halawata.artich.model.ApiUrlString import net.halawata.artich.model.AsyncNetworkTask import net.halawata.artich.model.DatabaseHelper import net.halawata.artich.model.QiitaTagListAdapter import net.halawata.artich.model.config.ConfigList import net.halawata.artich.model.config.QiitaTagList import net.halawata.artich.model.menu.MediaMenuFactory import java.net.HttpURLConnection class QiitaTagSelectionActivity : AppCompatActivity() { companion object { const val mediaTypeKey = "mediaTypeKey" } lateinit var mediaType: Media private var adapter: QiitaTagListAdapter? = null private var listView: ListView? = null private var loadingView: RelativeLayout? = null private var loadingText: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_qiita_tag_selection) title = resources.getString(R.string.menu_management_activity_title) val mediaString = intent.getStringExtra(QiitaTagSelectionActivity.mediaTypeKey) val configList = ConfigList(resources, ConfigList.Type.MENU) mediaType = configList.getMediaId(mediaString) ?: Media.COMMON loadingView = findViewById(R.id.loading_view) loadingText = findViewById(R.id.loading_text) // list setup adapter = QiitaTagListAdapter(this, ArrayList(), R.layout.qiita_tag_list_item) listView = findViewById(R.id.qiita_tag_list) listView?.adapter = adapter listView?.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l -> // 選択済みのものはダイアログを出さない if (adapter?.data?.get(i)?.selected == true) { return@OnItemClickListener } adapter?.data?.get(i)?.title?.let { val dialog = ConfirmDialogFragment() dialog.tagName = it dialog.show(fragmentManager, "qiitaTagAddition") } } // update request() } private fun request() { loadingView?.alpha = 1F loadingText?.text = resources.getString(R.string.loading_tag) val asyncNetWorkTask = AsyncNetworkTask() asyncNetWorkTask.request(ApiUrlString.Qiita.tagList, AsyncNetworkTask.Method.GET) asyncNetWorkTask.onResponse = { responseCode, content -> if (responseCode == HttpURLConnection.HTTP_OK && content != null) { val qiitaTagList = QiitaTagList() val helper = DatabaseHelper(this) val menu = MediaMenuFactory.create(mediaType, helper, resources) qiitaTagList.parse(content, menu.get())?.let { adapter?.data = it listView?.adapter = adapter loadingView?.alpha = 0F } ?: run { loadingText?.text = resources.getString(R.string.loading_fail_tag) } } else { loadingText?.text = resources.getString(R.string.loading_fail_tag) } } } /** * タグ選択確認ダイアログ */ class ConfirmDialogFragment : DialogFragment() { var tagName: String? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(activity) val activity = activity as QiitaTagSelectionActivity val title = tagName?.let { "「$it」を追加します。" } ?: run { getString(R.string.confirm) } builder.setTitle(title) .setPositiveButton("OK", { dialogInterface, i -> val intent = Intent() intent.putExtra("selectedTag", tagName) activity.setResult(Activity.RESULT_OK, intent) activity.finish() }) .setNegativeButton(getString(R.string.cancel), null) return builder.create() } } }
mit
b52cb274ad2c36d3ac7abfe68543f2c7
33.641221
100
0.637726
4.707469
false
true
false
false
camsteffen/polite
src/main/java/me/camsteffen/polite/rule/master/RuleMasterAdapter.kt
1
2245
package me.camsteffen.polite.rule.master import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.ListAdapter import me.camsteffen.polite.R import me.camsteffen.polite.model.CalendarRule import me.camsteffen.polite.model.Rule import me.camsteffen.polite.model.ScheduleRule private object ViewTypes { const val HEADING: Int = 0 const val CALENDAR_RULE: Int = 1 const val SCHEDULE_RULE: Int = 2 } class RuleMasterAdapter( private val ruleClickListener: RuleClickListener, private val ruleCheckedChangeListener: RuleCheckedChangeListener ) : ListAdapter<RuleMasterItem, RuleMasterViewHolder<*>>(RuleMasterItem.DIFF_CALLBACK) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RuleMasterViewHolder<*> { val inflater = LayoutInflater.from(parent.context) return when (viewType) { ViewTypes.HEADING -> { val view = inflater.inflate(R.layout.subhead_rules, parent, false) RuleMasterViewHolder.HeadingViewHolder(view) } ViewTypes.CALENDAR_RULE, ViewTypes.SCHEDULE_RULE -> { val view = inflater.inflate(R.layout.rule_list_item, parent, false) RuleMasterViewHolder .RuleViewHolder(view, ruleClickListener, ruleCheckedChangeListener) } else -> throw IllegalArgumentException() } } override fun onBindViewHolder(holder: RuleMasterViewHolder<*>, position: Int) { bindViewHolder(holder, getItem(position)) } @Suppress("UNCHECKED_CAST") private fun <E : RuleMasterItem> bindViewHolder( holder: RuleMasterViewHolder<E>, item: RuleMasterItem ) { holder.bind(item as E) } override fun getItemViewType(position: Int): Int { return when (val item = getItem(position)) { is RuleMasterItem.Heading -> ViewTypes.HEADING is RuleMasterItem.Rule<*> -> when (item.rule) { is CalendarRule -> ViewTypes.CALENDAR_RULE is ScheduleRule -> ViewTypes.SCHEDULE_RULE } } } fun getRuleAt(position: Int): Rule = (getItem(position) as RuleMasterItem.Rule<*>).rule }
mpl-2.0
a29767e824c52924c864aafc3059f905
35.803279
96
0.673497
4.66736
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/SettingActivity.kt
1
13371
package com.example.android.eyebody import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.support.v4.hardware.fingerprint.FingerprintManagerCompat import android.support.v4.os.CancellationSignal import android.support.v7.app.AppCompatActivity import android.util.Log import android.widget.Toast import com.example.android.eyebody.management.ManagementActivity import com.example.android.eyebody.management.config.subcontent.callee.content.FindPasswordActivity import kotlinx.android.synthetic.main.activity_setting.* import java.security.* import com.example.android.eyebody.utility.MyFingerPrintManager // 임시 UI 만드는 곳 // 비번입력하고 SchedulerActivity로 넘어감. class SettingActivity : AppCompatActivity() { val TAG = "mydbg_setting" val cancelSignal = CancellationSignal() //-------- 조금만 참아 --------------------------------------- val KEY_NAME = "my_key" var mKeyStore: KeyStore? = null var mKeyPairGenerator: KeyPairGenerator? = null var mSignature: Signature? = null //-------- 조금만 참아 --------------------------------------- override fun onStop() { super.onStop() if (!cancelSignal.isCanceled) cancelSignal.cancel() } @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_setting) Log.d(TAG, "setting 진입") val initSharedPref: SharedPreferences = getSharedPreferences(getString(R.string.getSharedPreference_initSetting), Context.MODE_PRIVATE) val sharedPref_hashedPW = initSharedPref.getString(getString(R.string.sharedPreference_hashedPW), getString(R.string.sharedPreference_default_hashedPW)) val configSharedPref = getSharedPreferences(getString(R.string.getSharedPreference_configuration_Only_Int), Context.MODE_PRIVATE) val isUserSetCanFingerPrintAuth = configSharedPref.getInt(getString(R.string.sharedPreference_Security_Use_Fingerprint), 0) == 1 // 키보드-확인 눌렀을 때 반응 setting_input_pw.setOnEditorActionListener { textView, i, keyEvent -> Log.d(TAG, "키보드-확인 누름") // EditText 친 부분 MD5 암호화 val md5 = MessageDigest.getInstance("MD5") val str_inputPW: String = setting_input_pw.text.toString() val pwByte: ByteArray = str_inputPW.toByteArray(charset("unicode")) md5.update(pwByte) val hashedPW = md5.digest().toString(charset("unicode")) // 공유변수와 일치여부 검증 Log.d(TAG, "prePW : $sharedPref_hashedPW / PW : $hashedPW") if (hashedPW == sharedPref_hashedPW.toString()) { val schedulerPage = Intent(this, ManagementActivity::class.java) if (!cancelSignal.isCanceled) cancelSignal.cancel() startActivity(schedulerPage) finish() } else { Toast.makeText(this, "관계자 외 출입금지~", Toast.LENGTH_LONG).show() } true } // password 찾기/수정 액티비티 button_explore_password.setOnClickListener { Log.d(TAG, "explore password") val mIntent = Intent(this, FindPasswordActivity::class.java) startActivity(mIntent) } // 지문인식 if (isUserSetCanFingerPrintAuth && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val osFpManager = FingerprintManagerCompat.from(this) if (osFpManager.isHardwareDetected) { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8fingerprint)) setting_text_pw_guide.text = "지문 또는 비밀번호를 입력하세요." /* // -------------------------------------------------------------------------------- // ------- signature 사용해보기 --------------------------------------------------- // -------------------------------------------------------------------------------- @RequiresApi(Build.VERSION_CODES.M) fun createKeyPair() { try { // Set the alias of the entry in Android KeyStore where the key will appear // and the constrains (purposes) in the constructor of the Builder mKeyPairGenerator?.initialize( KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_SIGN) .setDigests(KeyProperties.DIGEST_SHA256) .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1")) .setUserAuthenticationRequired(true) .build()) mKeyPairGenerator?.generateKeyPair() } catch (e: InvalidAlgorithmParameterException) { throw RuntimeException(e) } } @RequiresApi(Build.VERSION_CODES.M) fun initSignature(): Boolean { try { mKeyStore?.load(null) val key = mKeyStore?.getKey(KEY_NAME, null) as PrivateKey mSignature?.initSign(key) return true } catch (e: KeyPermanentlyInvalidatedException) { return false } catch (e: Exception) { throw RuntimeException("Failed to init Cipher : ${e.localizedMessage}", e) } } // -------------------------------------------------------------------------------- // 비대칭키를 생성한다. val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore") kpg.initialize( KeyGenParameterSpec.Builder("key1", KeyProperties.PURPOSE_SIGN) .setDigests(KeyProperties.DIGEST_SHA256) .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1")) .setUserAuthenticationRequired(true) .build()) kpg.generateKeyPair() // setUserAuthenticationRequired true 하면 등록한 상태에서만 하겠다는거고 이러면 대칭키를 만들어서 활용해야함? val keyStore1 = KeyStore.getInstance("AndroidKeyStore") keyStore1.load(null) val publicKey = keyStore1.getCertificate("Public Key").publicKey val keyStore2 = KeyStore.getInstance("AndroidKeyStore") keyStore2.load(null) val privateKey = keyStore2.getKey("Private Key", null) as PrivateKey val signature = Signature.getInstance("SHA256withECDSA") val keyStore = KeyStore.getInstance("AndroidKeyStore") keyStore.load(null) signature.initSign(privateKey) val cryptObject = FingerprintManagerCompat.CryptoObject(signature) // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // ---------- cipher 사용해보기 --------------------------------------------------- // -------------------------------------------------------------------------------- val KEY_NAME = "머라고써야돼는거야!!" val KEY_BYTE = KEY_NAME.toByteArray() // 임의의 키를 만든다. 앱별로 만들어짐. 해시처럼 비대칭키인것같다. 근데 rsa로 해버리기? val keyGenerator = KeyGenerator.getInstance("HmacSHA256") keyGenerator .init(KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT.or(KeyProperties.PURPOSE_DECRYPT)) .setBlockModes(KeyProperties.BLOCK_MODE_ECB) .setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) .build()) keyGenerator.generateKey() // 지문인식에 enc, dec를 해주는 보안 모듈?? 사이퍼를 위 키에 맞춰 만든다. val cipher = Cipher.getInstance("${KeyProperties.KEY_ALGORITHM_RSA}/${KeyProperties.BLOCK_MODE_ECB}/${KeyProperties.ENCRYPTION_PADDING_RSA_OAEP}") val keyStore = KeyStore.getInstance(KeyProperties.KEY_ALGORITHM_RSA) keyStore.load(null) cipher.init(Cipher.ENCRYPT_MODE, keyStore.getKey(KEY_NAME, null)) val crypto: FingerprintManagerCompat.CryptoObject = FingerprintManagerCompat.CryptoObject(cipher) // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- */ //createKeyPair() if (true/*initSignature()*/) { //val cryptObject = FingerprintManagerCompat.CryptoObject(mSignature) val myFpManager = object : MyFingerPrintManager(osFpManager, this, null, 0, cancelSignal, null) { override fun onAuthenticationSucceeded(result: FingerprintManagerCompat.AuthenticationResult?) { super.onAuthenticationSucceeded(result) val schedulerPage = Intent(baseContext, ManagementActivity::class.java) startActivity(schedulerPage) finish() } override fun afterLockout() { runOnUiThread { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8privacy)) setting_text_pw_guide.text = "비밀번호를 입력하세요. (지문인식은 30초 뒤 접근 가능합니다.)" } } override fun afterLockOutRelease() { runOnUiThread { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8fingerprint)) setting_text_pw_guide.text = "지문 또는 비밀번호를 입력하세요." } } override fun afterNoSpace() { runOnUiThread { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8privacy)) setting_text_pw_guide.text = "비밀번호를 입력하세요. (저장공간이 부족하여 지문인식이 불가능합니다.)" } } override fun afterUnAvailableError() { runOnUiThread { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8privacy)) setting_text_pw_guide.text = "비밀번호를 입력하세요." } } } myFpManager.startAuthenticate() } } else { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8privacy)) if (osFpManager.hasEnrolledFingerprints()) { // 등록을 안함. setting_text_pw_guide.text = "비밀번호를 입력하세요.\n(지문을 등록하지 않아 지문인식을 이용하실 수 없습니다.)" } else { // 디바이스 미지원 setting_text_pw_guide.text = "비밀번호를 입력하세요." } } } else { setting_image_fingerprint.setImageDrawable(getDrawable(R.drawable.icons8privacy)) setting_text_pw_guide.text = "비밀번호를 입력하세요." } } }
mit
0b6c3ed71fa6b1c1d8bfc322478af04b
50.644898
162
0.489449
5.230674
false
false
false
false
xfournet/intellij-community
java/execution/impl/src/com/intellij/execution/AlternativeSdkRootsProvider.kt
1
2823
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution import com.intellij.execution.configurations.ConfigurationWithAlternativeJre import com.intellij.openapi.application.WriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.AdditionalLibraryRootsProvider import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.SyntheticLibrary import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.EmptyRunnable import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.AppUIUtil import java.util.* /** * @author egor */ class AlternativeSdkRootsProvider : AdditionalLibraryRootsProvider() { override fun getAdditionalProjectLibraries(project: Project): Collection<SyntheticLibrary> { if (Registry.`is`("index.run.configuration.jre")) { return RunManager.getInstance(project).allConfigurationsList .filterIsInstance(ConfigurationWithAlternativeJre::class.java) .filter { it.isAlternativeJrePathEnabled } .mapNotNull { it.alternativeJrePath } .mapNotNull { ProjectJdkTable.getInstance().findJdk(it) } .distinct() .map { SdkSyntheticLibrary(it) } .toList() } return emptyList() } class SdkSyntheticLibrary(val sdk: Sdk) : SyntheticLibrary() { override fun getSourceRoots(): Collection<VirtualFile> = sdk.rootProvider.getFiles(OrderRootType.SOURCES).toList() override fun getBinaryRoots(): Collection<VirtualFile> = sdk.rootProvider.getFiles(OrderRootType.CLASSES).toList() override fun equals(other: Any?) = other is SdkSyntheticLibrary && sourceRoots == other.sourceRoots && binaryRoots == other.binaryRoots override fun hashCode() = Objects.hash(sourceRoots, binaryRoots) } companion object { private val storedLibs = mutableListOf<SyntheticLibrary>() @JvmStatic fun reindexIfNeeded(project: Project) { if (!Registry.`is`("index.run.configuration.jre")) return val provider = AdditionalLibraryRootsProvider.EP_NAME.findExtension(AlternativeSdkRootsProvider::class.java) val additionalProjectLibraries = provider.getAdditionalProjectLibraries(project) if (additionalProjectLibraries != storedLibs) { storedLibs.clear() storedLibs.addAll(additionalProjectLibraries) AppUIUtil.invokeOnEdt { WriteAction.run<RuntimeException> { ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true) } } } } } }
apache-2.0
08440cbeee2b7570906b44ee019645dd
41.787879
140
0.761247
4.825641
false
true
false
false
emufog/emufog
src/test/kotlin/emufog/backbone/BackboneConnectorTest.kt
1
4317
/* * MIT License * * Copyright (c) 2020 emufog contributors * * 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 emufog.backbone import emufog.graph.Graph import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test internal class BackboneConnectorTest { private val defaultBaseAddress = "1.2.3.4" @Test fun `update the predecessor if necessary`() { val graph = Graph(defaultBaseAddress) val system = graph.getOrCreateAutonomousSystem(0) val backboneNode0 = graph.createBackboneNode(0, system) val edgeNode1 = graph.createEdgeNode(1, system) val backboneNode2 = graph.createBackboneNode(2, system) val backboneNode3 = graph.createBackboneNode(3, system) graph.createEdge(0, backboneNode0, edgeNode1, 1F, 10F) graph.createEdge(1, backboneNode0, backboneNode2, 1F, 10F) graph.createEdge(2, edgeNode1, backboneNode3, 1F, 10F) graph.createEdge(3, backboneNode2, backboneNode3, 1F, 10F) BackboneConnector(system).connectBackbone() assertNotNull(graph.getBackboneNode(0)) assertNotNull(graph.getBackboneNode(2)) assertNotNull(graph.getBackboneNode(3)) assertNotNull(graph.getEdgeNode(1)) } @Test fun `the backbone should connect disjoint backbone parts`() { val graph = Graph(defaultBaseAddress) val system = graph.getOrCreateAutonomousSystem(0) val node0 = graph.createEdgeNode(0, system) val node1 = graph.createEdgeNode(1, system) val node2 = graph.createBackboneNode(2, system) val node3 = graph.createEdgeNode(3, system) val node4 = graph.createEdgeNode(4, system) val node5 = graph.createEdgeNode(5, system) val node6 = graph.createEdgeNode(6, system) val node7 = graph.createBackboneNode(7, system) val node8 = graph.createEdgeNode(8, system) val node9 = graph.createEdgeNode(9, system) val latency = 1.5F val bandwidth = 1000F graph.createEdge(0, node0, node2, latency, bandwidth) graph.createEdge(1, node1, node2, latency, bandwidth) graph.createEdge(2, node3, node2, latency, bandwidth) graph.createEdge(3, node4, node2, latency, bandwidth) graph.createEdge(4, node1, node5, latency, bandwidth) graph.createEdge(5, node4, node8, latency, bandwidth) graph.createEdge(6, node5, node7, latency, bandwidth) graph.createEdge(7, node6, node7, latency, bandwidth) graph.createEdge(8, node8, node7, latency, bandwidth) graph.createEdge(9, node9, node7, latency, bandwidth) Assertions.assertEquals(8, graph.edgeNodes.size) Assertions.assertEquals(2, graph.backboneNodes.size) Assertions.assertEquals(10, graph.edges.size) BackboneConnector(system).connectBackbone() Assertions.assertEquals(4, graph.backboneNodes.size) assertNotNull(graph.getBackboneNode(2)) assertNotNull(graph.getBackboneNode(7)) assertNotNull(graph.getBackboneNode(1)) assertNotNull(graph.getBackboneNode(5)) Assertions.assertEquals(6, graph.edgeNodes.size) Assertions.assertEquals(10, graph.edges.size) } }
mit
ba34363eefe6c7d4c1a08679d9ef979a
42.18
81
0.710679
4.175048
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/ChatBuilderEntity.kt
1
3535
package com.github.shynixn.blockball.core.logic.persistence.entity import com.github.shynixn.blockball.api.business.enumeration.ChatColor import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.api.persistence.entity.ChatBuilderComponent import com.github.shynixn.blockball.core.logic.business.extension.translateChatColors import java.util.ArrayList /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class ChatBuilderEntity : ChatBuilder { private val components = ArrayList<Any>() /** * Sets the color of the text. */ override fun setColor(color: ChatColor): ChatBuilder { this.components.add(color) return this } /** * Creates a new component with the given [text]. */ override fun component(text: String): ChatBuilderComponent { val component = ChatBuilderComponentEntity(this, text) this.components.add(component) return component } /** * Appends a line break. */ override fun nextLine(): ChatBuilder { this.components.add("\n") return this } /** * Appends text to the builder. */ override fun text(text: String): ChatBuilder { this.components.add(text) return this } /** * ToString. */ override fun toString(): String { val finalMessage = StringBuilder() val cache = StringBuilder() finalMessage.append("{\"text\": \"\"") finalMessage.append(", \"extra\" : [") var firstExtra = false for (component in this.components) { if (component !is ChatColor && firstExtra) { finalMessage.append(", ") } when (component) { is ChatColor -> cache.append(component) is String -> { finalMessage.append("{\"text\": \"") finalMessage.append((cache.toString() + component).translateChatColors()) finalMessage.append("\"}") cache.setLength(0) firstExtra = true } else -> { finalMessage.append(component) firstExtra = true } } } finalMessage.append("]}") return finalMessage.toString() } }
apache-2.0
ae1a62d30cb4d9ae6f662088e64ece1e
32.67619
93
0.633098
4.651316
false
false
false
false
chrisbanes/tivi
app/src/main/java/app/tivi/AppNavigation.kt
1
15740
/* * 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 import androidx.compose.animation.AnimatedContentScope import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.NavBackStackEntry import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.navArgument import app.tivi.account.AccountUi import app.tivi.episodedetails.EpisodeDetails import app.tivi.home.discover.Discover import app.tivi.home.followed.Followed import app.tivi.home.popular.PopularShows import app.tivi.home.recommended.RecommendedShows import app.tivi.home.search.Search import app.tivi.home.trending.TrendingShows import app.tivi.home.watched.Watched import app.tivi.showdetails.details.ShowDetails import app.tivi.showdetails.seasons.ShowSeasons import com.google.accompanist.navigation.animation.AnimatedNavHost import com.google.accompanist.navigation.animation.navigation import com.google.accompanist.navigation.material.BottomSheetNavigator import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi internal sealed class Screen(val route: String) { object Discover : Screen("discover") object Following : Screen("following") object Watched : Screen("watched") object Search : Screen("search") } private sealed class LeafScreen( private val route: String ) { fun createRoute(root: Screen) = "${root.route}/$route" object Discover : LeafScreen("discover") object Following : LeafScreen("following") object Trending : LeafScreen("trending") object Popular : LeafScreen("popular") object ShowDetails : LeafScreen("show/{showId}") { fun createRoute(root: Screen, showId: Long): String { return "${root.route}/show/$showId" } } object EpisodeDetails : LeafScreen("episode/{episodeId}") { fun createRoute(root: Screen, episodeId: Long): String { return "${root.route}/episode/$episodeId" } } object ShowSeasons : LeafScreen("show/{showId}/seasons?seasonId={seasonId}") { fun createRoute( root: Screen, showId: Long, seasonId: Long? = null ): String { return "${root.route}/show/$showId/seasons".let { if (seasonId != null) "$it?seasonId=$seasonId" else it } } } object RecommendedShows : LeafScreen("recommendedshows") object Watched : LeafScreen("watched") object Search : LeafScreen("search") object Account : LeafScreen("account") } @ExperimentalAnimationApi @Composable internal fun AppNavigation( navController: NavHostController, onOpenSettings: () -> Unit, modifier: Modifier = Modifier ) { AnimatedNavHost( navController = navController, startDestination = Screen.Discover.route, enterTransition = { defaultTiviEnterTransition(initialState, targetState) }, exitTransition = { defaultTiviExitTransition(initialState, targetState) }, popEnterTransition = { defaultTiviPopEnterTransition() }, popExitTransition = { defaultTiviPopExitTransition() }, modifier = modifier ) { addDiscoverTopLevel(navController, onOpenSettings) addFollowingTopLevel(navController, onOpenSettings) addWatchedTopLevel(navController, onOpenSettings) addSearchTopLevel(navController, onOpenSettings) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addDiscoverTopLevel( navController: NavController, openSettings: () -> Unit ) { navigation( route = Screen.Discover.route, startDestination = LeafScreen.Discover.createRoute(Screen.Discover) ) { addDiscover(navController, Screen.Discover) addAccount(Screen.Discover, openSettings) addShowDetails(navController, Screen.Discover) addShowSeasons(navController, Screen.Discover) addEpisodeDetails(navController, Screen.Discover) addRecommendedShows(navController, Screen.Discover) addTrendingShows(navController, Screen.Discover) addPopularShows(navController, Screen.Discover) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addFollowingTopLevel( navController: NavController, openSettings: () -> Unit ) { navigation( route = Screen.Following.route, startDestination = LeafScreen.Following.createRoute(Screen.Following) ) { addFollowedShows(navController, Screen.Following) addAccount(Screen.Following, openSettings) addShowDetails(navController, Screen.Following) addShowSeasons(navController, Screen.Following) addEpisodeDetails(navController, Screen.Following) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addWatchedTopLevel( navController: NavController, openSettings: () -> Unit ) { navigation( route = Screen.Watched.route, startDestination = LeafScreen.Watched.createRoute(Screen.Watched) ) { addWatchedShows(navController, Screen.Watched) addAccount(Screen.Watched, openSettings) addShowDetails(navController, Screen.Watched) addShowSeasons(navController, Screen.Watched) addEpisodeDetails(navController, Screen.Watched) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addSearchTopLevel( navController: NavController, openSettings: () -> Unit ) { navigation( route = Screen.Search.route, startDestination = LeafScreen.Search.createRoute(Screen.Search) ) { addSearch(navController, Screen.Search) addAccount(Screen.Search, openSettings) addShowDetails(navController, Screen.Search) addShowSeasons(navController, Screen.Search) addEpisodeDetails(navController, Screen.Search) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addDiscover( navController: NavController, root: Screen ) { composable( route = LeafScreen.Discover.createRoute(root), debugLabel = "Discover()" ) { Discover( openTrendingShows = { navController.navigate(LeafScreen.Trending.createRoute(root)) }, openPopularShows = { navController.navigate(LeafScreen.Popular.createRoute(root)) }, openRecommendedShows = { navController.navigate(LeafScreen.RecommendedShows.createRoute(root)) }, openShowDetails = { showId, seasonId, episodeId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) // If we have an season id, we also open that if (seasonId != null) { navController.navigate( LeafScreen.ShowSeasons.createRoute(root, showId, seasonId) ) } // If we have an episodeId, we also open that if (episodeId != null) { navController.navigate(LeafScreen.EpisodeDetails.createRoute(root, episodeId)) } }, openUser = { navController.navigate(LeafScreen.Account.createRoute(root)) } ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addFollowedShows( navController: NavController, root: Screen ) { composable( route = LeafScreen.Following.createRoute(root), debugLabel = "Followed()" ) { Followed( openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) }, openUser = { navController.navigate(LeafScreen.Account.createRoute(root)) } ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addWatchedShows( navController: NavController, root: Screen ) { composable( route = LeafScreen.Watched.createRoute(root), debugLabel = "Watched()" ) { Watched( openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) }, openUser = { navController.navigate(LeafScreen.Account.createRoute(root)) } ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addSearch( navController: NavController, root: Screen ) { composable(LeafScreen.Search.createRoute(root)) { Search( openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) } ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addShowDetails( navController: NavController, root: Screen ) { composable( route = LeafScreen.ShowDetails.createRoute(root), debugLabel = "ShowDetails()", arguments = listOf( navArgument("showId") { type = NavType.LongType } ) ) { ShowDetails( navigateUp = navController::navigateUp, openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) }, openEpisodeDetails = { episodeId -> navController.navigate(LeafScreen.EpisodeDetails.createRoute(root, episodeId)) }, openSeasons = { showId, seasonId -> navController.navigate(LeafScreen.ShowSeasons.createRoute(root, showId, seasonId)) } ) } } @OptIn(ExperimentalMaterialNavigationApi::class, ExperimentalMaterialApi::class) @ExperimentalAnimationApi private fun NavGraphBuilder.addEpisodeDetails( navController: NavController, root: Screen ) { bottomSheet( route = LeafScreen.EpisodeDetails.createRoute(root), debugLabel = "EpisodeDetails()", arguments = listOf( navArgument("episodeId") { type = NavType.LongType } ) ) { val bottomSheetNavigator = navController.navigatorProvider .getNavigator(BottomSheetNavigator::class.java) EpisodeDetails( expandedValue = bottomSheetNavigator.navigatorSheetState.currentValue, navigateUp = navController::navigateUp ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addRecommendedShows( navController: NavController, root: Screen ) { composable( route = LeafScreen.RecommendedShows.createRoute(root), debugLabel = "RecommendedShows()" ) { RecommendedShows( openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) }, navigateUp = navController::navigateUp ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addTrendingShows( navController: NavController, root: Screen ) { composable( route = LeafScreen.Trending.createRoute(root), debugLabel = "TrendingShows()" ) { TrendingShows( openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) }, navigateUp = navController::navigateUp ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addPopularShows( navController: NavController, root: Screen ) { composable( route = LeafScreen.Popular.createRoute(root), debugLabel = "PopularShows()" ) { PopularShows( openShowDetails = { showId -> navController.navigate(LeafScreen.ShowDetails.createRoute(root, showId)) }, navigateUp = navController::navigateUp ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addAccount( root: Screen, onOpenSettings: () -> Unit ) { dialog( route = LeafScreen.Account.createRoute(root), debugLabel = "AccountUi()" ) { AccountUi( openSettings = onOpenSettings ) } } @ExperimentalAnimationApi private fun NavGraphBuilder.addShowSeasons( navController: NavController, root: Screen ) { composable( route = LeafScreen.ShowSeasons.createRoute(root), debugLabel = "ShowSeasons()", arguments = listOf( navArgument("showId") { type = NavType.LongType }, navArgument("seasonId") { type = NavType.StringType nullable = true } ) ) { ShowSeasons( navigateUp = navController::navigateUp, openEpisodeDetails = { episodeId -> navController.navigate(LeafScreen.EpisodeDetails.createRoute(root, episodeId)) }, initialSeasonId = it.arguments?.getString("seasonId")?.toLong() ) } } @ExperimentalAnimationApi private fun AnimatedContentScope<*>.defaultTiviEnterTransition( initial: NavBackStackEntry, target: NavBackStackEntry ): EnterTransition { val initialNavGraph = initial.destination.hostNavGraph val targetNavGraph = target.destination.hostNavGraph // If we're crossing nav graphs (bottom navigation graphs), we crossfade if (initialNavGraph.id != targetNavGraph.id) { return fadeIn() } // Otherwise we're in the same nav graph, we can imply a direction return fadeIn() + slideIntoContainer(AnimatedContentScope.SlideDirection.Start) } @ExperimentalAnimationApi private fun AnimatedContentScope<*>.defaultTiviExitTransition( initial: NavBackStackEntry, target: NavBackStackEntry ): ExitTransition { val initialNavGraph = initial.destination.hostNavGraph val targetNavGraph = target.destination.hostNavGraph // If we're crossing nav graphs (bottom navigation graphs), we crossfade if (initialNavGraph.id != targetNavGraph.id) { return fadeOut() } // Otherwise we're in the same nav graph, we can imply a direction return fadeOut() + slideOutOfContainer(AnimatedContentScope.SlideDirection.Start) } private val NavDestination.hostNavGraph: NavGraph get() = hierarchy.first { it is NavGraph } as NavGraph @ExperimentalAnimationApi private fun AnimatedContentScope<*>.defaultTiviPopEnterTransition(): EnterTransition { return fadeIn() + slideIntoContainer(AnimatedContentScope.SlideDirection.End) } @ExperimentalAnimationApi private fun AnimatedContentScope<*>.defaultTiviPopExitTransition(): ExitTransition { return fadeOut() + slideOutOfContainer(AnimatedContentScope.SlideDirection.End) }
apache-2.0
8fa8a6822628ef8614d2b7c8c3f8f9a6
32.136842
98
0.680114
5.006361
false
false
false
false
jtransc/jtransc
jtransc-core/src/com/jtransc/ast/transform/CombineNewInitTransform.kt
2
2820
/* * 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.transform import com.jtransc.ast.* import java.util.* object CombineNewInitTransform : AstTransform() { /* private fun transform(stms: ArrayList<AstStm>) { var newToLocal = hashMapOf<AstExpr.LValueExpr, Pair<Int, AstType.REF>>() for (n in 0 until stms.size) { val stm = stms[n] // empty NEW if (stm is AstStm.SET && stm.expr.value is AstExpr.NEW) { val setLocal = stm.local val newExpr = stm.expr as AstExpr.NEW newToLocal[setLocal] = Pair(n, newExpr.type) } // CALL <init> constructor method if (stm is AstStm.STM_EXPR && stm.expr.value is AstExpr.CALL_INSTANCE) { val callExpr = stm.expr.value as AstExpr.CALL_INSTANCE val callLocal = if (callExpr.obj is AstExpr.LOCAL) { callExpr.obj } else if (callExpr.obj is AstExpr.CAST && callExpr.obj.expr is AstExpr.LOCAL) { callExpr.obj.expr } else { null } if (callLocal != null) { if (callExpr.isSpecial && callExpr.method.name == "<init>") { if (callLocal in newToLocal) { val (instantiateIndex, instantiateType) = newToLocal[callLocal]!! if (callExpr.method.containingClass != instantiateType.name) { throw AssertionError("Unexpected new + <init> call!") } stms[instantiateIndex] = AstStm.NOP() stms[n] = AstStm.SET_NEW_WITH_CONSTRUCTOR(callLocal, instantiateType, callExpr.method, callExpr.args) newToLocal.remove(callLocal) } } } } } // All new must have their <init> counterpart!, so we assert that! // TODO Commented, but important for kotlin classes that must be initializated!! //assert(newToLocal.isEmpty()) if (newToLocal.isNotEmpty()) { //println("WARNING (combining new+<init>): $newToLocal couldn't combine. This would make native instantiations to fail, otherwise this will work just fine.") //println(stms.joinToString("\n")) } } */ override fun invoke(body: AstBody): AstBody { /* if (body.stm is AstStm.STMS) { val stms = body.stm.stms.toCollection(arrayListOf<AstStm>()) transform(stms) return AstBody(AstStm.STMS(stms.filter { it !is AstStm.NOP }), body.locals, body.traps) } return body */ return body } }
apache-2.0
f24b56aa459c61dfd9c0917af5332c91
31.425287
160
0.683333
3.498759
false
false
false
false
outadoc/Twistoast-android
keolisprovider/src/main/kotlin/fr/outadev/android/transport/timeo/dto/LigneDTO.kt
1
1232
/* * Twistoast - LigneDTO.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twistoast is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.outadev.android.transport.timeo.dto import org.simpleframework.xml.Element /** * Represents a bus line returned by the XML API. * * @author outadoc */ class LigneDTO { @field:Element(name = "code") lateinit var code: String @field:Element(name = "nom") lateinit var nom: String @field:Element(name = "sens") lateinit var sens: String @field:Element(name = "vers", required = false) var vers: String? = null @field:Element(name = "couleur") var couleur: Int = 0x34495E }
gpl-3.0
71e1e898691c695254897479bcea72a8
35.235294
76
0.721591
3.710843
false
false
false
false
jtransc/jtransc
jtransc-gen-cpp/src/com/jtransc/gen/cpp/libs/Libs.kt
1
1251
package com.jtransc.gen.cpp.libs import com.jtransc.gen.cpp.CppCompiler import com.jtransc.io.ProcessUtils import com.jtransc.service.JTranscService import com.jtransc.vfs.ExecOptions import com.jtransc.vfs.SyncVfsFile import org.rauschig.jarchivelib.ArchiveFormat import org.rauschig.jarchivelib.ArchiverFactory import org.rauschig.jarchivelib.CompressionType import java.io.File import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.* object Libs { //val LIBS = ServiceLoader.load(Lib::class.java).toList() //val LIBS = listOf(BoostLib(), BdwgcLib(), JniHeadersLib()) //val LIBS = listOf(BdwgcLib(), JniHeadersLib()) //val LIBS = listOf(BdwgcLib()) val LIBS = listOf<Lib>() val cppCommonFolder get() = CppCompiler.CPP_COMMON_FOLDER.realfile val sdkDir = CppCompiler.CPP_COMMON_FOLDER.realfile val includeFolders: List<File> get() = LIBS.flatMap { it.includeFolders } val libFolders: List<File> get() = LIBS.flatMap { it.libFolders } val libs: List<String> get() = LIBS.flatMap { it.libs } val extraDefines: List<String> get() = LIBS.flatMap { it.extraDefines } fun installIfRequired(resourcesVfs: SyncVfsFile) { for (lib in LIBS) { lib.installIfRequired(resourcesVfs) } } }
apache-2.0
75f78469bf63e8fcef48fa622529b7e1
32.810811
74
0.766587
3.11194
false
false
false
false
avast/android-lectures
Lecture 3/Demo-app/app/src/main/java/com/avast/mff/lecture3/data/User.kt
1
416
package com.avast.mff.lecture3.data /** * Github user details. */ data class User( val login: String, val id: Int, val avatar_url: String, val gravatar_id: String = "", val url: String, val html_url: String, val followers_url: String, val following_url: String, val public_repos: Int = 0, val public_gists: Int = 0, val followers: Int = 0, val following: Int = 0, )
apache-2.0
b93213875bcb7362786ab4ef051dd3cb
20.947368
35
0.617788
3.354839
false
false
false
false
Fitbit/MvRx
launcher/src/main/java/com/airbnb/mvrx/launcher/MavericksLauncherTestMocksActivity.kt
1
2553
package com.airbnb.mvrx.launcher import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.FragmentActivity import com.airbnb.mvrx.launcher.MavericksLauncherTestMocksActivity.Companion.provideIntentToTestMock import com.airbnb.mvrx.mocking.MockedViewProvider import java.util.LinkedList /** * This is given a list of view mocks and automatically opens them all one at a time. * Each fragment waits until it successfully loads, then returns so the next one can be loaded. * This tests that each mock can be loaded without crashing. * * Override [provideIntentToTestMock] in order to customize what activity is used to test each * mock. */ class MavericksLauncherTestMocksActivity : FragmentActivity() { private val mockCount = mocksToShow.size override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { testNextMock() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_CODE_TEST_FINISHED) { testNextMock() } else { super.onActivityResult(requestCode, resultCode, data) } } private fun testNextMock() { // This assumes that it isn't rotated or otherwise restarted, and that it will resume when the previously launched screen returns val nextMock = mocksToShow.poll() ?: run { AlertDialog.Builder(this) .setTitle("Complete") .setMessage("$mockCount mocks were tested were crashes, and no crashes were found!") .setPositiveButton("OK") { _, _ -> finish() } .show() return } val intent = provideIntentToTestMock(this, nextMock) startActivityForResult(intent, REQUEST_CODE_TEST_FINISHED) // TODO Support clicking on views to catch crashes on click } companion object { internal val mocksToShow = LinkedList<MockedViewProvider<*>>() private const val REQUEST_CODE_TEST_FINISHED = 2 /** * Override this in order to customize what activity is used to test each * mock. */ var provideIntentToTestMock: (Context, MockedViewProvider<*>) -> Intent = { context, mock -> MavericksLauncherMockActivity.intent(context, mock, finishAfterLaunch = true) } } }
apache-2.0
b3792d466c9b43615ca8d4a338440315
34.957746
137
0.669017
4.872137
false
true
false
false
http4k/http4k
http4k-core/src/test/kotlin/org/http4k/lens/CookiesTest.kt
1
4158
package org.http4k.lens import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Uri.Companion.of import org.http4k.core.cookie.Cookie import org.http4k.core.cookie.cookie import org.junit.jupiter.api.Test class CookiesTest { private val request = Request(GET, of("")) .cookie("hello", "world") .cookie("hello", "world2") @Test fun `value present`() { assertThat(Cookies.optional("hello")(request), equalTo(Cookie("hello", "world"))) assertThat(Cookies.required("hello")(request), equalTo(Cookie("hello", "world"))) assertThat(Cookies.map { it.value.length }.required("hello")(request), equalTo(5)) assertThat(Cookies.map { it.value.length }.optional("hello")(request), equalTo(5)) val expected: List<Cookie?> = listOf(Cookie("hello", "world"), Cookie("hello", "world2")) assertThat(Cookies.multi.required("hello")(request), equalTo(expected)) assertThat(Cookies.multi.optional("hello")(request), equalTo(expected)) } @Test fun `value missing`() { assertThat(Cookies.optional("world")(request), absent()) val required = Cookies.required("world") assertThat({ required(request) }, throws(lensFailureWith<Request>(Missing(required.meta), overallType = Failure.Type.Missing))) assertThat(Cookies.multi.optional("world")(request), absent()) val optionalMulti = Cookies.multi.required("world") assertThat({ optionalMulti(request) }, throws(lensFailureWith<Request>(Missing(optionalMulti.meta), overallType = Failure.Type.Missing))) } @Test fun `value replaced`() { val single = Cookies.required("world") val target = single(Cookie("world", "value1"), request) val actual = single(Cookie("world", "value2"), target) assertThat(actual, equalTo(request.cookie(Cookie("world", "value2")))) val multi = Cookies.multi.required("world") assertThat(multi(listOf(Cookie("world", "value3"), Cookie("world", "value4")), multi(listOf(Cookie("world", "value1"), Cookie("world", "value2")), request)), equalTo(request.cookie(Cookie("world", "value3")).cookie(Cookie("world", "value4")))) } @Test fun `invalid value`() { val asInt = Cookies.map { it.value.toInt() } val required = asInt.required("hello") assertThat({ required(request) }, throws(lensFailureWith<Request>(Invalid(required.meta), overallType = Failure.Type.Invalid))) val optional = asInt.optional("hello") assertThat({ optional(request) }, throws(lensFailureWith<Request>(Invalid(optional.meta), overallType = Failure.Type.Invalid))) val requiredMulti = asInt.multi.required("hello") assertThat({ requiredMulti(request) }, throws(lensFailureWith<Request>(Invalid(requiredMulti.meta), overallType = Failure.Type.Invalid))) val optionalMulti = asInt.multi.optional("hello") assertThat({ optionalMulti(request) }, throws(lensFailureWith<Request>(Invalid(optionalMulti.meta), overallType = Failure.Type.Invalid))) } @Test fun `sets value on request`() { val cookie = Cookies.required("bob") val cookieInstance = Cookie("bob", "hello") val withCookies = cookie(cookieInstance, request) assertThat(cookie(withCookies), equalTo(cookieInstance)) } @Test fun `can create a custom type and get and set on request`() { val custom = Cookies.map({ MyCustomType(it.value) }, { Cookie("bob", it.value) }).required("bob") val instance = MyCustomType("hello world!") val reqWithCookies = custom(instance, Request(GET, "")) assertThat(reqWithCookies.cookie("bob"), equalTo(Cookie("bob", "hello world!"))) assertThat(custom(reqWithCookies), equalTo(MyCustomType("hello world!"))) } @Test fun `toString is ok`() { assertThat(Cookies.optional("hello").toString(), equalTo("Optional cookie 'hello'")) } }
apache-2.0
45033130219473de632d1782d48c0736
42.768421
165
0.670996
4.158
false
true
false
false
Ingwersaft/James
src/main/kotlin/com/mkring/james/Chat.kt
1
4061
package com.mkring.james import com.mkring.james.chatbackend.ChatBackend import com.mkring.james.chatbackend.OutgoingPayload import com.mkring.james.chatbackend.UniqueChatTarget import com.mkring.james.chatbackend.rocketchat.singleLineLog import com.mkring.james.mapping.Ask import com.mkring.james.mapping.Mapping import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.slf4j.LoggerFactory import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.coroutines.CoroutineContext class Chat( val type: String, val mappings: Map<String, Mapping.() -> Unit>, val chatBackend: ChatBackend, val abortKeywords: MutableList<String>, val mappingprefix: String ) : CoroutineScope { private val job = Job() override val coroutineContext: CoroutineContext get() = job + JamesPool private val runningJobs = mutableMapOf<UniqueChatTarget, Job>() private val askResultMap: MutableMap<UniqueChatTarget, CompletableFuture<String>> = mutableMapOf() internal suspend fun start() { log.info("start() called") log.info("received the following mappings:\n" + mappings.map { it.key }.joinToString("\n")) chatBackend.start() log.info("Chat chat started, now iterating chatBackend channel") launch { chatBackend.backendToJamesChannel.consumeEach { (uniqueChatTarget, username, text) -> log.info("chatBackend.backendToJamesChannel received $text from $username - $uniqueChatTarget") try { if (callbackFutureHandled(text, uniqueChatTarget).not()) { mappings.map { it.key }.joinToString(";").let { log.debug("chatLogicMappings keys =$it") } mappings.entries.firstOrNull { text.startsWith(it.key) }?.let { entry -> log.info("going to handle ${entry.key}") val job = launch { Mapping(text, uniqueChatTarget, username, mappingprefix, this@Chat).apply { entry.value.invoke(this) } } log.info("launch done") runningJobs[uniqueChatTarget] = job } log.trace("nothing found for $text from $uniqueChatTarget") } } catch (e: Exception) { log.warn("chatBackend.backendToJamesChannel.consumeEach threw exception: ${e.singleLineLog()}") } } } } private fun callbackFutureHandled(text: String, target: UniqueChatTarget): Boolean { askResultMap[target]?.let { if (text isIn abortKeywords) { log.info("target $target received abortKeyword: $text") send(OutgoingPayload(target, "aborted")) askResultMap[target]?.cancel(true) askResultMap.remove(target) return true } askResultMap[target]?.complete(text) askResultMap.remove(target) return true } return false } internal fun send(outgoingPayload: OutgoingPayload) = runBlocking { chatBackend.fromJamesToBackendChannel.send(outgoingPayload) } internal fun ask( text: String, options: Map<String, String> = emptyMap(), timeout: Int, timeunit: TimeUnit, target: UniqueChatTarget ): Ask<String> { val future = CompletableFuture<String>() askResultMap[target] = future send(OutgoingPayload(target, text, options)) return Ask.of { future.get(timeout.toLong(), timeunit) } } internal fun stop() { job.cancel() } companion object { private val log = LoggerFactory.getLogger("Chat") } }
gpl-3.0
54cb66618f1310b82ff058fe0a6a25b7
38.427184
115
0.614873
4.749708
false
false
false
false
material-components/material-components-android-codelabs
kotlin/shrine/app/src/main/java/com/google/codelabs/mdc/kotlin/shrine/ProductGridFragment.kt
1
3176
package com.google.codelabs.mdc.kotlin.shrine import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.View import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.codelabs.mdc.kotlin.shrine.network.ProductEntry import com.google.codelabs.mdc.kotlin.shrine.staggeredgridlayout.StaggeredProductCardRecyclerViewAdapter import kotlinx.android.synthetic.main.shr_product_grid_fragment.view.* class ProductGridFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment with the ProductGrid theme val view = inflater.inflate(R.layout.shr_product_grid_fragment, container, false) // Set up the tool bar (activity as AppCompatActivity).setSupportActionBar(view.app_bar) view.app_bar.setNavigationOnClickListener(NavigationIconClickListener( activity!!, view.product_grid, AccelerateDecelerateInterpolator(), ContextCompat.getDrawable(context!!, R.drawable.shr_branded_menu), // Menu open icon ContextCompat.getDrawable(context!!, R.drawable.shr_close_menu))) // Menu close icon // Set up the RecyclerView view.recycler_view.setHasFixedSize(true) val gridLayoutManager = GridLayoutManager(context, 2, RecyclerView.HORIZONTAL, false) gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (position % 3 == 2) 2 else 1 } } view.recycler_view.layoutManager = gridLayoutManager val adapter = StaggeredProductCardRecyclerViewAdapter( ProductEntry.initProductEntryList(resources)) view.recycler_view.adapter = adapter val largePadding = resources.getDimensionPixelSize(R.dimen.shr_staggered_product_grid_spacing_large) val smallPadding = resources.getDimensionPixelSize(R.dimen.shr_staggered_product_grid_spacing_small) view.recycler_view.addItemDecoration(ProductGridItemDecoration(largePadding, smallPadding)) // Set cut corner background for API 23+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { view.product_grid.background = context?.getDrawable(R.drawable.shr_product_grid_background_shape) } return view } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.shr_toolbar_menu, menu) super.onCreateOptionsMenu(menu, menuInflater) } }
apache-2.0
bb66ab3b48310df002d44f92c4b2bf65
45.028986
109
0.731108
4.90881
false
false
false
false
MichaelRocks/DataBindingCompat
plugin/src/main/java/io/michaelrocks/databindingcompat/processor/DataBindingCompatProcessor.kt
1
7203
/* * Copyright 2017 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.databindingcompat.processor import io.michaelrocks.databindingcompat.logging.getLogger import io.michaelrocks.databindingcompat.transform.TransformSet import io.michaelrocks.databindingcompat.transform.TransformUnit import io.michaelrocks.grip.GripFactory import io.michaelrocks.grip.mirrors.Type import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassWriter import java.io.Closeable import java.io.File import java.io.InputStream import java.io.OutputStream import java.util.jar.JarEntry import java.util.jar.JarInputStream import java.util.jar.JarOutputStream import java.util.jar.Manifest class DataBindingCompatProcessor(private val transformSet: TransformSet) : Closeable { private val logger = getLogger() private val grip = GripFactory.create(transformSet.getClasspath()) fun process() { logger.info("Starting DataBindingCompat") if (logger.isDebugEnabled) { transformSet.dump() logger.debug("Classpath:\n {}", grip.fileRegistry.classpath().joinToString(separator = "\n ")) } if (Types.ANDROIDX_APP_COMPAT_RESOURCES in grip.fileRegistry) { if (Patch(Types.ANDROIDX_VIEW_DATA_BINDING, Types.ANDROIDX_APP_COMPAT_RESOURCES).maybeApply()) { logger.info("Patched {} successfully", Types.ANDROIDX_VIEW_DATA_BINDING.className) return } } if (Types.SUPPORT_APP_COMPAT_RESOURCES in grip.fileRegistry) { if (Patch(Types.SUPPORT_VIEW_DATA_BINDING, Types.SUPPORT_APP_COMPAT_RESOURCES).maybeApply()) { logger.info("Patched {} successfully", Types.SUPPORT_VIEW_DATA_BINDING.className) return } } logger.info("AppCompatResources class not found. Aborting...") } private fun TransformSet.dump() { logger.debug("Transform set:") logger.debug(" Units:\n {}", units.joinToString(separator = "\n ")) logger.debug(" Referenced units:\n {}", referencedUnits.joinToString(separator = "\n ")) logger.debug(" Boot classpath:\n {}", bootClasspath.joinToString(separator = "\n ")) } override fun close() { grip.close() } private inner class Patch( private val viewDataBindingType: Type.Object, private val appCompatResourcesType: Type.Object ) { fun maybeApply(): Boolean { val input = findViewDataBindingClassFile() if (input == null) { logger.info("ViewDataBinding class not found. Aborting...") return false } val unit = findTransformUnitForInputFile(input) if (unit == null) { logger.info("ViewDataBinding class cannot be transformed. Aborting...") return false } logger.info("Patching ViewDataBinding.class: {}", unit) val data = createPatchedViewDataBindingClass() savePatchedViewDataBindingClass(unit, data) return true } private fun createPatchedViewDataBindingClass(): ByteArray { val data = grip.fileRegistry.readClass(viewDataBindingType) val reader = ClassReader(data) val writer = StandaloneClassWriter(reader, ClassWriter.COMPUTE_MAXS or ClassWriter.COMPUTE_FRAMES, grip.classRegistry) val patcher = ViewDataBindingClassPatcher(writer, appCompatResourcesType) reader.accept(patcher, ClassReader.SKIP_FRAMES) return writer.toByteArray() } private fun findViewDataBindingClassFile(): File? { return grip.fileRegistry.findFileForType(viewDataBindingType) } private fun findTransformUnitForInputFile(input: File): TransformUnit? { val canonicalInput = input.canonicalFile val units = transformSet.units.filter { it.changes.status != TransformUnit.Status.REMOVED } return units.firstOrNull { it.input.canonicalFile == canonicalInput } } private fun savePatchedViewDataBindingClass(unit: TransformUnit, data: ByteArray) { when (unit.format) { TransformUnit.Format.DIRECTORY -> savePatchedViewDataBindingClassToDirectory(unit.output, data) TransformUnit.Format.JAR -> savePatchedViewDataBindingClassToJar(unit.output, data) } } private fun savePatchedViewDataBindingClassToDirectory(directory: File, data: ByteArray) { logger.info("Save patched ViewDataBinding to directory {}", directory) val file = File(directory, viewDataBindingType.toFilePath()) file.mkdirs() file.writeBytes(data) } private fun savePatchedViewDataBindingClassToJar(jar: File, data: ByteArray) { logger.info("Save patched ViewDataBinding to jar {}", jar) val temporary = createTempFile(jar.name, "tmp") try { savePatchedViewDataBindingClassToJar(jar, temporary, data) temporary.inputStream().buffered().use { jarInputStream -> jar.outputStream().buffered().use { jarOutputStream -> jarInputStream.copyTo(jarOutputStream) } } } finally { if (!temporary.delete()) { logger.warn("Cannot delete a temporary file {}", temporary) } } } private fun savePatchedViewDataBindingClassToJar(source: File, target: File, data: ByteArray) { source.inputStream().buffered().jar().use { jarInputStream -> target.outputStream().buffered().jar(jarInputStream.manifest).use { jarOutputStream -> val path = viewDataBindingType.toFilePath() jarInputStream.entries().filterNot { it.name == path }.forEach { jarEntry -> jarOutputStream.putNextEntry(jarEntry) jarInputStream.copyTo(jarOutputStream) jarInputStream.closeEntry() jarOutputStream.closeEntry() } jarOutputStream.putNextEntry(JarEntry(path)) jarOutputStream.write(data) jarOutputStream.closeEntry() } } } private fun Type.Object.toFilePath(): String { return "$internalName.class" } private fun InputStream.jar(verify: Boolean = true): JarInputStream { return JarInputStream(this, verify) } private fun OutputStream.jar(manifest: Manifest? = null): JarOutputStream { return if (manifest != null) JarOutputStream(this, manifest) else JarOutputStream(this) } private fun JarInputStream.entries(): Sequence<JarEntry> { return generateSequence { nextJarEntry } } } companion object { private fun TransformSet.getClasspath(): List<File> { val classpath = ArrayList<File>(units.size + referencedUnits.size + bootClasspath.size) units.mapTo(classpath) { it.input } referencedUnits.mapTo(classpath) { it.input } classpath += bootClasspath return classpath } } }
apache-2.0
36bfd82049bd3dac803a8d4df77d0425
36.321244
124
0.70193
4.587898
false
false
false
false
tfcbandgeek/SmartReminders-android
smartreminderssave/src/main/java/jgappsandgames/smartreminderssave/date/Month.kt
1
3812
package jgappsandgames.smartreminderssave.date // Java import java.util.Calendar // Save import jgappsandgames.smartreminderssave.tasks.Task /** * Month * Created by joshua on 12/12/2017. */ class Month(start: Calendar) { // Data ---------------------------------------------------------------------------------------- private var daysInMonth = start.getMaximum(Calendar.DAY_OF_MONTH) private var monthStartsOn = start.get(Calendar.DAY_OF_WEEK) private val start = start.clone() as Calendar private var end: Calendar private var days: ArrayList<Day> // Constructors -------------------------------------------------------------------------------- init { days = ArrayList(daysInMonth) for (i in 0 until daysInMonth) { days.add(Day(start.clone() as Calendar)) start.add(Calendar.DAY_OF_MONTH, 1) } end = days[daysInMonth - 1].day end.add(Calendar.DAY_OF_MONTH, 1) } // Task Management Methods --------------------------------------------------------------------- // TODO: CLEAN UP AL of the if stements here fun addTask(task: Task): Boolean { if (task.getDateDue()!!.get(Calendar.YEAR) >= start.get(Calendar.YEAR)) { if (task.getDateDue()!!.get(Calendar.DAY_OF_YEAR) >= start.get(Calendar.MONTH)) { if (task.getDateDue()!!.get(Calendar.YEAR) <= end.get(Calendar.YEAR)) { if (task.getDateDue()!!.get(Calendar.MONTH) <= end.get(Calendar.MONTH)) { for (day in days) { if (day.day.get(Calendar.DAY_OF_MONTH) == task.getDateDue()!!.get(Calendar.DAY_OF_MONTH)) { day.addTask(task) return true } } } } } } return false } fun removeTask(task: Task): Boolean { if (task.getDateDue()!!.get(Calendar.YEAR) >= start.get(Calendar.YEAR)) { if (task.getDateDue()!!.get(Calendar.DAY_OF_YEAR) >= start.get(Calendar.MONTH)) { if (task.getDateDue()!!.get(Calendar.YEAR) <= end.get(Calendar.YEAR)) { if (task.getDateDue()!!.get(Calendar.MONTH) <= end.get(Calendar.MONTH)) { for (day in days) { if (day.day.get(Calendar.DAY_OF_MONTH) == task.getDateDue()!!.get(Calendar.DAY_OF_MONTH)) { day.removeTask(task) return true } } } } } } return false } // Getters ------------------------------------------------------------------------------------- fun getDay(instance: Calendar): Day? { if (instance.get(Calendar.YEAR) >= start.get(Calendar.YEAR)) { if (instance.get(Calendar.DAY_OF_YEAR) >= start.get(Calendar.MONTH)) { if (instance.get(Calendar.YEAR) <= end.get(Calendar.YEAR)) { if (instance.get(Calendar.MONTH) <= end.get(Calendar.MONTH)) { for (day in days) { if (day.day.get(Calendar.DAY_OF_MONTH) == instance.get(Calendar.DAY_OF_MONTH)) { return day } } } } } } return null } fun getStart(): Calendar = start fun getEnd(): Calendar = end fun getAllTasks(): ArrayList<Task> { val tasks = ArrayList<Task>() if (days.size == 0) return tasks for (day in days) tasks.addAll(day.tasks) return tasks } }
apache-2.0
30a98f82c15f90c6ca953c57345081c4
35.314286
119
0.456191
4.654457
false
false
false
false
pdvrieze/ProcessManager
java-common/src/javaMain/kotlin/net/devrieze/util/MemHandleMap.kt
1
20452
/* * Copyright (c) 2021. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package net.devrieze.util import java.util.* import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write import kotlin.jvm.JvmOverloads import kotlin.jvm.javaClass /** * * * A map that helps with mapping items and their handles. * * * * The system will generate handles in a systematic way. A handle consists of * two parts: the first part (most significant 32 bits) is the generation. The * second part is the position in the array. The generation allows reuse of * storage space while still being able to have unique handles. The handles are * not guaranteed to have any relation between each other. * * * * While handles are not guaranteed, the generation of the handles is NOT secure * in the sense of being able to be predicted with reasonable certainty. * * @author Paul de Vrieze * * @param V The type of object contained in the map. * @param capacity The initial capacity. * * @param loadFactor The load factor to use for the map. */ @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") actual open class MemHandleMap<V : Any> @JvmOverloads constructor(capacity: Int = DEFAULT_CAPACITY, private var loadFactor: Float = DEFAULT_LOADFACTOR, val handleAssigner: (V, Handle<V>) -> V? = ::HANDLE_AWARE_ASSIGNER) : MutableHandleMap<V>, MutableIterable<V> { actual constructor(handleAssigner: (V, Handle<V>) -> V?) : this( DEFAULT_CAPACITY, DEFAULT_LOADFACTOR, handleAssigner ) private var changeMagic = 0 // Counter that increases every change. This can detect concurrentmodification. /** * This array contains the actual values in the map. */ @Suppress("UNCHECKED_CAST") private var _values: Array<V?> = arrayOfNulls<Any>(capacity) as Array<V?> /** * This array records for each value what generation it is. This is used to * compare the generation of the value to the generation of the handle. */ private var generations: IntArray = IntArray(capacity) private var nextHandle = FIRST_HANDLE private var barrier = capacity /** * The handle at the 0th element of the list. This allows for handle numbers * to increase over time without storage being needed. */ private var offset = 0 private var size = 0 val lock = ReentrantReadWriteLock() /** * Create a new map with given load factor. * * @param loadFactor The load factor to use. */ constructor(loadFactor: Float) : this(DEFAULT_CAPACITY, loadFactor) { } /** * Completely reset the state of the map. This is mainly for testing. */ fun reset() { lock.write { _values.fill(null) generations.fill(0) size = 0 barrier = _values.size offset = 0 nextHandle = FIRST_HANDLE ++changeMagic } } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#clear() */ override fun clear() { lock.write { _values.fill(null) generations.fill(0) size = 0 updateBarrier() } } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#iterator() */ override fun iterator(): MutableIterator<V> { return MapIterator() } operator fun contains(element: Any): Boolean { if (element is Handle<*>) { return contains(element) } else { return lock.read { _values.any { it == element } } } } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#contains(java.lang.Object) */ override fun containsElement(element: V): Boolean { return contains(element) } override fun contains(handle: Handle<V>): Boolean { return lock.read { val index = indexFromHandle(handle.handleValue) if (index < 0 || index >= _values.size) { false } else _values[index] != null } } /** * Determine whether a handle might be valid. Used by the iterator. */ private fun inRange(iterPos: Int): Boolean { if (barrier <= nextHandle) { return iterPos in barrier..(nextHandle - 1) } return iterPos >= barrier || iterPos < nextHandle } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#put(V) */ override fun <W : V> put(value: W): Handle<W> { assert( if (value is ReadableHandleAware<*>) !value.handle.isValid else true ) { "Storing a value that already has a handle is invalid" } var index: Int // The space in the mValues array where to store the value var generation: Int // To allow reuse of spaces without reuse of handles // every reuse increases it's generation. val handle: Long = lock.write { ++changeMagic // If we can just add a handle to the ringbuffer. if (nextHandle != barrier) { index = nextHandle nextHandle++ if (nextHandle == _values.size) { if (barrier == _values.size) { barrier = 0 } nextHandle = 0 offset += _values.size } generation = START_GENERATION } else { // Ring buffer too full if (size == _values.size || size >= loadFactor * _values.size) { expand() return put(value) // expand } else { // Reuse a handle. index = findNextFreeIndex() generation = maxOf(generations[index], START_GENERATION) } } val h = (generation.toLong() shl 32) + handleFromIndex(index) val updatedValue = handleAssigner(value, if (h < 0) Handle.invalid() else Handle(h)) ?: value _values[index] = updatedValue generations[index] = generation size++ h } return Handle(handle) } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#get(long) */ operator fun get(handle: Long): V? { if (handle == -1L) return null // Split the handle up into generation and index. val generation = (handle shr 32).toInt() return lock.read { val index = indexFromHandle(handle.toInt().toLong()) when { index < 0 || // If the generation doesn't map we have a wrong handle. generations[index] != generation -> null else -> _values[index] // Just get the element out of the map. } } } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#get(net.devrieze.util.MemHandleMap.Handle) */ override fun get(handle: Handle<V>): V? { return get(handle.handleValue) } @Deprecated("Don't use untyped handles") override fun set(handle: Long, value: V): V? { // Split the handle up into generation and index. val generation = (handle shr 32).toInt() return lock.write { val index = indexFromHandle(handle.toInt().toLong()) if (index < 0) { throw ArrayIndexOutOfBoundsException(handle.toInt()) } // If the generation doesn't map we have a wrong handle. if (generations[index] != generation) { throw ArrayIndexOutOfBoundsException("Generation mismatch ($generation)") } val updatedValue = handleAssigner(value, if (handle < 0) Handle.invalid() else Handle(handle)) ?: value // Just get the element out of the map. _values[index] = updatedValue updatedValue } } override fun set(handle: Handle<V>, value: V): V? { @Suppress("DEPRECATION") return set(handle.handleValue, value) } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#size() */ @Suppress("OverridingDeprecatedMember") override fun getSize() = lock.read { size } fun size() = lock.read { size } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#remove(net.devrieze.util.MemHandleMap.Handle) */ override fun remove(handle: Handle<V>): Boolean { return remove(handle.handleValue) } /* (non-Javadoc) * @see net.devrieze.util.HandleMap#remove(long) */ fun remove(handle: Long): Boolean { val generation = (handle shr 32).toInt() return lock.write { val index = indexFromHandle(handle.toInt().toLong()) if (index < 0) { throw ArrayIndexOutOfBoundsException(handle.toInt()) } if (generations[index] != generation) { return false } if (_values[index] != null) { ++changeMagic _values[index] = null generations[index]++ // Update the generation for safety checking size-- updateBarrier() true } else { false } } } /** * Try to make the barrier move down to allow the map to stay small. This * method itself isn't synchronized as the calling method should be. */ private fun updateBarrier() { if (size == 0) { offset += nextHandle barrier = _values.size nextHandle = 0 } else { if (barrier == _values.size) { barrier = 0 } while (_values[barrier] == null) { barrier++ if (barrier == _values.size) { barrier = 0 } } } } /** * Get an index from the given handle. This method is not synchronized, * callers should be. * @param pHandle The handle to use. * * @return the index into the values array. * * @throws ArrayIndexOutOfBoundsException when the handle is not a valid * * position. */ private fun indexFromHandle(pHandle: Long): Int { val handle = pHandle.toInt() var result = handle - offset if (result < 0) { result += _values.size if (result < barrier) { return -1 } } else if (result >= nextHandle) { return -1 } if (result >= _values.size) { return -1 } return result } private fun handleFromIndex(pIndex: Int): Int { if (nextHandle > barrier) { return pIndex + offset } if (pIndex < barrier) { // must be at same offset as mNextHandle return pIndex + offset } else { return pIndex + offset - _values.size } } private fun findNextFreeIndex(): Int { var i = barrier while (_values[i] != null) { i++ if (i == _values.size) { i = 0 } } return i } private fun expand() { if (barrier == _values.size) { System.err.println("Unexpected code visit") barrier = 0 } if (barrier != nextHandle) { System.err.println("Expanding while not full") return } val newLen = _values.size * 2 @Suppress("UNCHECKED_CAST") val newValues = arrayOfNulls<Any>(newLen) as Array<V?> val newGenerations = IntArray(newLen) System.arraycopy(_values, barrier, newValues, 0, _values.size - barrier) System.arraycopy(generations, barrier, newGenerations, 0, generations.size - barrier) if (barrier > 0) { System.arraycopy(_values, 0, newValues, _values.size - barrier, barrier) System.arraycopy(generations, 0, newGenerations, generations.size - barrier, barrier) } offset = handleFromIndex(barrier) nextHandle = _values.size _values = newValues generations = newGenerations barrier = 0 } @Suppress("OverridingDeprecatedMember") override fun isEmpty(): Boolean = lock.read { size == 0 } @Suppress("UNCHECKED_CAST") fun toArray(): Array<Any> { lock.read { val result = arrayOfNulls<Any>(size) return writeToArray(result) as Array<Any> } } fun <U> toArray(pA: Array<U?>): Array<U?> { lock.read { val size = size var array = pA if (pA.size < size) { @Suppress("UNCHECKED_CAST") array = java.lang.reflect.Array.newInstance(array.javaClass.componentType, size) as Array<U?> } writeToArray(array) return array } } private fun <T> writeToArray(result: Array<T?>): Array<T?> { var i = 0 for (elem in _values) { @Suppress("UNCHECKED_CAST") result[i] = elem as T ++i } if (result.size > i) { result[i] = null // Mark the element afterwards as null as by {@link #toArray(T[])} } return result } fun add(element: V): Boolean { put(element) return true } fun remove(element: Any): Boolean { if (element is Handle<*>) { return remove(element.handleValue) } lock.write { val it = iterator() while (it.hasNext()) { if (it.next() == element) { it.remove() return true } } } return false } fun containsAll(elements: Collection<*>): Boolean { lock.read { return elements.all { contains(it) } } } fun addAll(elements: Collection<V>): Boolean { lock.write { return elements.fold(false) { r, elem -> add(elem) or r } } } fun removeAll(elements: Collection<*>): Boolean { lock.write { return elements.fold(false) { r, elem -> remove(elem as Any) or r } } } fun retainAll(pC: Collection<*>): Boolean { var result = false lock.write { val it = iterator() while (it.hasNext()) { val elem = it.next() if (!pC.contains(elem)) { it.remove() result = result or true } } } return result } override fun toString(): String { return lock.read { val it = MapIterator() generateSequence { if (it.hasNext()) { val value = it.next() "${it.handle}: $value" } else null }.joinToString(prefix = "MemHandleMap [", postfix = "]") } } companion object { private const val DEFAULT_LOADFACTOR = 0.9f private const val DEFAULT_CAPACITY = 1024 const val FIRST_HANDLE = 0 private const val START_GENERATION = 0 } internal class MapCollection<T : Any>(private val handleMap: MemHandleMap<T>) : MutableCollection<T> { override val size: Int get() { return handleMap.size } override fun isEmpty(): Boolean { return handleMap.size == 0 } override operator fun contains(element: T): Boolean { return handleMap.containsElement(element) } override fun iterator(): MutableIterator<T> { return handleMap.iterator() } fun toArray(): Array<Any> { handleMap.lock.read { val result = arrayOfNulls<Any?>(size) @Suppress("UNCHECKED_CAST") return writeToArray(result) as Array<Any> } } private fun writeToArray(result: Array<Any?>): Array<Any?> { var i = 0 handleMap.lock.read { for (elem in handleMap) { result[i] = elem ++i } } if (result.size > i) { result[i] = null // Mark the element afterwards as null as by {@link #toArray(T[])} } return result } override fun add(element: T): Boolean { handleMap.put(element) return true } override fun remove(element: T): Boolean { if (element is ReadableHandleAware<*>) { return handleMap.remove(element.handle) } return handleMap.remove(element) } override fun containsAll(elements: Collection<T>): Boolean { return handleMap.containsAll(elements) } override fun addAll(elements: Collection<T>): Boolean { return handleMap.addAll(elements) } override fun removeAll(elements: Collection<T>): Boolean { return handleMap.removeAll(elements) } override fun retainAll(elements: Collection<T>): Boolean { return handleMap.retainAll(elements) } override fun clear() { handleMap.clear() } } private inner class MapIterator : MutableIterator<V> { private var iterPos: Int = -1 private val iteratorMagic: Int private var oldPos = -1 private var atStart = true init { iteratorMagic = lock.read { iterPos = if (barrier >= _values.size) 0 else barrier changeMagic } } override fun hasNext(): Boolean { lock.read { if (iteratorMagic != changeMagic) { throw ConcurrentModificationException("Trying to iterate over a changed map.") } if (iterPos == nextHandle && barrier == nextHandle) { return atStart } if (barrier < nextHandle) { return iterPos < nextHandle } return iterPos >= barrier || iterPos < nextHandle } } override fun next(): V { oldPos = iterPos atStart = false lock.read { if (iteratorMagic != changeMagic) { throw ConcurrentModificationException("Trying to iterate over a changed map.") } do { iterPos++ if (iterPos >= _values.size) { iterPos = 0 } } while (_values[iterPos] == null && inRange(iterPos)) return _values[oldPos]!! } } override fun remove() { lock.write { if (iteratorMagic != changeMagic) throw ConcurrentModificationException("The underlying collection changed before remove") if (_values[oldPos] == null) { throw IllegalStateException("Calling remove twice can not work") } _values[oldPos] = null generations[oldPos]++ updateBarrier() if (iterPos == barrier) { atStart = true } } } val handle: Long get() = lock.read { handleFromIndex(oldPos).toLong() } } }
lgpl-3.0
5a0c98f847122fd3f159d531547454bb
28.813411
138
0.532711
4.686526
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/geometry/ElementGeometryTable.kt
1
1654
package de.westnordost.streetcomplete.data.osm.geometry object ElementGeometryTable { const val NAME = "elements_geometry" object Columns { const val ELEMENT_ID = "element_id" const val ELEMENT_TYPE = "element_type" const val GEOMETRY_POLYGONS = "geometry_polygons" const val GEOMETRY_POLYLINES = "geometry_polylines" const val CENTER_LATITUDE = "latitude" const val CENTER_LONGITUDE = "longitude" const val MIN_LATITUDE = "min_lat" const val MIN_LONGITUDE = "min_lon" const val MAX_LATITUDE = "max_lat" const val MAX_LONGITUDE = "max_lon" } const val CREATE = """ CREATE TABLE $NAME ( ${Columns.ELEMENT_TYPE} varchar(255) NOT NULL, ${Columns.ELEMENT_ID} int NOT NULL, ${Columns.GEOMETRY_POLYLINES} blob, ${Columns.GEOMETRY_POLYGONS} blob, ${Columns.CENTER_LATITUDE} double NOT NULL, ${Columns.CENTER_LONGITUDE} double NOT NULL, ${Columns.MIN_LATITUDE} double NOT NULL, ${Columns.MAX_LATITUDE} double NOT NULL, ${Columns.MIN_LONGITUDE} double NOT NULL, ${Columns.MAX_LONGITUDE} double NOT NULL, CONSTRAINT primary_key PRIMARY KEY ( ${Columns.ELEMENT_TYPE}, ${Columns.ELEMENT_ID} ) );""" const val SPATIAL_INDEX_CREATE = """ CREATE INDEX elements_geometry_bounds_index ON $NAME ( ${Columns.MIN_LATITUDE}, ${Columns.MAX_LATITUDE}, ${Columns.MIN_LONGITUDE}, ${Columns.MAX_LONGITUDE} ); """ }
gpl-3.0
d964e9e03d217550e50e8e7f0b587261
34.956522
62
0.584039
4.318538
false
false
false
false
SimonVT/cathode
cathode-provider/src/main/java/net/simonvt/cathode/provider/helper/ListDatabaseHelper.kt
1
2915
/* * Copyright (C) 2015 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.provider.helper import android.content.ContentValues import android.content.Context import net.simonvt.cathode.api.entity.CustomList import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.ListsColumns import net.simonvt.cathode.provider.ProviderSchematic.Lists import net.simonvt.cathode.provider.query import javax.inject.Inject import javax.inject.Singleton @Singleton class ListDatabaseHelper @Inject constructor( private val context: Context ) { fun getId(traktId: Long): Long { val c = context.contentResolver.query( Lists.LISTS, arrayOf(ListsColumns.ID), ListsColumns.TRAKT_ID + "=?", arrayOf(traktId.toString()) ) val id = if (!c.moveToFirst()) -1L else c.getLong(ListsColumns.ID) c.close() return id } fun getTraktId(listId: Long): Long { val c = context.contentResolver.query(Lists.withId(listId), arrayOf(ListsColumns.TRAKT_ID)) val traktId = if (!c.moveToFirst()) -1L else c.getLong(ListsColumns.TRAKT_ID) c.close() return traktId } fun updateOrInsert(list: CustomList): Long { val traktId = list.ids.trakt!! var listId = getId(traktId) if (listId == -1L) { listId = Lists.getId(context.contentResolver.insert(Lists.LISTS, getValues(list))!!) } else { update(listId, list) } return listId } fun update(listId: Long, list: CustomList) { context.contentResolver.update(Lists.withId(listId), getValues(list), null, null) } private fun getValues(list: CustomList): ContentValues { val values = ContentValues() values.put(ListsColumns.NAME, list.name) values.put(ListsColumns.DESCRIPTION, list.description) values.put(ListsColumns.PRIVACY, list.privacy.toString()) values.put(ListsColumns.DISPLAY_NUMBERS, list.display_numbers) values.put(ListsColumns.ALLOW_COMMENTS, list.allow_comments) values.put(ListsColumns.SORT_BY, list.sort_by.toString()) values.put(ListsColumns.SORT_ORIENTATION, list.sort_how.toString()) values.put(ListsColumns.UPDATED_AT, list.updated_at?.timeInMillis) values.put(ListsColumns.LIKES, list.likes) values.put(ListsColumns.SLUG, list.ids.slug) values.put(ListsColumns.TRAKT_ID, list.ids.trakt) return values } }
apache-2.0
ce76fa071fb108a4e1041277cb0f9077
32.505747
95
0.730703
3.85582
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/button/ButtonBlockView.kt
1
2760
package io.rover.sdk.experiences.ui.blocks.button import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.graphics.Canvas import android.os.Build import androidx.appcompat.widget.AppCompatTextView import android.util.AttributeSet import io.rover.sdk.experiences.logging.log import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView import io.rover.sdk.experiences.ui.concerns.ViewModelBinding import io.rover.sdk.experiences.ui.blocks.concerns.ViewComposition import io.rover.sdk.experiences.ui.blocks.concerns.background.ViewBackground import io.rover.sdk.experiences.ui.blocks.concerns.border.ViewBorder import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutableView import io.rover.sdk.experiences.ui.blocks.concerns.layout.ViewBlock import io.rover.sdk.experiences.ui.blocks.concerns.text.AndroidRichTextToSpannedTransformer import io.rover.sdk.experiences.ui.blocks.concerns.text.ViewText // API compatibility is managed at runtime in a way that Android lint's static analysis is not able // to pick up. @TargetApi(Build.VERSION_CODES.LOLLIPOP) @SuppressLint("NewApi") internal class ButtonBlockView : AppCompatTextView, LayoutableView<ButtonBlockViewModelInterface> { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override var viewModelBinding: MeasuredBindableView.Binding<ButtonBlockViewModelInterface>? by ViewModelBinding { binding, _ -> viewBackground.viewModelBinding = binding viewBorder.viewModelBinding = binding viewBlock.viewModelBinding = binding viewBackground.viewModelBinding = binding viewText.viewModelBinding = binding } private val viewComposition = ViewComposition() private val viewBackground = ViewBackground(this) private val viewBorder = ViewBorder(this, viewComposition) private val viewBlock = ViewBlock(this) private val viewText = ViewText(this, AndroidRichTextToSpannedTransformer()) override fun draw(canvas: Canvas) { viewComposition.beforeDraw(canvas) super.draw(canvas) viewComposition.afterDraw(canvas) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) viewComposition.onSizeChanged(w, h, oldw, oldh) } @SuppressLint("MissingSuperCall") override fun requestLayout() { // log.v("Tried to invalidate layout. Inhibited.") } override fun forceLayout() { log.v("Tried to forcefully invalidate layout. Inhibited.") } }
apache-2.0
729fec4a114f5eda7f304441bfe5574f
42.809524
131
0.772826
4.339623
false
false
false
false
mgolokhov/dodroid
app/src/main/java/doit/study/droid/quiz/ui/QuizPageFragment.kt
1
10654
package doit.study.droid.quiz.ui import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.StringRes import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import doit.study.droid.R import doit.study.droid.app.App import doit.study.droid.databinding.AnswerItemBinding import doit.study.droid.databinding.FragmentQuizPageBinding import doit.study.droid.utils.AnalyticsData import doit.study.droid.utils.SoundPlayer import doit.study.droid.utils.lazyAndroid import doit.study.droid.utils.showToastFailure import doit.study.droid.utils.showToastSuccess import javax.inject.Inject import timber.log.Timber class QuizPageFragment : Fragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var soundPlayer: SoundPlayer private lateinit var viewDataBinding: FragmentQuizPageBinding private val viewModel: QuizPageViewModel by lazyAndroid { ViewModelProviders .of(requireParentFragment(), viewModelFactory) .get(pagePosition.toString(), QuizPageViewModel::class.java) } private val viewModelMain: QuizMainViewModel by lazyAndroid { ViewModelProviders .of(parentFragment!!, viewModelFactory) .get(QuizMainViewModel::class.java) } private val pagePosition: Int by lazyAndroid { arguments!!.getInt(ARG_POSITION_IN_QUIZ_KEY, 0) } override fun onCreate(savedInstanceState: Bundle?) { App.dagger.inject(this) super.onCreate(savedInstanceState) setHasOptionsMenu(true) viewModelMain } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun onDestroy() { super.onDestroy() Timber.d("onDestroy ${this.hashCode()}") } override fun onDestroyView() { super.onDestroyView() Timber.d("onDestroyView ${this.hashCode()}") } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewDataBinding = FragmentQuizPageBinding.inflate(inflater, container, false) return viewDataBinding.root } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { super.onCreateOptionsMenu(menu, menuInflater) menuInflater.inflate(R.menu.fragment_question, menu) } override fun onOptionsItemSelected(menuItem: MenuItem): Boolean { when (menuItem.itemId) { R.id.doc_reference -> { openDocumentation() return true } R.id.action_settings -> { findNavController().navigate(R.id.settings_fragment_dest) return true } else -> return super.onOptionsItemSelected(menuItem) } } private fun openDocumentation() { if (viewModel.getDocRef().isEmpty()) Toast.makeText( activity, getString(R.string.not_yet_for_this_question), Toast.LENGTH_SHORT ).show() else { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(viewModel.getDocRef()) startActivity(intent) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Timber.d("onActivityCreated, page: $pagePosition; ${this.hashCode()}") viewModelMain.items.observe(viewLifecycleOwner, Observer { if (it.isNotEmpty()) { // setting every config change? Timber.d("pager pagePosition $pagePosition for items size ${it.size}") viewModel.setItem(it[pagePosition]) setupQuestion() setupAnswerVariants() setupCommitButton() setupThumbUpButton() setupThumbDownButton() setupToastFeedbackForEvaluation() setupToastFeedbackForAnswer() setupSoundFeedbackForAnswer() setupTitle() } }) } private fun setupTitle() { viewModel.lockInteraction.observe(viewLifecycleOwner, Observer { Timber.d("try to update title") viewModelMain.refreshUi() }) } private fun setupToastFeedbackForEvaluation() { viewModel.showToastForEvaluationEvent.observe(viewLifecycleOwner, Observer { event -> event.getContentIfNotHandled()?.let { showFeedbackToast(it) } }) } private fun setupQuestion() { viewModel.item.observe(viewLifecycleOwner, Observer { quizItem -> Timber.d("setupQuestion[$pagePosition]: $quizItem") quizItem?.let { viewDataBinding.questionTextView.text = quizItem.questionText Timber.d("setupQuestion ${viewDataBinding.questionTextView.text} ${this.hashCode()} ${viewDataBinding.questionTextView.hashCode()}") } }) } private fun setupAnswerVariants() { viewModel.item.observe(viewLifecycleOwner, Observer { quizItem -> Timber.d("setupAnswerVariants[$pagePosition]: $quizItem") quizItem?.let { val layoutInflater = LayoutInflater.from(view?.context) viewDataBinding.containerAnswerVariantsLinearLayout.removeAllViews() quizItem.answerVariants.forEach { variant -> val answerViewVariant = AnswerItemBinding.inflate(layoutInflater, viewDataBinding.containerAnswerVariantsLinearLayout, false) answerViewVariant.viewmodel = viewModel answerViewVariant.answerVariantItem = variant answerViewVariant.executePendingBindings() viewDataBinding.containerAnswerVariantsLinearLayout.addView(answerViewVariant.root) } } }) viewModel.lockInteraction.observe(viewLifecycleOwner, Observer { for (i in 0 until viewDataBinding.containerAnswerVariantsLinearLayout.childCount) { viewDataBinding.containerAnswerVariantsLinearLayout.getChildAt(i)?.apply { isEnabled = false } } }) } private fun setupCommitButton() { viewModel.commitButtonState.observe(viewLifecycleOwner, Observer { viewDataBinding.commitFabButton.setImageDrawable(resources.getDrawable(it)) }) viewDataBinding.commitFabButton.setOnClickListener { viewModel.checkAnswer() } viewModel.lockInteraction.observe(viewLifecycleOwner, Observer { viewDataBinding.commitFabButton.isEnabled = false }) } private fun setupThumbUpButton() { viewDataBinding.thumbUpImageButton.setOnClickListener { viewModel.handleThumbUpButton( AnalyticsData( category = getString(R.string.report_because), action = getString(R.string.like), label = viewDataBinding.questionTextView.text.toString() )) } } private fun setupThumbDownButton() { viewDataBinding.thumbDownImageButton.setOnClickListener { // TODO: code smells - decision should be in viewModel // hrr, ping pong with long flow based on onActivityResult if (!viewModel.isEvaluated()) { val dislikeDialog = FeedbackDialogFragment.newInstance(viewDataBinding.questionTextView.text.toString()) dislikeDialog.setTargetFragment(this, REPORT_DIALOG_REQUEST_CODE) dislikeDialog.show(fragmentManager!!, REPORT_DIALOG_TAG) } else { showFeedbackToast(R.string.already_voted) } } } private fun setupSoundFeedbackForAnswer() { viewModel.playSoundEvent.observe(viewLifecycleOwner, Observer { it.getContentIfNotHandled()?.let { fileName -> soundPlayer.play(lifecycle, fileName) } }) } private fun setupToastFeedbackForAnswer() { viewModel.showToastSuccessEvent.observe(viewLifecycleOwner, Observer { it.getContentIfNotHandled()?.let { showToastSuccess(it) } }) viewModel.showToastFailureEvent.observe(viewLifecycleOwner, Observer { it.getContentIfNotHandled()?.let { showToastFailure(it) } }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode != Activity.RESULT_OK) return if (requestCode == REPORT_DIALOG_REQUEST_CODE) { data?.let { val label = viewDataBinding.questionTextView.text.toString() + data.getStringExtra(FeedbackDialogFragment.EXTRA_CAUSE) viewModel.handleThumbDownButton( AnalyticsData( category = getString(R.string.report_because), action = getString(R.string.dislike), label = label )) } } } private fun showFeedbackToast(@StringRes message: Int) { val mes = resources.getString(message) Toast.makeText(activity, mes, Toast.LENGTH_SHORT).apply { setGravity(Gravity.CENTER, 0, 0) show() } } companion object { private const val REPORT_DIALOG_REQUEST_CODE = 0 private const val REPORT_DIALOG_TAG = "fragment_feedback_dialog" private const val ARG_POSITION_IN_QUIZ_KEY = "arg_position_in_quiz_key" fun newInstance(position: Int): QuizPageFragment { return QuizPageFragment().apply { arguments = Bundle().apply { putInt(ARG_POSITION_IN_QUIZ_KEY, position) } } } } } const val QUIZ_QUESTION_ITEM_TYPE = "quiz_question_item_type"
mit
0b845aa888282ee2e9034327950ed44e
36.382456
148
0.631594
5.237955
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/fragment/BaseLoadMoreRecycleViewFragment.kt
1
5120
package me.ykrank.s1next.view.fragment import android.os.Bundle import android.text.TextUtils import android.view.* import androidx.annotation.CallSuper import com.github.ykrank.androidtools.ui.LibBaseLoadMoreRecycleViewFragment import com.github.ykrank.androidtools.ui.internal.LoadingViewModelBindingDelegate import io.reactivex.Single import me.ykrank.s1next.App import me.ykrank.s1next.R import me.ykrank.s1next.data.User import me.ykrank.s1next.data.api.ApiCacheProvider import me.ykrank.s1next.data.api.ApiFlatTransformer import me.ykrank.s1next.data.api.S1Service import me.ykrank.s1next.data.api.UserValidator import me.ykrank.s1next.data.api.app.model.AppResult import me.ykrank.s1next.data.api.model.Result import me.ykrank.s1next.data.pref.DownloadPreferencesManager import me.ykrank.s1next.databinding.FragmentBaseBinding import me.ykrank.s1next.databinding.FragmentBaseCardViewContainerBinding import me.ykrank.s1next.view.internal.LoadingViewModelBindingDelegateBaseCardViewContainerImpl import me.ykrank.s1next.view.internal.LoadingViewModelBindingDelegateBaseImpl /** * Created by ykrank on 2016/11/12 0012. */ abstract class BaseLoadMoreRecycleViewFragment<D> : LibBaseLoadMoreRecycleViewFragment<D>() { internal lateinit var mUserValidator: UserValidator internal lateinit var mS1Service: S1Service internal lateinit var apiCacheProvider: ApiCacheProvider internal lateinit var mDownloadPrefManager: DownloadPreferencesManager internal lateinit var mUser: User @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mUserValidator = App.appComponent.userValidator mS1Service = App.appComponent.s1Service apiCacheProvider = App.appComponent.apiCacheProvider mDownloadPrefManager = App.preAppComponent.downloadPreferencesManager mUser = App.appComponent.user setHasOptionsMenu(true) } @CallSuper override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.fragment_base, menu) } @CallSuper override fun onPrepareOptionsMenu(menu: Menu) { // Disables the refresh menu when loading data. menu?.findItem(R.id.menu_refresh)?.isEnabled = !isLoading } @CallSuper override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item?.itemId) { R.id.menu_refresh -> { startSwipeRefresh() return true } else -> return super.onOptionsItemSelected(item) } } /** * Subclass can override this in order to provider different * layout for [LoadingViewModelBindingDelegate]. * run when [.onCreateView] */ override fun getLoadingViewModelBindingDelegateImpl(inflater: LayoutInflater, container: ViewGroup?): LoadingViewModelBindingDelegate { if (isCardViewContainer) { val binding = FragmentBaseCardViewContainerBinding.inflate(inflater, container, false) return LoadingViewModelBindingDelegateBaseCardViewContainerImpl(binding) } else { val binding = FragmentBaseBinding.inflate(inflater, container, false) return LoadingViewModelBindingDelegateBaseImpl(binding) } } protected abstract fun getPageSourceObservable(pageNum: Int): Single<D> override fun getLibPageSourceObservable(pageNum: Int): Single<D> = getPageSourceObservable(pageNum) .compose(ApiFlatTransformer.apiErrorTransformer()) /** * Called when a data was emitted from [.getSourceObservable]. * * * Actually this method was only called once during loading (if no error occurs) * because we only emit data once from [.getSourceObservable]. */ @CallSuper override fun onNext(data: D) { super.onNext(data) mUserValidator.validateIntercept(data) } /** * A helper method consumes [Result]. * * * Sometimes we cannot get data if we have logged out or * have no permission to access this data. * This method is only used during [.onNext]. * * @param result The data's result we get. */ protected fun consumeResult(result: Result?) { if (isAdded && userVisibleHint) { if (result != null) { val message = result.message if (!TextUtils.isEmpty(message)) { showRetrySnackbar(message) } } else { showRetrySnackbar(R.string.message_server_connect_error) } } } protected fun consumeAppResult(result: AppResult?) { if (isAdded && userVisibleHint) { if (result != null) { val message = result.message if (!TextUtils.isEmpty(message)) { showRetrySnackbar(message!!) } } else { showRetrySnackbar(R.string.message_server_connect_error) } } } }
apache-2.0
6d1c37d80411c851de2db5490a9d0b72
35.056338
113
0.680469
4.684355
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/PersistenceModule.kt
1
1328
package voice.data.repo.internals import android.content.Context import androidx.room.Room import androidx.room.migration.Migration import com.squareup.anvil.annotations.ContributesTo import dagger.Module import dagger.Provides import voice.common.AppScope import voice.data.repo.internals.dao.BookContentDao import voice.data.repo.internals.dao.BookmarkDao import voice.data.repo.internals.dao.ChapterDao import voice.data.repo.internals.dao.LegacyBookDao import voice.data.repo.internals.dao.RecentBookSearchDao import javax.inject.Singleton @Module @ContributesTo(AppScope::class) object PersistenceModule { @Provides fun chapterDao(appDb: AppDb): ChapterDao = appDb.chapterDao() @Provides fun bookContentDao(appDb: AppDb): BookContentDao = appDb.bookContentDao() @Provides fun bookmarkDao(appDb: AppDb): BookmarkDao = appDb.bookmarkDao() @Provides fun legacyBookDao(appDb: AppDb): LegacyBookDao = appDb.legacyBookDao() @Provides fun recentBookSearchDao(appDb: AppDb): RecentBookSearchDao = appDb.recentBookSearchDao() @Provides @Singleton fun appDb( context: Context, migrations: Set<@JvmSuppressWildcards Migration>, ): AppDb { return Room.databaseBuilder(context, AppDb::class.java, AppDb.DATABASE_NAME) .addMigrations(*migrations.toTypedArray()) .build() } }
gpl-3.0
844711a18db2ad54a4d2882fde219c75
27.869565
90
0.787651
3.905882
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/screens/suggested/SuggestedPresenter.kt
1
5929
package com.simplecity.amp_library.ui.screens.suggested import com.simplecity.amp_library.data.Repository.PlaylistsRepository import com.simplecity.amp_library.data.Repository.SongsRepository import com.simplecity.amp_library.model.Album import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.model.Song import com.simplecity.amp_library.ui.common.Presenter import com.simplecity.amp_library.ui.screens.album.menu.AlbumMenuPresenter import com.simplecity.amp_library.ui.screens.songs.menu.SongMenuPresenter import com.simplecity.amp_library.ui.screens.suggested.SuggestedContract.View import com.simplecity.amp_library.utils.ComparisonUtils import com.simplecity.amp_library.utils.LogUtils import com.simplecity.amp_library.utils.Operators import com.simplecity.amp_library.utils.extensions.getSongsSingle import com.simplecity.amp_library.utils.menu.album.AlbumsMenuCallbacks import com.simplecity.amp_library.utils.menu.song.SongsMenuCallbacks import com.simplecity.amp_library.utils.playlists.FavoritesPlaylistManager import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Function4 import io.reactivex.schedulers.Schedulers import javax.inject.Inject class SuggestedPresenter @Inject constructor( private val songsRepository: SongsRepository, private val playlistRepository: PlaylistsRepository, private val favoritesPlaylistManager: FavoritesPlaylistManager, private val songMenuPresenter: SongMenuPresenter, private val albumMenuPresenter: AlbumMenuPresenter ) : Presenter<SuggestedContract.View>(), SuggestedContract.Presenter, SongsMenuCallbacks by songMenuPresenter, AlbumsMenuCallbacks by albumMenuPresenter { override fun bindView(view: View) { super.bindView(view) songMenuPresenter.bindView(view) albumMenuPresenter.bindView(view) } override fun unbindView(view: View) { super.unbindView(view) songMenuPresenter.unbindView(view) albumMenuPresenter.unbindView(view) } data class SuggestedData( val mostPlayedPlaylist: Playlist, val mostPlayedSongs: List<Song>, val recentlyPlayedPlaylist: Playlist, val recentlyPlayedAlbums: List<Album>, val favoriteSongsPlaylist: Playlist, val favoriteSongs: List<Song>, val recentlyAddedAlbumsPlaylist: Playlist, val recentlyAddedAlbums: List<Album> ) override fun loadData() { val mostPlayedPlaylist = playlistRepository.getMostPlayedPlaylist() val recentlyPlayedPlaylist = playlistRepository.getRecentlyPlayedPlaylist() val recentlyAddedAlbumsPlaylist = playlistRepository.getRecentlyAddedPlaylist() lateinit var favoriteSongsPlaylist: Playlist val mostPlayedSongs = songsRepository.getSongs(mostPlayedPlaylist) .take(20) val recentlyPlayedAlbums = songsRepository.getSongs(recentlyPlayedPlaylist) .flatMap { songs -> Observable.just(Operators.songsToAlbums(songs)) } .flatMapSingle { albums -> Observable.fromIterable(albums) .sorted { a, b -> ComparisonUtils.compareLong(b.lastPlayed, a.lastPlayed) } .concatMapSingle { album -> album.getSongsSingle(songsRepository) .map { songs -> album.numSongs = songs.size album } .filter { a -> a.numSongs > 0 } .toSingle() } .sorted { a, b -> ComparisonUtils.compareLong(b.lastPlayed, a.lastPlayed) } .take(6) .toList() } val favoriteSongs = favoritesPlaylistManager.getFavoritesPlaylist() .flatMapObservable { playlist -> favoriteSongsPlaylist = playlist songsRepository.getSongs(favoriteSongsPlaylist) .take(20) } val recentlyAddedAlbums = songsRepository.getSongs(recentlyAddedAlbumsPlaylist) .flatMap { songs -> Observable.just(Operators.songsToAlbums(songs)) } .flatMapSingle { source -> Observable.fromIterable(source) .sorted { a, b -> ComparisonUtils.compareLong(b.dateAdded, a.dateAdded) } .take(10) .toList() } addDisposable( Observable.combineLatest(mostPlayedSongs, recentlyPlayedAlbums, favoriteSongs, recentlyAddedAlbums, Function4<List<Song>, List<Album>, List<Song>, List<Album>, SuggestedData> { mostPlayedSongs, recentlyPlayedAlbums, favoriteSongs, recentlyAddedAlbums -> SuggestedData( mostPlayedPlaylist, mostPlayedSongs, recentlyPlayedPlaylist, recentlyPlayedAlbums, favoriteSongsPlaylist, favoriteSongs, recentlyAddedAlbumsPlaylist, recentlyAddedAlbums ) }) .subscribe( { suggestedData -> view?.setData(suggestedData) }, { error -> LogUtils.logException(TAG, "Failed to load data", error) } ) ) } override fun <T> transform(src: Single<List<T>>, dst: (List<T>) -> Unit) { addDisposable( src .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( { items -> dst(items) }, { error -> LogUtils.logException(SongMenuPresenter.TAG, "Failed to transform src single", error) } ) ) } companion object { private const val TAG = "SuggestedPresenter" } }
gpl-3.0
3de870acfc09efffd8d84846275d69b3
42.602941
169
0.655422
5.011834
false
false
false
false
NextFaze/dev-fun
devfun-gradle-plugin/kotlin-plugin-1251/src/main/kotlin/com/nextfaze/devfun/gradle/plugin/KotlinGradlePlugin.kt
1
1048
package com.nextfaze.devfun.gradle.plugin import com.google.auto.service.AutoService import org.gradle.api.Project import org.gradle.api.tasks.SourceSet import org.gradle.api.tasks.compile.AbstractCompile import org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin import org.jetbrains.kotlin.gradle.plugin.SubpluginOption @AutoService(KotlinGradleSubplugin::class) class DevFunKotlinGradlePlugin : KotlinGradleSubplugin<AbstractCompile> { override fun getCompilerPluginId() = KotlinGradlePlugin.compilerPluginId override fun getArtifactName() = KotlinGradlePlugin.artifactName override fun getGroupName() = KotlinGradlePlugin.groupName override fun isApplicable(project: Project, task: AbstractCompile) = KotlinGradlePlugin.isApplicable(project, task) override fun apply( project: Project, kotlinCompile: AbstractCompile, javaCompile: AbstractCompile, variantData: Any?, androidProjectHandler: Any?, javaSourceSet: SourceSet? ): List<SubpluginOption> = emptyList() }
apache-2.0
6c3363b2e2ebb850d04c0f370468b3a7
39.307692
119
0.78626
4.637168
false
false
false
false
Microsoft/vso-intellij
client/backend/src/test/kotlin/com/microsoft/tfs/ServerWorkspaceClientTests.kt
1
1971
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.tfs import com.microsoft.tfs.jni.FileSystemUtils import com.microsoft.tfs.model.host.TfsLocalPath import com.microsoft.tfs.model.host.TfsServerStatusType import com.microsoft.tfs.tests.TfsClientTestFixture import com.microsoft.tfs.tests.cloneTestRepository import com.microsoft.tfs.tests.createClient import org.junit.Assert.* import org.junit.Test import java.nio.file.Path class ServerWorkspaceClientTests : TfsClientTestFixture() { override fun cloneRepository(): Path = cloneTestRepository(true) private val fileSystem = FileSystemUtils.getInstance() private fun isReadOnly(path: Path): Boolean = fileSystem.getAttributes(path.toFile()).isReadOnly @Test fun readOnlyFilesShouldBeClonedByDefault() { val filePath = workspacePath.resolve("readme.txt") assertTrue(isReadOnly(filePath)) } // @Test for manual run only, because concurrent checkout in tests is not supported fun readOnlyFlagShouldBeClearedOnCheckout() { val client = createClient(testLifetime) val filePath = workspacePath.resolve("readme.txt") client.checkoutFilesForEdit(listOf(TfsLocalPath(filePath.toString())), false) assertFalse(isReadOnly(filePath)) } // @Test for manual run only, because concurrent checkout in tests is not supported fun getPendingChangesShouldReturnACheckedOutFile() { val client = createClient(testLifetime) val filePath = workspacePath.resolve("readme.txt") val paths = listOf(TfsLocalPath(filePath.toString())) client.checkoutFilesForEdit(paths, false) val pendingChanges = toPendingChanges(client.status(paths).single()) val change = pendingChanges.single() val types = change.changeTypes assertEquals(TfsServerStatusType.EDIT, types.single()) } }
mit
b9034e1c24d1fa8aaced2475b1be91f3
37.666667
87
0.742263
4.626761
false
true
false
false
michaelgallacher/intellij-community
platform/platform-impl/src/org/jetbrains/io/bufferToChars.kt
17
1878
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.io import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBufUtil import io.netty.util.CharsetUtil import java.nio.ByteBuffer import java.nio.CharBuffer import java.nio.charset.CharacterCodingException import java.nio.charset.CharsetDecoder fun ByteBuf.readIntoCharBuffer(byteCount: Int = readableBytes(), charBuffer: CharBuffer) { val decoder = CharsetUtil.decoder(CharsetUtil.UTF_8) if (nioBufferCount() == 1) { decodeString(decoder, internalNioBuffer(readerIndex(), byteCount), charBuffer) } else { val buffer = alloc().heapBuffer(byteCount) try { buffer.writeBytes(this, readerIndex(), byteCount) decodeString(decoder, buffer.internalNioBuffer(0, byteCount), charBuffer) } finally { buffer.release() } } } private fun decodeString(decoder: CharsetDecoder, src: ByteBuffer, dst: CharBuffer) { try { var cr = decoder.decode(src, dst, true) if (!cr.isUnderflow) { cr.throwException() } cr = decoder.flush(dst) if (!cr.isUnderflow) { cr.throwException() } } catch (x: CharacterCodingException) { throw IllegalStateException(x) } } fun writeIntAsAscii(value: Int, buffer: ByteBuf) { ByteBufUtil.writeAscii(buffer, StringBuilder().append(value)) }
apache-2.0
8f67b8ae4b6fbde074c57a86adc3a1ec
29.306452
90
0.724707
3.945378
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/util/AutoExit.kt
1
2085
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.util import javafx.application.Platform import javafx.stage.Stage /** * My application may close the last remaining JavaFX stage, and then try to create another one. * This class ensures that JavaFX does not terminate when it shouldn't */ object AutoExit { val log = false private var enabled = true init { Platform.setImplicitExit(false) } var resourceCounter = 0 fun disable() { Platform.setImplicitExit(true) enabled = false } fun inc(message: String) { privateInc() if (log) printLog("inc $message $resourceCounter") } private fun privateInc() { resourceCounter++ } fun dec(message: String) { privateDec() if (log) printLog("dec $message $resourceCounter") } private fun privateDec() { resourceCounter-- if (resourceCounter == 0 && enabled) { Platform.exit() // I need this when using Swing from within JavaFX. JEditTerm uses Swing. System.exit(0) } } fun show(stage: Stage) { privateInc() stage.show() if (log) printLog("Show $resourceCounter $stage") stage.setOnHiding { privateDec() if (log) printLog("Hide $resourceCounter $stage") } } fun printLog(message: String) { println(message) } }
gpl-3.0
240d1a96c2869b14cda70d99a882f613
24.740741
96
0.656595
4.298969
false
false
false
false
renard314/textfairy
app/src/main/java/com/renard/ocr/documents/creation/PdfDocumentWrapper.kt
1
2169
package com.renard.ocr.documents.creation import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.ParcelFileDescriptor import android.util.Log import com.googlecode.leptonica.android.Pix import com.googlecode.leptonica.android.ReadFile import com.renard.ocr.documents.creation.ocr.OcrPdfActivity import com.shockwave.pdfium.PdfiumCore import java.io.Closeable import kotlin.math.max class PdfDocumentWrapper(context: Context, fd: ParcelFileDescriptor) : Closeable, Iterable<Pix> { private val pdfiumCore = PdfiumCore(context) private val pdfDocument = pdfiumCore.newDocument(fd) fun getPageAsBitmap(pageNumber: Int, targetWidth: Int = -1, targetHeight: Int = -1): Bitmap { pdfiumCore.openPage(pdfDocument, pageNumber) val pageHeight = pdfiumCore.getPageHeightPoint(pdfDocument, pageNumber) * (200 / 72) val pageWidth = pdfiumCore.getPageWidthPoint(pdfDocument, pageNumber) * (200 / 72) val scaleX = pageWidth.toFloat() / if(targetWidth==-1) pageWidth else targetWidth val scaleY = pageHeight.toFloat() / if(targetWidth==-1) pageHeight else targetHeight val scale = max(scaleX, scaleY) val width = pageWidth/scale val height= pageHeight/scale val bitmap = Bitmap.createBitmap(width.toInt(), height.toInt(), Bitmap.Config.ARGB_8888) Log.d(OcrPdfActivity::class.java.simpleName, "renderPageBitmap($pageNumber)") pdfiumCore.renderPageBitmap(pdfDocument, bitmap, pageNumber, 0, 0, width.toInt(), height.toInt()) return bitmap } fun getPage(pageNumber: Int): Pix { val bitmap = getPageAsBitmap(pageNumber) val p = ReadFile.readBitmap(bitmap) bitmap.recycle() return p } fun getPageCount() = pdfiumCore.getPageCount(pdfDocument) override fun close() { pdfiumCore.closeDocument(pdfDocument) } override fun iterator(): Iterator<Pix> { return object : Iterator<Pix> { private var i = 0 override fun hasNext() = i < getPageCount() - 1 override fun next() = getPage(i).also { i += 1 } } } }
apache-2.0
38377ecd36af8aa23478c71f74800134
36.396552
105
0.700323
3.987132
false
false
false
false
nemerosa/ontrack
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/webhooks/GQLTypeWebhook.kt
1
3379
package net.nemerosa.ontrack.extension.notifications.webhooks import graphql.Scalars.GraphQLInt import graphql.Scalars.GraphQLString import graphql.schema.GraphQLArgument import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.booleanField import net.nemerosa.ontrack.graphql.support.getTypeDescription import net.nemerosa.ontrack.graphql.support.pagination.GQLPaginatedListFactory import net.nemerosa.ontrack.graphql.support.stringField import net.nemerosa.ontrack.model.annotations.getPropertyDescription import org.springframework.stereotype.Component @Component class GQLTypeWebhook( private val gqlInputWebhookExchangeFilter: GQLInputWebhookExchangeFilter, private val gqlTypeWebhookExchange: GQLTypeWebhookExchange, private val gqlPaginatedListFactory: GQLPaginatedListFactory, private val webhookExchangeService: WebhookExchangeService, ) : GQLType { override fun getTypeName(): String = Webhook::class.java.simpleName override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description(getTypeDescription(Webhook::class)) .stringField(Webhook::name) .booleanField(Webhook::enabled) .stringField(Webhook::url) .field { it.name("timeoutSeconds") .description(getPropertyDescription(Webhook::timeout)) .type(GraphQLInt) .dataFetcher { env -> val webhook: Webhook = env.getSource() webhook.timeout.toSeconds() } } .field { it.name("authenticationType") .description("Webhook authentication") .type(GraphQLString) .dataFetcher { env -> val webhook: Webhook = env.getSource() webhook.authentication.type } } .field( gqlPaginatedListFactory.createPaginatedField<Webhook, WebhookExchange>( cache = cache, fieldName = "exchanges", fieldDescription = "Exchanges for this webhook", itemType = gqlTypeWebhookExchange, arguments = listOf( GraphQLArgument.newArgument() .name(ARG_EXCHANGES_FILTER) .description("Filter for the exchanges") .type(gqlInputWebhookExchangeFilter.typeRef) .build() ), itemPaginatedListProvider = { env, source, offset, size -> val argFilter = gqlInputWebhookExchangeFilter.convert(env.getArgument(ARG_EXCHANGES_FILTER)) ?: WebhookExchangeFilter() val filter = argFilter.withPagination(offset, size).withWebhook(source.name) webhookExchangeService.exchanges(filter) } ) ) .build() companion object { private const val ARG_EXCHANGES_FILTER = "filter" } }
mit
ef8649f228bb543493d79aabf8b5c294
42.896104
116
0.605209
5.897033
false
false
false
false
neo4j-contrib/neo4j-apoc-procedures
extended/src/test/kotlin/apoc/nlp/NodeMatcherTest.kt
1
3148
package apoc.nlp import apoc.result.VirtualNode import junit.framework.Assert.assertFalse import junit.framework.Assert.assertTrue import org.hamcrest.StringDescription import org.junit.Test import org.neo4j.graphdb.Label class NodeMatcherTest { @Test fun `different labels`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, properties) assertFalse(matcher.matches(VirtualNode(arrayOf(Label { "Human" }), properties))) } @Test fun `different properties`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, properties) assertFalse(matcher.matches(VirtualNode(labels.toTypedArray(), mapOf("id" to 5678L)))) } @Test fun `different labels and properties`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, properties) assertFalse(matcher.matches(VirtualNode(arrayOf(Label { "Human" }), mapOf("id" to 5678L)))) } @Test fun `same labels and properties`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, properties) assertTrue(matcher.matches(VirtualNode(labels.toTypedArray(), properties))) } @Test fun `no labels in actual`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(listOf(), properties) assertFalse(matcher.matches(VirtualNode(labels.toTypedArray(), properties))) } @Test fun `no labels in expected`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, properties) assertFalse(matcher.matches(VirtualNode(arrayOf(), properties))) } @Test fun `no labels in actual and expected`() { val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(listOf(), properties) val description = StringDescription() matcher.describeTo(description) assertTrue(matcher.matches(VirtualNode(arrayOf(), properties))) } @Test fun `no properties in actual`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, mapOf()) assertFalse(matcher.matches(VirtualNode(labels.toTypedArray(), properties))) } @Test fun `no properties in expected`() { val labels = listOf(Label { "Person" }) val properties = mapOf("id" to 1234L) val matcher = NodeMatcher(labels, properties) assertFalse(matcher.matches(VirtualNode(labels.toTypedArray(), mapOf()))) } @Test fun `no properties in expected and actual`() { val labels = listOf(Label { "Person" }) val matcher = NodeMatcher(labels, mapOf()) assertTrue(matcher.matches(VirtualNode(labels.toTypedArray(), mapOf()))) } }
apache-2.0
d721bebe488024c683bec5a375f6cd9c
29.563107
99
0.637865
4.336088
false
true
false
false
aglne/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/view/ProjectController.kt
3
27018
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.view import com.google.common.eventbus.Subscribe import com.mycollab.common.domain.Tag import com.mycollab.core.MyCollabException import com.mycollab.core.ResourceNotFoundException import com.mycollab.core.utils.StringUtils import com.mycollab.db.arguments.NumberSearchField import com.mycollab.db.arguments.SetSearchField import com.mycollab.module.page.domain.Page import com.mycollab.module.project.CurrentProjectVariables import com.mycollab.module.project.ProjectMemberStatusConstants import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.dao.TicketKeyMapper import com.mycollab.module.project.domain.* import com.mycollab.module.project.domain.criteria.* import com.mycollab.module.project.event.* import com.mycollab.module.project.service.BugService import com.mycollab.module.project.service.TaskService import com.mycollab.module.project.service.RiskService import com.mycollab.module.project.view.bug.BugAddPresenter import com.mycollab.module.project.view.bug.BugReadPresenter import com.mycollab.module.project.view.finance.IInvoiceListPresenter import com.mycollab.module.project.view.message.MessageListPresenter import com.mycollab.module.project.view.message.MessageReadPresenter import com.mycollab.module.project.view.milestone.MilestoneAddPresenter import com.mycollab.module.project.view.milestone.MilestoneListPresenter import com.mycollab.module.project.view.milestone.MilestoneReadPresenter import com.mycollab.module.project.view.milestone.MilestoneRoadmapPresenter import com.mycollab.module.project.view.page.PageAddPresenter import com.mycollab.module.project.view.page.PageListPresenter import com.mycollab.module.project.view.page.PageReadPresenter import com.mycollab.module.project.view.parameters.* import com.mycollab.module.project.view.risk.IRiskAddPresenter import com.mycollab.module.project.view.risk.IRiskReadPresenter import com.mycollab.module.project.view.settings.* import com.mycollab.module.project.view.task.TaskAddPresenter import com.mycollab.module.project.view.task.TaskReadPresenter import com.mycollab.module.project.view.ticket.ITicketKanbanPresenter import com.mycollab.module.project.view.ticket.TicketDashboardPresenter import com.mycollab.module.project.view.user.ProjectDashboardPresenter import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.ApplicationEventListener import com.mycollab.vaadin.mvp.AbstractController import com.mycollab.vaadin.mvp.PresenterResolver /** * @author MyCollab Ltd * @since 6.0.0 */ class ProjectController(val projectView: ProjectView) : AbstractController() { init { bindProjectEvents() bindTicketEvents() bindTaskEvents() bindRiskEvents() bindBugEvents() bindMessageEvents() bindMilestoneEvents() bindUserGroupEvents() bindTimeandInvoiceEvents() bindPageEvents() } private fun bindProjectEvents() { this.register(object : ApplicationEventListener<ProjectEvent.GotoEdit> { @Subscribe override fun handle(event: ProjectEvent.GotoEdit) { val project = event.data as SimpleProject CurrentProjectVariables.project = project val presenter = PresenterResolver.getPresenter(ProjectDashboardPresenter::class.java) presenter.go(projectView, ProjectScreenData.Edit(project)) } }) this.register(object : ApplicationEventListener<ProjectEvent.GotoTagListView> { @Subscribe override fun handle(event: ProjectEvent.GotoTagListView) { val tag = event.data as? Tag val presenter = PresenterResolver.getPresenter(ProjectDashboardPresenter::class.java) presenter.go(projectView, ProjectScreenData.GotoTagList(tag)) } }) this.register(object : ApplicationEventListener<ProjectEvent.GotoFavoriteView> { @Subscribe override fun handle(event: ProjectEvent.GotoFavoriteView) { val presenter = PresenterResolver.getPresenter(ProjectDashboardPresenter::class.java) presenter.go(projectView, ProjectScreenData.GotoFavorite()) } }) this.register(object : ApplicationEventListener<ProjectEvent.GotoDashboard> { @Subscribe override fun handle(event: ProjectEvent.GotoDashboard) { val presenter = PresenterResolver.getPresenter(ProjectDashboardPresenter::class.java) presenter.go(projectView, null) } }) } private fun bindTicketEvents() { this.register(object : ApplicationEventListener<TicketEvent.GotoDashboard> { @Subscribe override fun handle(event: TicketEvent.GotoDashboard) { val data = TicketScreenData.GotoDashboard(event.data) val presenter = PresenterResolver.getPresenter(TicketDashboardPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<TicketEvent.GotoRead> { @Subscribe override fun handle(event: TicketEvent.GotoRead) { val ticketKeyMapper = AppContextUtil.getSpringBean(TicketKeyMapper::class.java) val ex = TicketKeyExample() ex.createCriteria().andProjectidEqualTo(event.projectId).andTicketkeyEqualTo(event.ticketKey) val ticketKeys = ticketKeyMapper.selectByExample(ex) when (ticketKeys.size) { 0 -> throw ResourceNotFoundException("Not found ticketKey with projectId=${event.projectId} and ticketKey=${event.ticketKey}") 1 -> { val ticketKey = ticketKeys[0] when (ticketKey.tickettype) { ProjectTypeConstants.RISK -> { val riskService = AppContextUtil.getSpringBean(RiskService::class.java) val risk = riskService.findById(ticketKey.ticketid, AppUI.accountId) if (risk != null) { val presenter = PresenterResolver.getPresenter(IRiskReadPresenter::class.java) presenter.go(projectView, RiskScreenData.Read(risk)) } else throw ResourceNotFoundException("Can not find risk with id = ${ticketKey.ticketid} in account ${AppUI.accountId}") } ProjectTypeConstants.TASK -> { val taskService = AppContextUtil.getSpringBean(TaskService::class.java) val task = taskService.findById(ticketKey.ticketid, AppUI.accountId) if (task != null) { val presenter = PresenterResolver.getPresenter(TaskReadPresenter::class.java) presenter.go(projectView, TaskScreenData.Read(task)) } else throw ResourceNotFoundException("Can not find task with id = ${ticketKey.ticketid} in account ${AppUI.accountId}") } ProjectTypeConstants.BUG -> { val bugService = AppContextUtil.getSpringBean(BugService::class.java) val bug = bugService.findById(ticketKey.ticketid, AppUI.accountId) if (bug != null) { val presenter = PresenterResolver.getPresenter(BugReadPresenter::class.java) presenter.go(projectView, BugScreenData.Read(bug)) } else throw ResourceNotFoundException("Can not find bug with id = ${ticketKey.ticketid} in account ${AppUI.accountId}") } else -> throw MyCollabException("Not support ticket type ${ticketKey.tickettype}") } } else -> throw MyCollabException("Find more than one ticketKeys with projectId=${event.projectId} and ticketKey=${event.ticketKey}") } } }) } private fun bindTaskEvents() { this.register(object : ApplicationEventListener<TaskEvent.GotoRead> { @Subscribe override fun handle(event: TaskEvent.GotoRead) { val data = TaskScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(TaskReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<TaskEvent.GotoAdd> { @Subscribe override fun handle(event: TaskEvent.GotoAdd) { val param = event.data val data = if (param is SimpleTask) TaskScreenData.Add(param) else TaskScreenData.Add(SimpleTask()) val presenter = PresenterResolver.getPresenter(TaskAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<TaskEvent.GotoEdit> { @Subscribe override fun handle(event: TaskEvent.GotoEdit) { val data = TaskScreenData.Edit(event.data as SimpleTask) val presenter = PresenterResolver.getPresenter(TaskAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<TaskEvent.GotoKanbanView> { @Subscribe override fun handle(event: TaskEvent.GotoKanbanView) { val data = TicketScreenData.GotoKanbanView() val presenter = PresenterResolver.getPresenter(ITicketKanbanPresenter::class.java) presenter.go(projectView, data) } }) } private fun bindRiskEvents() { this.register(object : ApplicationEventListener<RiskEvent.GotoAdd> { @Subscribe override fun handle(event: RiskEvent.GotoAdd) { val param = event.data val data = if (param is SimpleRisk) RiskScreenData.Add(param) else RiskScreenData.Add(SimpleRisk()) val presenter = PresenterResolver.getPresenter(IRiskAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<RiskEvent.GotoEdit> { @Subscribe override fun handle(event: RiskEvent.GotoEdit) { val data = RiskScreenData.Edit(event.data as Risk) val presenter = PresenterResolver.getPresenter(IRiskAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<RiskEvent.GotoRead> { @Subscribe override fun handle(event: RiskEvent.GotoRead) { val data = RiskScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(IRiskReadPresenter::class.java) presenter.go(projectView, data) } }) } private fun bindBugEvents() { this.register(object : ApplicationEventListener<BugEvent.GotoAdd> { @Subscribe override fun handle(event: BugEvent.GotoAdd) { val data = BugScreenData.Add(SimpleBug()) val presenter = PresenterResolver.getPresenter(BugAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugEvent.GotoEdit> { @Subscribe override fun handle(event: BugEvent.GotoEdit) { val data = BugScreenData.Edit(event.data as SimpleBug) val presenter = PresenterResolver.getPresenter(BugAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugEvent.GotoRead> { @Subscribe override fun handle(event: BugEvent.GotoRead) { val data = BugScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(BugReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugComponentEvent.GotoAdd> { @Subscribe override fun handle(event: BugComponentEvent.GotoAdd) { val data = ComponentScreenData.Add(Component()) val presenter = PresenterResolver.getPresenter(ComponentAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugComponentEvent.GotoEdit> { @Subscribe override fun handle(event: BugComponentEvent.GotoEdit) { val data = ComponentScreenData.Edit(event.data as Component) val presenter = PresenterResolver.getPresenter(ComponentAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugComponentEvent.GotoRead> { @Subscribe override fun handle(event: BugComponentEvent.GotoRead) { val data = ComponentScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(ComponentReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugComponentEvent.GotoList> { @Subscribe override fun handle(event: BugComponentEvent.GotoList) { val criteria = ComponentSearchCriteria() criteria.projectId = NumberSearchField(CurrentProjectVariables.projectId) val presenter = PresenterResolver.getPresenter(ComponentListPresenter::class.java) presenter.go(projectView, ComponentScreenData.Search(criteria)) } }) this.register(object : ApplicationEventListener<BugVersionEvent.GotoAdd> { @Subscribe override fun handle(event: BugVersionEvent.GotoAdd) { val data = VersionScreenData.Add(Version()) val presenter = PresenterResolver.getPresenter(VersionAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugVersionEvent.GotoEdit> { @Subscribe override fun handle(event: BugVersionEvent.GotoEdit) { val data = VersionScreenData.Edit(event.data as Version) val presenter = PresenterResolver.getPresenter(VersionAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugVersionEvent.GotoRead> { @Subscribe override fun handle(event: BugVersionEvent.GotoRead) { val data = VersionScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(VersionReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<BugVersionEvent.GotoList> { @Subscribe override fun handle(event: BugVersionEvent.GotoList) { val criteria = VersionSearchCriteria() criteria.projectId = NumberSearchField(CurrentProjectVariables.projectId) val presenter = PresenterResolver.getPresenter(VersionListPresenter::class.java) presenter.go(projectView, VersionScreenData.Search(criteria)) } }) } private fun bindMessageEvents() { this.register(object : ApplicationEventListener<MessageEvent.GotoRead> { @Subscribe override fun handle(event: MessageEvent.GotoRead) { val data = MessageScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(MessageReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<MessageEvent.GotoList> { @Subscribe override fun handle(event: MessageEvent.GotoList) { val searchCriteria = MessageSearchCriteria() searchCriteria.projectIds = SetSearchField(CurrentProjectVariables.projectId) val data = MessageScreenData.Search(searchCriteria) val presenter = PresenterResolver.getPresenter(MessageListPresenter::class.java) presenter.go(projectView, data) } }) } private fun bindMilestoneEvents() { this.register(object : ApplicationEventListener<MilestoneEvent.GotoAdd> { @Subscribe override fun handle(event: MilestoneEvent.GotoAdd) { val data = MilestoneScreenData.Add(SimpleMilestone()) val presenter = PresenterResolver.getPresenter(MilestoneAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<MilestoneEvent.GotoRead> { @Subscribe override fun handle(event: MilestoneEvent.GotoRead) { val data = MilestoneScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(MilestoneReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<MilestoneEvent.GotoList> { @Subscribe override fun handle(event: MilestoneEvent.GotoList) { val criteria = MilestoneSearchCriteria() criteria.projectIds = SetSearchField(CurrentProjectVariables.projectId) val presenter = PresenterResolver.getPresenter(MilestoneListPresenter::class.java) presenter.go(projectView, MilestoneScreenData.Search(criteria)) } }) this.register(object : ApplicationEventListener<MilestoneEvent.GotoRoadmap> { @Subscribe override fun handle(event: MilestoneEvent.GotoRoadmap) { val presenter = PresenterResolver.getPresenter(MilestoneRoadmapPresenter::class.java) presenter.go(projectView, MilestoneScreenData.Roadmap()) } }) this.register(object : ApplicationEventListener<MilestoneEvent.GotoEdit> { @Subscribe override fun handle(event: MilestoneEvent.GotoEdit) { val data = MilestoneScreenData.Edit(event.data as Milestone) val presenter = PresenterResolver.getPresenter(MilestoneAddPresenter::class.java) presenter.go(projectView, data) } }) } private fun bindUserGroupEvents() { this.register(object : ApplicationEventListener<ProjectRoleEvent.GotoList> { @Subscribe override fun handle(event: ProjectRoleEvent.GotoList) { val project = CurrentProjectVariables.project val criteria = ProjectRoleSearchCriteria() criteria.projectId = NumberSearchField(project!!.id) val presenter = PresenterResolver.getPresenter(ProjectRoleListPresenter::class.java) presenter.go(projectView, ProjectRoleScreenData.Search(criteria)) } }) this.register(object : ApplicationEventListener<ProjectRoleEvent.GotoAdd> { @Subscribe override fun handle(event: ProjectRoleEvent.GotoAdd) { val data = ProjectRoleScreenData.Add(ProjectRole()) val presenter = PresenterResolver.getPresenter(ProjectRoleAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<ProjectRoleEvent.GotoEdit> { @Subscribe override fun handle(event: ProjectRoleEvent.GotoEdit) { val data = ProjectRoleScreenData.Add(event.data as ProjectRole) val presenter = PresenterResolver.getPresenter(ProjectRoleAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<ProjectRoleEvent.GotoRead> { @Subscribe override fun handle(event: ProjectRoleEvent.GotoRead) { val data = ProjectRoleScreenData.Read(event.data as Int) val presenter = PresenterResolver.getPresenter(ProjectRoleReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<ProjectMemberEvent.GotoList> { @Subscribe override fun handle(event: ProjectMemberEvent.GotoList) { val criteria = ProjectMemberSearchCriteria() criteria.projectIds = SetSearchField(event.projectId) criteria.saccountid = NumberSearchField(AppUI.accountId) criteria.statuses = SetSearchField(ProjectMemberStatusConstants.ACTIVE, ProjectMemberStatusConstants.NOT_ACCESS_YET) val presenter = PresenterResolver.getPresenter(ProjectMemberListPresenter::class.java) presenter.go(projectView, ProjectMemberScreenData.Search(criteria)) } }) this.register(object : ApplicationEventListener<ProjectMemberEvent.GotoRead> { @Subscribe override fun handle(event: ProjectMemberEvent.GotoRead) { val data = ProjectMemberScreenData.Read(event.data) val presenter = PresenterResolver.getPresenter(ProjectMemberReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<ProjectMemberEvent.GotoInviteMembers> { @Subscribe override fun handle(event: ProjectMemberEvent.GotoInviteMembers) { val data = ProjectMemberScreenData.InviteProjectMembers() val presenter = PresenterResolver.getPresenter(ProjectMemberInvitePresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<ProjectMemberEvent.GotoEdit> { @Subscribe override fun handle(event: ProjectMemberEvent.GotoEdit) { val data = ProjectMemberScreenData.Add(event.data as ProjectMember) val presenter = PresenterResolver.getPresenter(ProjectMemberEditPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<ProjectNotificationEvent.GotoList> { @Subscribe override fun handle(event: ProjectNotificationEvent.GotoList) { val data = ProjectSettingScreenData.ViewSettings() val presenter = PresenterResolver.getPresenter(ProjectCustomPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<CustomizeUIEvent.UpdateFeaturesList> { @Subscribe override fun handle(event: CustomizeUIEvent.UpdateFeaturesList) { projectView.updateProjectFeatures() } }) } private fun bindTimeandInvoiceEvents() { this.register(object : ApplicationEventListener<InvoiceEvent.GotoList> { @Subscribe override fun handle(event: InvoiceEvent.GotoList) { val presenter = PresenterResolver.getPresenter(IInvoiceListPresenter::class.java) presenter.go(projectView, null) } }) } private fun bindPageEvents() { this.register(object : ApplicationEventListener<PageEvent.GotoAdd> { @Subscribe override fun handle(event: PageEvent.GotoAdd) { var pagePath = event.data as? String if ("" == pagePath || pagePath == null) { pagePath = "${CurrentProjectVariables.currentPagePath}/${StringUtils.generateSoftUniqueId()}" } val page = Page() page.path = pagePath val data = PageScreenData.Add(page) val presenter = PresenterResolver.getPresenter(PageAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<PageEvent.GotoEdit> { @Subscribe override fun handle(event: PageEvent.GotoEdit) { val data = PageScreenData.Edit(event.data as Page) val presenter = PresenterResolver.getPresenter(PageAddPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<PageEvent.GotoRead> { @Subscribe override fun handle(event: PageEvent.GotoRead) { val data = PageScreenData.Read(event.data as Page) val presenter = PresenterResolver.getPresenter(PageReadPresenter::class.java) presenter.go(projectView, data) } }) this.register(object : ApplicationEventListener<PageEvent.GotoList> { @Subscribe override fun handle(event: PageEvent.GotoList) { val presenter = PresenterResolver.getPresenter(PageListPresenter::class.java) presenter.go(projectView, PageScreenData.Search(event.data)) } }) } }
agpl-3.0
588c6cf6cf5f8c07a9526ef184770871
49.033333
153
0.641115
5.120735
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/core/db/NotificationDB.kt
1
1025
package treehou.se.habit.core.db import java.util.Date import io.realm.Realm import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class NotificationDB : RealmObject() { @PrimaryKey var id: Long = 0 var message: String? = "" var date: Date? = null var viewed: Boolean = false companion object { fun save(item: NotificationDB) { val realm = Realm.getDefaultInstance() realm.beginTransaction() if (item.id <= 0) { item.id = uniqueId } realm.copyToRealmOrUpdate(item) realm.commitTransaction() realm.close() } val uniqueId: Long get() { val realm = Realm.getDefaultInstance() val num = realm.where(NotificationDB::class.java).max("id") var newId: Long = 1 if (num != null) newId = num.toLong() + 1 realm.close() return newId } } }
epl-1.0
8e85a1f93e6fab8ba2e4b382ce7c6216
24.625
75
0.539512
4.617117
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/list/adapter/DataAdapter.kt
1
1487
package com.engineer.imitate.ui.list.adapter import android.annotation.SuppressLint import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.engineer.imitate.R /** * * @authro: Rookie * @since: 2019-01-05 */ class DataAdapter() : RecyclerView.Adapter<DataAdapter.MyViewHolder>() { private var size = 100; override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyViewHolder { val view = LayoutInflater.from(p0.context).inflate(R.layout.view_item, p0, false) return MyViewHolder(view) } override fun getItemCount(): Int { return size } public fun setSize(size:Int) { this.size = size } @SuppressLint("SetTextI18n") override fun onBindViewHolder(p0: MyViewHolder, p1: Int) { val type = p1 % 2 when (type) { 0 -> p0.shell.setBackgroundResource(R.color.cpb_grey) 1 -> p0.shell.setBackgroundResource(R.color.cpb_white) } p0.desc.text = "this is $p1" p0.path.text = "$p1" } inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val desc = itemView.findViewById<TextView>(R.id.desc) val path = itemView.findViewById<TextView>(R.id.path) val shell = itemView.findViewById<ConstraintLayout>(R.id.shell) } }
apache-2.0
922c42e049df9d9166d5cc62ab216931
27.615385
89
0.68191
3.882507
false
false
false
false
samtstern/quickstart-android
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PasswordlessActivity.kt
1
7820
package com.google.firebase.quickstart.auth.kotlin import android.content.Intent import android.os.Bundle import com.google.android.material.snackbar.Snackbar import android.text.TextUtils import android.util.Log import android.view.View import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthActionCodeException import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.ktx.actionCodeSettings import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import com.google.firebase.quickstart.auth.R import com.google.firebase.quickstart.auth.databinding.ActivityPasswordlessBinding /** * Demonstrate Firebase Authentication without a password, using a link sent to an * email address. */ class PasswordlessActivity : BaseActivity(), View.OnClickListener { private var pendingEmail: String = "" private var emailLink: String = "" private lateinit var auth: FirebaseAuth private lateinit var binding: ActivityPasswordlessBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPasswordlessBinding.inflate(layoutInflater) setContentView(binding.root) setProgressBar(binding.progressBar) // Initialize Firebase Auth auth = Firebase.auth binding.passwordlessSendEmailButton.setOnClickListener(this) binding.passwordlessSignInButton.setOnClickListener(this) binding.signOutButton.setOnClickListener(this) // Restore the "pending" email address if (savedInstanceState != null) { pendingEmail = savedInstanceState.getString(KEY_PENDING_EMAIL, null) binding.fieldEmail.setText(pendingEmail) } // Check if the Intent that started the Activity contains an email sign-in link. checkIntent(intent) } override fun onStart() { super.onStart() updateUI(auth.currentUser) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) checkIntent(intent) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(KEY_PENDING_EMAIL, pendingEmail) } /** * Check to see if the Intent has an email link, and if so set up the UI accordingly. * This can be called from either onCreate or onNewIntent, depending on how the Activity * was launched. */ private fun checkIntent(intent: Intent?) { if (intentHasEmailLink(intent)) { emailLink = intent!!.data!!.toString() binding.status.setText(R.string.status_link_found) binding.passwordlessSendEmailButton.isEnabled = false binding.passwordlessSignInButton.isEnabled = true } else { binding.status.setText(R.string.status_email_not_sent) binding.passwordlessSendEmailButton.isEnabled = true binding.passwordlessSignInButton.isEnabled = false } } /** * Determine if the given Intent contains an email sign-in link. */ private fun intentHasEmailLink(intent: Intent?): Boolean { if (intent != null && intent.data != null) { val intentData = intent.data.toString() if (auth.isSignInWithEmailLink(intentData)) { return true } } return false } /** * Send an email sign-in link to the specified email. */ private fun sendSignInLink(email: String) { val settings = actionCodeSettings { setAndroidPackageName( packageName, false, null/* minimum app version */)/* install if not available? */ handleCodeInApp = true url = "https://kotlin.auth.example.com/emailSignInLink" } hideKeyboard(binding.fieldEmail) showProgressBar() auth.sendSignInLinkToEmail(email, settings) .addOnCompleteListener { task -> hideProgressBar() if (task.isSuccessful) { Log.d(TAG, "Link sent") showSnackbar("Sign-in link sent!") pendingEmail = email binding.status.setText(R.string.status_email_sent) } else { val e = task.exception Log.w(TAG, "Could not send link", e) showSnackbar("Failed to send link.") if (e is FirebaseAuthInvalidCredentialsException) { binding.fieldEmail.error = "Invalid email address." } } } } /** * Sign in using an email address and a link, the link is passed to the Activity * from the dynamic link contained in the email. */ private fun signInWithEmailLink(email: String, link: String?) { Log.d(TAG, "signInWithLink:" + link!!) hideKeyboard(binding.fieldEmail) showProgressBar() auth.signInWithEmailLink(email, link) .addOnCompleteListener { task -> hideProgressBar() if (task.isSuccessful) { Log.d(TAG, "signInWithEmailLink:success") binding.fieldEmail.text = null updateUI(task.result?.user) } else { Log.w(TAG, "signInWithEmailLink:failure", task.exception) updateUI(null) if (task.exception is FirebaseAuthActionCodeException) { showSnackbar("Invalid or expired sign-in link.") } } } } private fun onSendLinkClicked() { val email = binding.fieldEmail.text.toString() if (TextUtils.isEmpty(email)) { binding.fieldEmail.error = "Email must not be empty." return } sendSignInLink(email) } private fun onSignInClicked() { val email = binding.fieldEmail.text.toString() if (TextUtils.isEmpty(email)) { binding.fieldEmail.error = "Email must not be empty." return } signInWithEmailLink(email, emailLink) } private fun onSignOutClicked() { auth.signOut() updateUI(null) binding.status.setText(R.string.status_email_not_sent) } private fun updateUI(user: FirebaseUser?) { if (user != null) { binding.status.text = getString(R.string.passwordless_status_fmt, user.email, user.isEmailVerified) binding.passwordlessFields.visibility = View.GONE binding.passwordlessButtons.visibility = View.GONE binding.signedInButtons.visibility = View.VISIBLE } else { binding.passwordlessFields.visibility = View.VISIBLE binding.passwordlessButtons.visibility = View.VISIBLE binding.signedInButtons.visibility = View.GONE } } private fun showSnackbar(message: String) { Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_SHORT).show() } override fun onClick(view: View) { when (view.id) { R.id.passwordlessSendEmailButton -> onSendLinkClicked() R.id.passwordlessSignInButton -> onSignInClicked() R.id.signOutButton -> onSignOutClicked() } } companion object { private const val TAG = "PasswordlessSignIn" private const val KEY_PENDING_EMAIL = "key_pending_email" } }
apache-2.0
887e03e5fe02a81fe51f09efb8baec50
33.755556
96
0.615985
4.905897
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-github/layout/src/main/java/com/bennyhuo/dsl/layout/v2/LayoutParams.kt
2
3532
package com.bennyhuo.dsl.layout.v2 import android.annotation.TargetApi import android.os.Build.VERSION_CODES import android.view.ViewGroup.MarginLayoutParams import android.widget.RelativeLayout //region MarginLayoutParam @get:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) @set:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) var <T : MarginLayoutParams> T.startMargin: Int set(value) { marginStart = value } get() { return marginStart } @get:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) @set:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) var <T : MarginLayoutParams> T.endMargin: Int set(value) { marginEnd = value } get() { return marginEnd } fun <T : MarginLayoutParams> T.margin(margin: Int) { leftMargin = margin topMargin = margin rightMargin = margin bottomMargin = margin startMargin = margin endMargin = margin } //endregion //region RelativeLayoutParam fun <T : RelativeLayout.LayoutParams> T.leftOf(id: Int) { addRule(RelativeLayout.LEFT_OF, id) } fun <T : RelativeLayout.LayoutParams> T.rightOf(id: Int) { addRule(RelativeLayout.RIGHT_OF, id) } fun <T : RelativeLayout.LayoutParams> T.above(id: Int) { addRule(RelativeLayout.ABOVE, id) } fun <T : RelativeLayout.LayoutParams> T.below(id: Int) { addRule(RelativeLayout.BELOW, id) } fun <T : RelativeLayout.LayoutParams> T.alignBaseline(id: Int) { addRule(RelativeLayout.ALIGN_BASELINE, id) } fun <T : RelativeLayout.LayoutParams> T.alignLeft(id: Int) { addRule(RelativeLayout.ALIGN_LEFT, id) } fun <T : RelativeLayout.LayoutParams> T.alignTop(id: Int) { addRule(RelativeLayout.ALIGN_TOP, id) } fun <T : RelativeLayout.LayoutParams> T.alignRight(id: Int) { addRule(RelativeLayout.ALIGN_RIGHT, id) } fun <T : RelativeLayout.LayoutParams> T.alignBottom(id: Int) { addRule(RelativeLayout.ALIGN_BOTTOM, id) } fun <T : RelativeLayout.LayoutParams> T.alignParentLeft() { addRule(RelativeLayout.ALIGN_PARENT_LEFT) } fun <T : RelativeLayout.LayoutParams> T.alignParentTop() { addRule(RelativeLayout.ALIGN_PARENT_TOP) } fun <T : RelativeLayout.LayoutParams> T.alignParentRight() { addRule(RelativeLayout.ALIGN_PARENT_RIGHT) } fun <T : RelativeLayout.LayoutParams> T.alignParentBottom() { addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } fun <T : RelativeLayout.LayoutParams> T.centerInParent() { addRule(RelativeLayout.CENTER_IN_PARENT) } fun <T : RelativeLayout.LayoutParams> T.centerHorizontal() { addRule(RelativeLayout.CENTER_HORIZONTAL) } fun <T : RelativeLayout.LayoutParams> T.centerVertical() { addRule(RelativeLayout.CENTER_VERTICAL) } @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) fun <T : RelativeLayout.LayoutParams> T.startOf(id: Int) { addRule(RelativeLayout.START_OF, id) } @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) fun <T : RelativeLayout.LayoutParams> T.endOf(id: Int) { addRule(RelativeLayout.END_OF, id) } @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) fun <T : RelativeLayout.LayoutParams> T.alignStart(id: Int) { addRule(RelativeLayout.ALIGN_START, id) } @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) fun <T : RelativeLayout.LayoutParams> T.alignEnd(id: Int) { addRule(RelativeLayout.ALIGN_END, id) } @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) fun <T : RelativeLayout.LayoutParams> T.alignParentStart() { addRule(RelativeLayout.ALIGN_PARENT_START) } @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) fun <T : RelativeLayout.LayoutParams> T.alignParentEnd() { addRule(RelativeLayout.ALIGN_PARENT_END) } //endregion
apache-2.0
1e01099fa54664d499c65b27590f0bbe
25.556391
64
0.73188
3.449219
false
false
false
false
marcelgross90/Cineaste
app/src/main/kotlin/de/cineaste/android/database/dbHelper/UserDbHelper.kt
1
1388
package de.cineaste.android.database.dbHelper import android.content.ContentValues import android.content.Context import de.cineaste.android.database.dao.BaseDao import de.cineaste.android.entity.User class UserDbHelper private constructor(context: Context) : BaseDao(context) { val user: User? get() { val projection = arrayOf(UserEntry.ID, UserEntry.COLUMN_USER_NAME) val c = readDb.query( UserEntry.TABLE_NAME, projection, null, null, null, null, null, null ) var user: User? = null if (c.moveToFirst()) { do { user = User() user.userName = c.getString(c.getColumnIndexOrThrow(UserEntry.COLUMN_USER_NAME)) } while (c.moveToNext()) } c.close() return user } fun createUser(user: User) { val values = ContentValues() values.put(UserEntry.COLUMN_USER_NAME, user.userName) writeDb.insert(UserEntry.TABLE_NAME, null, values) } companion object { private var mInstance: UserDbHelper? = null fun getInstance(context: Context): UserDbHelper { if (mInstance == null) { mInstance = UserDbHelper(context) } return mInstance!! } } }
gpl-3.0
871c55948f2c81e03e97035c838ce917
25.711538
100
0.566282
4.626667
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/ActivityTracker.kt
1
2688
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util import android.app.Activity import android.app.Application import android.os.Bundle import de.vanita5.twittnuker.activity.HomeActivity class ActivityTracker : Application.ActivityLifecycleCallbacks { private val internalStack = ArrayList<Int>() var isHomeActivityStarted: Boolean = false private set var isHomeActivityLaunched: Boolean = false private set private fun isSwitchingInSameTask(hashCode: Int): Boolean { return internalStack.lastIndexOf(hashCode) < internalStack.size - 1 } fun size(): Int { return internalStack.size } val isEmpty: Boolean get() = internalStack.isEmpty() override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (activity is HomeActivity) { isHomeActivityLaunched = true } } override fun onActivityStarted(activity: Activity) { internalStack.add(System.identityHashCode(activity)) if (activity is HomeActivity) { isHomeActivityStarted = true } } override fun onActivityResumed(activity: Activity) { Analyzer.activityResumed(activity) } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { val hashCode = System.identityHashCode(activity) if (activity is HomeActivity) { isHomeActivityStarted = false } internalStack.remove(hashCode) } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityDestroyed(activity: Activity) { if (activity is HomeActivity && activity.isFinishing()) { isHomeActivityLaunched = false } } }
gpl-3.0
fbf1c852cb594d064791f7e123e9eab0
28.877778
85
0.700893
4.774423
false
false
false
false
stripe/stripe-android
identity/src/test/java/com/stripe/android/identity/states/IDDetectorTransitionerTest.kt
1
18141
package com.stripe.android.identity.states import com.google.common.truth.Truth.assertThat import com.stripe.android.camera.framework.time.ClockMark import com.stripe.android.camera.framework.time.milliseconds import com.stripe.android.identity.ml.BoundingBox import com.stripe.android.identity.ml.Category import com.stripe.android.identity.ml.IDDetectorOutput import com.stripe.android.identity.states.IdentityScanState.ScanType import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) internal class IDDetectorTransitionerTest { private val mockNeverTimeoutClockMark = mock<ClockMark>().also { whenever(it.hasPassed()).thenReturn(false) } private val mockAlwaysTimeoutClockMark = mock<ClockMark>().also { whenever(it.hasPassed()).thenReturn(true) } private val mockReachedStateAt = mock<ClockMark>().also { whenever(it.elapsedSince()).thenReturn(0.milliseconds) } @Test fun `Found transitions to Found when iOUCheckPass failed`() = runBlocking { val transitioner = IDDetectorTransitioner(mockNeverTimeoutClockMark) val foundState = IdentityScanState.Found( ScanType.ID_FRONT, transitioner, mockReachedStateAt ) // initialize previousBoundingBox transitioner.transitionFromFound(foundState, mock(), INITIAL_ID_FRONT_OUTPUT) // send a low IOU result assertThat( transitioner.transitionFromFound( foundState, mock(), createAnalyzerOutputWithLowIOU(INITIAL_ID_FRONT_OUTPUT) ) ).isSameInstanceAs(foundState) // verify timer is reset assertThat(foundState.reachedStateAt).isNotSameInstanceAs(mockReachedStateAt) } @Test fun `Found stays in Found when moreResultsRequired and transitions to Satisfied when timeRequired is met`() = runBlocking { val timeRequired = 500 val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, timeRequired = timeRequired ) val mockFoundState = mock<IdentityScanState.Found>().also { whenever(it.type).thenReturn(ScanType.ID_FRONT) whenever(it.reachedStateAt).thenReturn(mockReachedStateAt) whenever(it.transitioner).thenReturn(transitioner) } val result = createAnalyzerOutputWithHighIOU(INITIAL_ID_FRONT_OUTPUT) // mock time required is not yet met whenever(mockReachedStateAt.elapsedSince()).thenReturn((timeRequired - 10).milliseconds) assertThat( transitioner.transitionFromFound( mockFoundState, mock(), result ) ).isSameInstanceAs(mockFoundState) // mock time required is met whenever(mockReachedStateAt.elapsedSince()).thenReturn((timeRequired + 10).milliseconds) val resultState = transitioner.transitionFromFound( mockFoundState, mock(), createAnalyzerOutputWithHighIOU(result) ) assertThat(resultState).isInstanceOf(IdentityScanState.Satisfied::class.java) assertThat((resultState as IdentityScanState.Satisfied).type).isEqualTo( ScanType.ID_FRONT ) } @Test fun `Found stays in Found when moreResultsRequired and stays in Found when IOU check fails`() = runBlocking { val timeRequired = 500 val allowedUnmatchedFrames = 2 val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, timeRequired = timeRequired, allowedUnmatchedFrames = allowedUnmatchedFrames ) // never meets required time whenever(mockReachedStateAt.elapsedSince()).thenReturn((timeRequired - 10).milliseconds) val foundState = IdentityScanState.Found( ScanType.ID_FRONT, transitioner, mockReachedStateAt ) // 1st frame - a match, stays in Found val result = createAnalyzerOutputWithHighIOU(INITIAL_ID_FRONT_OUTPUT) assertThat( transitioner.transitionFromFound( foundState, mock(), result ) ).isSameInstanceAs(foundState) // 2nd frame - a low IOU frame, stays in Found assertThat( transitioner.transitionFromFound( foundState, mock(), createAnalyzerOutputWithLowIOU(result) ) ).isSameInstanceAs(foundState) // verify timer is reset assertThat(foundState.reachedStateAt).isNotSameInstanceAs(mockReachedStateAt) } @Test fun `Found keeps staying in Found while unmatched frames within allowedUnmatchedFrames and to Unsatisfied when going beyond`() = runBlocking { val timeRequired = 500 val allowedUnmatchedFrames = 2 val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, timeRequired = timeRequired, allowedUnmatchedFrames = allowedUnmatchedFrames ) // never meets required time whenever(mockReachedStateAt.elapsedSince()).thenReturn((timeRequired - 10).milliseconds) val mockFoundState = mock<IdentityScanState.Found>().also { whenever(it.type).thenReturn(ScanType.ID_FRONT) whenever(it.reachedStateAt).thenReturn(mockReachedStateAt) whenever(it.transitioner).thenReturn(transitioner) } // 1st frame - a match, stays in Found var result = createAnalyzerOutputWithHighIOU(INITIAL_ID_FRONT_OUTPUT) assertThat( transitioner.transitionFromFound( mockFoundState, mock(), result ) ).isSameInstanceAs(mockFoundState) // follow up frames - high IOU frames with unmatch within allowedUnmatchedFrames, stays in Found for (i in 1..allowedUnmatchedFrames) { result = createAnalyzerOutputWithHighIOU(result, Category.ID_BACK) assertThat( transitioner.transitionFromFound( mockFoundState, mock(), result ) ).isSameInstanceAs(mockFoundState) } // another high iOU frame that breaks the streak val resultState = transitioner.transitionFromFound( mockFoundState, mock(), createAnalyzerOutputWithHighIOU(result, Category.ID_BACK) ) assertThat(resultState).isInstanceOf(IdentityScanState.Unsatisfied::class.java) assertThat((resultState as IdentityScanState.Unsatisfied).reason).isEqualTo( "Type ${Category.ID_BACK} doesn't match ${ScanType.ID_FRONT}" ) assertThat(resultState.type).isEqualTo(ScanType.ID_FRONT) } @Test fun `Found keeps staying in Found while unmatched frames within allowedUnmatchedFrames and to Satisfied when going beyond`() = runBlocking { val timeRequired = 500 val allowedUnmatchedFrames = 2 val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, timeRequired = timeRequired, allowedUnmatchedFrames = allowedUnmatchedFrames ) // never meets required time whenever(mockReachedStateAt.elapsedSince()).thenReturn((timeRequired - 10).milliseconds) val mockFoundState = mock<IdentityScanState.Found>().also { whenever(it.type).thenReturn(ScanType.ID_FRONT) whenever(it.reachedStateAt).thenReturn(mockReachedStateAt) whenever(it.transitioner).thenReturn(transitioner) } // 1st frame - a match, stays in Found var result = createAnalyzerOutputWithHighIOU(INITIAL_ID_FRONT_OUTPUT) assertThat( transitioner.transitionFromFound( mockFoundState, mock(), result ) ).isSameInstanceAs(mockFoundState) // follow up frames - high IOU frames with unmatch within allowedUnmatchedFrames, stays in Found for (i in 1..allowedUnmatchedFrames) { result = createAnalyzerOutputWithHighIOU(result, Category.ID_BACK) assertThat( transitioner.transitionFromFound( mockFoundState, mock(), result ) ).isSameInstanceAs(mockFoundState) } // mock required time is met whenever(mockReachedStateAt.elapsedSince()).thenReturn((timeRequired + 10).milliseconds) // another high iOU frame with a match val resultState = transitioner.transitionFromFound( mockFoundState, mock(), createAnalyzerOutputWithHighIOU(result, Category.ID_FRONT) ) assertThat(resultState).isInstanceOf(IdentityScanState.Satisfied::class.java) assertThat(resultState.type).isEqualTo(ScanType.ID_FRONT) } @Test fun `Initial transitions to Timeout when timeout`() = runBlocking { val transitioner = IDDetectorTransitioner( timeoutAt = mockAlwaysTimeoutClockMark ) val initialState = IdentityScanState.Initial( ScanType.ID_FRONT, transitioner ) assertThat( transitioner.transitionFromInitial( initialState, mock(), createAnalyzerOutputWithLowIOU(INITIAL_ID_BACK_OUTPUT) ) ).isInstanceOf(IdentityScanState.TimeOut::class.java) } @Test fun `Initial stays in Initial if type doesn't match`() = runBlocking { val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark ) val initialState = IdentityScanState.Initial( ScanType.ID_FRONT, transitioner ) assertThat( transitioner.transitionFromInitial( initialState, mock(), createAnalyzerOutputWithLowIOU(INITIAL_ID_BACK_OUTPUT) ) ).isSameInstanceAs(initialState) } @Test fun `Initial transitions to Found if type does match`() = runBlocking { val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark ) val initialState = IdentityScanState.Initial( ScanType.ID_FRONT, transitioner ) assertThat( transitioner.transitionFromInitial( initialState, mock(), createAnalyzerOutputWithLowIOU(INITIAL_ID_FRONT_OUTPUT) ) ).isInstanceOf(IdentityScanState.Found::class.java) } @Test fun `Satisfied transitions to Finished when displaySatisfiedDuration has passed`() = runBlocking { val mockReachAtClockMark: ClockMark = mock() whenever(mockReachAtClockMark.elapsedSince()).thenReturn((DEFAULT_DISPLAY_SATISFIED_DURATION + 1).milliseconds) val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, displaySatisfiedDuration = DEFAULT_DISPLAY_SATISFIED_DURATION ) assertThat( transitioner.transitionFromSatisfied( IdentityScanState.Satisfied( ScanType.ID_FRONT, transitioner, reachedStateAt = mockReachAtClockMark ), mock(), mock() ) ).isInstanceOf(IdentityScanState.Finished::class.java) } @Test fun `Satisfied stays in Satisfied when displaySatisfiedDuration has not passed`() = runBlocking { val mockReachAtClockMark: ClockMark = mock() whenever(mockReachAtClockMark.elapsedSince()).thenReturn((DEFAULT_DISPLAY_SATISFIED_DURATION - 1).milliseconds) val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, displaySatisfiedDuration = DEFAULT_DISPLAY_SATISFIED_DURATION ) val satisfiedState = IdentityScanState.Satisfied( ScanType.ID_FRONT, transitioner, reachedStateAt = mockReachAtClockMark ) val resultState = transitioner.transitionFromSatisfied(satisfiedState, mock(), mock()) assertThat(resultState).isSameInstanceAs(satisfiedState) } @Test fun `Unsatisfied transitions to Timeout when timeout`() = runBlocking { val transitioner = IDDetectorTransitioner( timeoutAt = mockAlwaysTimeoutClockMark, displaySatisfiedDuration = DEFAULT_DISPLAY_SATISFIED_DURATION ) assertThat( transitioner.transitionFromUnsatisfied( IdentityScanState.Unsatisfied( "reason", ScanType.ID_FRONT, transitioner ), mock(), mock() ) ).isInstanceOf(IdentityScanState.TimeOut::class.java) } @Test fun `Unsatisfied stays in Unsatisfied when displaySatisfiedDuration has not passed`() = runBlocking { val mockReachAtClockMark: ClockMark = mock() whenever(mockReachAtClockMark.elapsedSince()).thenReturn((DEFAULT_DISPLAY_UNSATISFIED_DURATION - 1).milliseconds) val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, displayUnsatisfiedDuration = DEFAULT_DISPLAY_UNSATISFIED_DURATION ) val unsatisfiedState = IdentityScanState.Unsatisfied( "reason", ScanType.ID_FRONT, transitioner, reachedStateAt = mockReachAtClockMark ) val resultState = transitioner.transitionFromUnsatisfied( unsatisfiedState, mock(), mock() ) assertThat(resultState).isSameInstanceAs(unsatisfiedState) } @Test fun `Unsatisfied transitions to Initial when displaySatisfiedDuration has passed`() = runBlocking { val mockReachAtClockMark: ClockMark = mock() whenever(mockReachAtClockMark.elapsedSince()).thenReturn((DEFAULT_DISPLAY_UNSATISFIED_DURATION + 1).milliseconds) val transitioner = IDDetectorTransitioner( timeoutAt = mockNeverTimeoutClockMark, displayUnsatisfiedDuration = DEFAULT_DISPLAY_UNSATISFIED_DURATION ) val unsatisfiedState = IdentityScanState.Unsatisfied( "reason", ScanType.ID_FRONT, transitioner, reachedStateAt = mockReachAtClockMark ) val resultState = transitioner.transitionFromUnsatisfied( unsatisfiedState, mock(), mock() ) assertThat(resultState).isInstanceOf(IdentityScanState.Initial::class.java) } private fun createAnalyzerOutputWithHighIOU( previousAnalyzerOutput: IDDetectorOutput, newCategory: Category? = null ) = IDDetectorOutput( boundingBox = BoundingBox( previousAnalyzerOutput.boundingBox.left + 1, previousAnalyzerOutput.boundingBox.top + 1, previousAnalyzerOutput.boundingBox.width + 1, previousAnalyzerOutput.boundingBox.height + 1 ), newCategory ?: previousAnalyzerOutput.category, previousAnalyzerOutput.resultScore, previousAnalyzerOutput.allScores ) private fun createAnalyzerOutputWithLowIOU(previousAnalyzerOutput: IDDetectorOutput) = IDDetectorOutput( boundingBox = BoundingBox( previousAnalyzerOutput.boundingBox.left + 500f, previousAnalyzerOutput.boundingBox.top + 500f, previousAnalyzerOutput.boundingBox.width + 500f, previousAnalyzerOutput.boundingBox.height + 500f ), previousAnalyzerOutput.category, previousAnalyzerOutput.resultScore, previousAnalyzerOutput.allScores ) private companion object { val INITIAL_BOUNDING_BOX = BoundingBox(0f, 0f, 500f, 500f) val INITIAL_ID_FRONT_OUTPUT = IDDetectorOutput( INITIAL_BOUNDING_BOX, Category.ID_FRONT, 0f, listOf() ) val INITIAL_ID_BACK_OUTPUT = IDDetectorOutput( INITIAL_BOUNDING_BOX, Category.ID_BACK, 0f, listOf() ) const val DEFAULT_DISPLAY_SATISFIED_DURATION = 1000 const val DEFAULT_DISPLAY_UNSATISFIED_DURATION = 1000 } }
mit
2f81eec8f545bb7774c15b07e3d6ed07
36.636929
132
0.595171
5.42494
false
false
false
false
stripe/stripe-android
financial-connections/src/main/java/com/stripe/android/financialconnections/repository/FinancialConnectionsApiRepository.kt
1
6373
package com.stripe.android.financialconnections.repository import androidx.annotation.VisibleForTesting import com.stripe.android.core.exception.APIConnectionException import com.stripe.android.core.exception.APIException import com.stripe.android.core.exception.AuthenticationException import com.stripe.android.core.exception.InvalidRequestException import com.stripe.android.core.exception.PermissionException import com.stripe.android.core.exception.RateLimitException import com.stripe.android.core.injection.STRIPE_ACCOUNT_ID import com.stripe.android.core.model.parsers.StripeErrorJsonParser import com.stripe.android.core.networking.ApiRequest import com.stripe.android.core.networking.HTTP_TOO_MANY_REQUESTS import com.stripe.android.core.networking.StripeNetworkClient import com.stripe.android.core.networking.StripeRequest import com.stripe.android.core.networking.StripeResponse import com.stripe.android.core.networking.responseJson import com.stripe.android.financialconnections.di.PUBLISHABLE_KEY import com.stripe.android.financialconnections.model.FinancialConnectionsAccountList import com.stripe.android.financialconnections.model.FinancialConnectionsSession import com.stripe.android.financialconnections.model.FinancialConnectionsSessionManifest import com.stripe.android.financialconnections.model.GetFinancialConnectionsAcccountsParams import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json import java.net.HttpURLConnection import javax.inject.Inject import javax.inject.Named internal class FinancialConnectionsApiRepository @Inject constructor( @Named(PUBLISHABLE_KEY) publishableKey: String, @Named(STRIPE_ACCOUNT_ID) stripeAccountId: String?, private val stripeNetworkClient: StripeNetworkClient, private val apiRequestFactory: ApiRequest.Factory ) : FinancialConnectionsRepository { @VisibleForTesting internal val json: Json = Json { coerceInputValues = true ignoreUnknownKeys = true isLenient = true encodeDefaults = true } private val options by lazy { ApiRequest.Options( apiKey = publishableKey, stripeAccount = stripeAccountId ) } override suspend fun getFinancialConnectionsAccounts( getFinancialConnectionsAcccountsParams: GetFinancialConnectionsAcccountsParams ): FinancialConnectionsAccountList { val financialConnectionsRequest = apiRequestFactory.createGet( url = listAccountsUrl, options = options, params = getFinancialConnectionsAcccountsParams.toParamMap() ) return executeRequest(financialConnectionsRequest, FinancialConnectionsAccountList.serializer()) } override suspend fun getFinancialConnectionsSession( clientSecret: String ): FinancialConnectionsSession { val financialConnectionsRequest = apiRequestFactory.createGet( url = sessionReceiptUrl, options = options, params = mapOf( PARAMS_CLIENT_SECRET to clientSecret ) ) return executeRequest(financialConnectionsRequest, FinancialConnectionsSession.serializer()) } override suspend fun generateFinancialConnectionsSessionManifest( clientSecret: String, applicationId: String ): FinancialConnectionsSessionManifest { val financialConnectionsRequest = apiRequestFactory.createPost( url = generateHostedUrl, options = options, params = mapOf( PARAMS_FULLSCREEN to true, PARAMS_HIDE_CLOSE_BUTTON to true, PARAMS_CLIENT_SECRET to clientSecret, PARAMS_APPLICATION_ID to applicationId ) ) return executeRequest( financialConnectionsRequest, FinancialConnectionsSessionManifest.serializer() ) } private suspend fun <Response> executeRequest( request: StripeRequest, responseSerializer: KSerializer<Response> ): Response = runCatching { stripeNetworkClient.executeRequest( request ) }.fold( onSuccess = { response -> if (response.isError) { throw handleApiError(response) } else { json.decodeFromString( responseSerializer, requireNotNull(response.body) ) } }, onFailure = { throw APIConnectionException( "Failed to execute $request", cause = it ) } ) @Throws( InvalidRequestException::class, AuthenticationException::class, APIException::class ) private fun handleApiError(response: StripeResponse<String>): Exception { val requestId = response.requestId?.value val responseCode = response.code val stripeError = StripeErrorJsonParser().parse(response.responseJson()) throw when (responseCode) { HttpURLConnection.HTTP_BAD_REQUEST, HttpURLConnection.HTTP_NOT_FOUND -> InvalidRequestException( stripeError, requestId, responseCode ) HttpURLConnection.HTTP_UNAUTHORIZED -> AuthenticationException(stripeError, requestId) HttpURLConnection.HTTP_FORBIDDEN -> PermissionException(stripeError, requestId) HTTP_TOO_MANY_REQUESTS -> RateLimitException(stripeError, requestId) else -> APIException(stripeError, requestId, responseCode) } } internal companion object { private const val API_HOST = "https://api.stripe.com" internal const val PARAMS_CLIENT_SECRET = "client_secret" internal const val PARAMS_APPLICATION_ID = "application_id" internal const val PARAMS_FULLSCREEN = "fullscreen" internal const val PARAMS_HIDE_CLOSE_BUTTON = "hide_close_button" internal const val listAccountsUrl: String = "$API_HOST/v1/link_account_sessions/list_accounts" internal const val sessionReceiptUrl: String = "$API_HOST/v1/link_account_sessions/session_receipt" internal const val generateHostedUrl: String = "$API_HOST/v1/link_account_sessions/generate_hosted_url" } }
mit
e9b1760c2ffeec3ac632bf4cf53abce0
38.583851
104
0.698572
5.447009
false
false
false
false
ppamorim/chaos-face
app/src/main/java/com/github/ppamorim/chaos/SettingsActivity.kt
1
1716
package com.github.ppamorim.chaos import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.widget.RecyclerView import android.view.View class SettingsActivity: Activity() { val recyclerView: RecyclerView by lazy { findViewById(R.id.recycler_view) as RecyclerView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) val colorsName = resources.getStringArray(R.array.colors_accent_name) val colorsAccent = resources.getIntArray(R.array.colors_accent_values) if (colorsName.size != colorsAccent.size) { throw IllegalStateException("Count of colors is different of count of names") } val colors: Array<Color> = colorsAccent .mapIndexed { index, value -> Color(value, colorsName[index]) } .toTypedArray() recyclerView.adapter = ColorAdapter(colors, onClickListener) } private val onClickListener = View.OnClickListener { (it.tag as? Int)?.let { position -> resources.getIntArray(R.array.colors_accent_values)[position].let { val intent = Intent() intent.putExtra(ACCENT_COLOR, it) intent.action = CHANGE_COLOR intent.addCategory(Intent.CATEGORY_DEFAULT) sendBroadcast(intent) val sharedPref = getSharedPreferences("com.github.ppamorim.chaos", Context.MODE_PRIVATE) val editor = sharedPref.edit() editor.putInt(ACCENT_COLOR, it) editor.commit() println("notified") } } } }
mit
bc2a8ea2a023945d948076bc8c4bf52c
28.603448
96
0.715035
4.366412
false
false
false
false
bl-lia/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/realm/RealmAccount.kt
1
1063
package com.bl_lia.kirakiratter.domain.entity.realm import com.bl_lia.kirakiratter.domain.entity.Account import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class RealmAccount( @PrimaryKey open var id: Int = -1, open var userName: String? = null, open var displayName: String? = null, open var avatar: String? = null, open var header: String? = null, open var note: String? = null, open var followersCount: Int? = null, open var followingCount: Int? = null, open var statusesCount: Int? = null ): RealmObject() { fun toAccount(): Account = Account( id = id, userName = userName, displayName = displayName, avatar = avatar, header = header, note = note, followersCount = followersCount, followingCount = followingCount, statusesCount = statusesCount ) }
mit
3cc2c56e7a349a099a8c588b866195ff
32.25
52
0.552211
4.99061
false
false
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/model/SourceOrderFixtures.kt
1
2952
package com.stripe.android.model import org.json.JSONObject internal object SourceOrderFixtures { val SOURCE_ORDER_JSON = JSONObject( """ { "amount": 1000, "currency": "eur", "email": "[email protected]", "items": [{ "amount": 1000, "currency": "eur", "description": "shoes", "quantity": 1, "type": "sku" }, { "amount": 1000, "currency": "eur", "description": "socks", "quantity": 1, "type": "sku" }, { "amount": 499, "currency": "eur", "description": "ground shipping", "type": "shipping" }, { "amount": 299, "currency": "eur", "description": "sales tax", "type": "tax" } ], "shipping": { "address": { "city": "San Francisco", "country": "US", "line1": "123 Market St", "line2": "#345", "postal_code": "94107", "state": "CA" }, "carrier": "UPS", "name": "Jenny Rosen", "phone": "1-800-555-1234", "tracking_number": "tracking_12345" } } """.trimIndent() ) val SOURCE_ORDER = SourceOrder( amount = 1000, currency = "eur", email = "[email protected]", items = listOf( SourceOrder.Item( type = SourceOrder.Item.Type.Sku, amount = 1000, currency = "eur", description = "shoes", quantity = 1 ), SourceOrder.Item( type = SourceOrder.Item.Type.Sku, amount = 1000, currency = "eur", description = "socks", quantity = 1 ), SourceOrder.Item( type = SourceOrder.Item.Type.Shipping, amount = 499, currency = "eur", description = "ground shipping" ), SourceOrder.Item( type = SourceOrder.Item.Type.Tax, amount = 299, currency = "eur", description = "sales tax" ) ), shipping = SourceOrder.Shipping( address = AddressFixtures.ADDRESS, carrier = "UPS", name = "Jenny Rosen", phone = "1-800-555-1234", trackingNumber = "tracking_12345" ) ) }
mit
3349ad83bd534c69383b595a379def7a
29.122449
54
0.364837
5.116118
false
false
false
false
exponent/exponent
packages/expo-barcode-scanner/android/src/main/java/expo/modules/barcodescanner/BarCodeScannerView.kt
2
5685
package expo.modules.barcodescanner import android.content.Context import android.hardware.SensorManager import android.view.OrientationEventListener import android.view.View import android.view.ViewGroup import android.view.WindowManager import expo.modules.barcodescanner.BarCodeScannedEvent.Companion.obtain import expo.modules.barcodescanner.utils.mapX import expo.modules.barcodescanner.utils.mapY import expo.modules.core.ModuleRegistryDelegate import expo.modules.core.interfaces.services.EventEmitter import expo.modules.interfaces.barcodescanner.BarCodeScannerResult import expo.modules.interfaces.barcodescanner.BarCodeScannerSettings import kotlin.math.roundToInt class BarCodeScannerView( private val viewContext: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate ) : ViewGroup(viewContext) { private val orientationListener = object : OrientationEventListener( viewContext, SensorManager.SENSOR_DELAY_NORMAL ) { override fun onOrientationChanged(orientation: Int) { if (setActualDeviceOrientation(viewContext)) { layoutViewFinder() } } }.apply { if (canDetectOrientation()) enable() else disable() } private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() private lateinit var viewFinder: BarCodeScannerViewFinder private var actualDeviceOrientation = -1 private var leftPadding = 0 private var topPadding = 0 private var type = 0 override fun onDetachedFromWindow() { super.onDetachedFromWindow() orientationListener.disable() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { layoutViewFinder(left, top, right, bottom) } override fun onViewAdded(child: View) { if (viewFinder == child) return // remove and read view to make sure it is in the back. // @TODO figure out why there was a z order issue in the first place and fix accordingly. removeView(viewFinder) addView(viewFinder, 0) } fun onBarCodeScanned(barCode: BarCodeScannerResult) { val emitter: EventEmitter by moduleRegistry() transformBarCodeScannerResultToViewCoordinates(barCode) val event = obtain(id, barCode, displayDensity) emitter.emit(id, event) } private val displayDensity: Float get() = resources.displayMetrics.density private fun transformBarCodeScannerResultToViewCoordinates(barCode: BarCodeScannerResult) { val cornerPoints = barCode.cornerPoints val previewWidth = width - leftPadding * 2 val previewHeight = height - topPadding * 2 // fix for problem with rotation when front camera is in use if (type == ExpoBarCodeScanner.CAMERA_TYPE_FRONT && getDeviceOrientation(viewContext) % 2 == 0) { cornerPoints.mapY { barCode.referenceImageHeight - cornerPoints[it] } } if (type == ExpoBarCodeScanner.CAMERA_TYPE_FRONT && getDeviceOrientation(viewContext) % 2 != 0) { cornerPoints.mapX { barCode.referenceImageWidth - cornerPoints[it] } } // end of fix cornerPoints.mapX { (cornerPoints[it] * previewWidth / barCode.referenceImageWidth.toFloat() + leftPadding) .roundToInt() } cornerPoints.mapY { (cornerPoints[it] * previewHeight / barCode.referenceImageHeight.toFloat() + topPadding) .roundToInt() } barCode.referenceImageHeight = height barCode.referenceImageWidth = width barCode.cornerPoints = cornerPoints } fun setCameraType(cameraType: Int) { type = cameraType if (!::viewFinder.isInitialized) { viewFinder = BarCodeScannerViewFinder( viewContext, cameraType, this, moduleRegistryDelegate ) addView(viewFinder) } else { viewFinder.setCameraType(cameraType) ExpoBarCodeScanner.instance.adjustPreviewLayout(cameraType) } } fun setBarCodeScannerSettings(settings: BarCodeScannerSettings?) { viewFinder.setBarCodeScannerSettings(settings) } private fun setActualDeviceOrientation(context: Context): Boolean { val innerActualDeviceOrientation = getDeviceOrientation(context) return if (actualDeviceOrientation != innerActualDeviceOrientation) { actualDeviceOrientation = innerActualDeviceOrientation ExpoBarCodeScanner.instance.actualDeviceOrientation = actualDeviceOrientation true } else { false } } private fun getDeviceOrientation(context: Context) = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation fun layoutViewFinder() { layoutViewFinder(left, top, right, bottom) } private fun layoutViewFinder(left: Int, top: Int, right: Int, bottom: Int) { if (!::viewFinder.isInitialized) { return } val width = (right - left).toFloat() val height = (bottom - top).toFloat() val viewfinderWidth: Int val viewfinderHeight: Int val ratio = viewFinder.ratio // Just fill the given space if (ratio * height < width) { viewfinderWidth = (ratio * height).toInt() viewfinderHeight = height.toInt() } else { viewfinderHeight = (width / ratio).toInt() viewfinderWidth = width.toInt() } val viewFinderPaddingX = ((width - viewfinderWidth) / 2).toInt() val viewFinderPaddingY = ((height - viewfinderHeight) / 2).toInt() leftPadding = viewFinderPaddingX topPadding = viewFinderPaddingY viewFinder.layout(viewFinderPaddingX, viewFinderPaddingY, viewFinderPaddingX + viewfinderWidth, viewFinderPaddingY + viewfinderHeight) postInvalidate(left, top, right, bottom) } init { ExpoBarCodeScanner.createInstance(getDeviceOrientation(viewContext)) } }
bsd-3-clause
13762cf604bb66e4127154ebab54daa0
33.664634
138
0.736324
4.637031
false
false
false
false
JoachimR/Bible2net
app/src/androidTest/java/de/reiss/bible2net/theword/note/list/NoteListFragmentTest.kt
1
3240
package de.reiss.bible2net.theword.note.list import androidx.lifecycle.MutableLiveData import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withText import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.architecture.AsyncLoad import de.reiss.bible2net.theword.model.Note import de.reiss.bible2net.theword.testutil.FragmentTest import de.reiss.bible2net.theword.testutil.assertDisplayed import de.reiss.bible2net.theword.testutil.assertNotDisplayed import de.reiss.bible2net.theword.testutil.assertRecyclerViewItemsCount import de.reiss.bible2net.theword.testutil.onRecyclerView import de.reiss.bible2net.theword.testutil.sampleNote import org.junit.Before import org.junit.Test class NoteListFragmentTest : FragmentTest<NoteListFragment>() { private val notesLiveData = MutableLiveData<AsyncLoad<FilteredNotes>>() private val mockedViewModel = mock<NoteListViewModel> { on { notesLiveData() } doReturn notesLiveData } override fun createFragment(): NoteListFragment = NoteListFragment.createInstance() .apply { viewModelProvider = mock { on { get(any<Class<NoteListViewModel>>()) } doReturn mockedViewModel } } @Before fun setUp() { launchFragment() } @Test fun whenLoadingThenShowLoading() { notesLiveData.postValue(AsyncLoad.loading()) assertDisplayed(R.id.note_list_loading) } @Test fun whenLoadedNoNotesThenShowEmptyState() { notesLiveData.postValue(AsyncLoad.success(FilteredNotes())) assertNotDisplayed(R.id.note_list_loading) assertDisplayed(R.id.note_list_no_notes) assertNotDisplayed(R.id.note_list_recycler_view) } @Test fun whenLoaded1NoteThenShowListWith1Item() { val notes = listOf(sampleNote(0)) notesLiveData.postValue(AsyncLoad.success(FilteredNotes(notes, notes, ""))) assertNotDisplayed(R.id.note_list_no_notes) assertDisplayed(R.id.note_list_recycler_view) assertRecyclerViewItemsCount(R.id.note_list_recycler_view, 1) assertNoteIsDisplayedAt(note = notes.first(), index = 0) } @Test fun whenLoaded99NotesThenShowListWith99Items() { val notes = (1..99).map { sampleNote(it) } notesLiveData.postValue(AsyncLoad.success(FilteredNotes(notes, notes, ""))) assertNotDisplayed(R.id.note_list_no_notes) assertNotDisplayed(R.id.note_list_loading) assertDisplayed(R.id.note_list_recycler_view) assertRecyclerViewItemsCount(R.id.note_list_recycler_view, 99) for ((index, note) in notes.withIndex()) { assertNoteIsDisplayedAt(note = note, index = index) } } private fun assertNoteIsDisplayedAt(note: Note, index: Int) { onRecyclerView( recyclerViewResId = R.id.note_list_recycler_view, itemPosition = index, viewInItem = R.id.note_list_item_text ) .check(matches(withText(note.noteText))) } }
gpl-3.0
45c1f487ea17e31e0719662d730dc29d
33.105263
88
0.70679
4.196891
false
true
false
false
AndroidX/androidx
playground-common/playground-plugin/src/test/kotlin/androidx/playground/SettingsParserTest.kt
3
2363
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.playground import com.google.common.truth.Truth.assertThat import org.junit.Test class SettingsParserTest { @Test fun parseProjects() { val projects = SettingsParser.findProjects( """ includeProject(":no:filepath", [BuildType.MAIN]) includeProject(":with:filepath", "some/dir", [BuildType.COMPOSE]) includeProject(":has:spaces:before:include", "dir2", [BuildType.MAIN]) includeProject(":has:comments:after", "dir3", [BuildType.MAIN]) // some comment // includeProject("commented", "should not be there", [BuildType.MAIN]) includeProject("no:build:type") includeProject("no:build:type:with:path", "dir4") """.trimIndent() ) assertThat( projects ).containsExactly( SettingsParser.IncludedProject( gradlePath = ":with:filepath", filePath = "some/dir" ), SettingsParser.IncludedProject( gradlePath = ":no:filepath", filePath = "no/filepath" ), SettingsParser.IncludedProject( gradlePath = ":has:spaces:before:include", filePath = "dir2" ), SettingsParser.IncludedProject( gradlePath = ":has:comments:after", filePath = "dir3" ), SettingsParser.IncludedProject( gradlePath = "no:build:type", filePath = "no/build/type" ), SettingsParser.IncludedProject( gradlePath = "no:build:type:with:path", filePath = "dir4" ) ) } }
apache-2.0
0d4e6eb6e12d2651ef388da082541f63
35.353846
91
0.586543
4.707171
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/Metadata.kt
1
510
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Metadata with connections and interactions. * * @param connections All connections for an object. * @param interactions All interactions for an object. */ @JsonClass(generateAdapter = true) data class Metadata<Connections_T, Interactions_T>( @Json(name = "connections") val connections: Connections_T? = null, @Json(name = "interactions") val interactions: Interactions_T? = null )
mit
401feac8574005ec7e5b6689eb22ab77
24.5
54
0.737255
4.047619
false
false
false
false
exponent/exponent
packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/MediaLibraryModule.kt
2
14772
package expo.modules.medialibrary import android.Manifest.permission.* import android.app.Activity import android.content.Context import android.content.Intent import android.content.IntentSender.SendIntentException import android.content.pm.PackageManager import android.database.ContentObserver import android.net.Uri import android.os.AsyncTask import android.os.Binder import android.os.Build import android.os.Bundle import android.os.Handler import android.provider.MediaStore import expo.modules.core.ExportedModule import expo.modules.core.ModuleRegistry import expo.modules.core.ModuleRegistryDelegate import expo.modules.core.Promise import expo.modules.core.interfaces.ActivityEventListener import expo.modules.core.interfaces.ActivityProvider import expo.modules.core.interfaces.ExpoMethod import expo.modules.core.interfaces.services.EventEmitter import expo.modules.core.interfaces.services.UIManager import expo.modules.interfaces.permissions.Permissions import expo.modules.medialibrary.MediaLibraryModule.Action import expo.modules.medialibrary.albums.AddAssetsToAlbum import expo.modules.medialibrary.albums.CreateAlbum import expo.modules.medialibrary.albums.DeleteAlbums import expo.modules.medialibrary.albums.GetAlbum import expo.modules.medialibrary.albums.GetAlbums import expo.modules.medialibrary.albums.RemoveAssetsFromAlbum import expo.modules.medialibrary.albums.getAssetsInAlbums import expo.modules.medialibrary.albums.migration.CheckIfAlbumShouldBeMigrated import expo.modules.medialibrary.albums.migration.MigrateAlbum import expo.modules.medialibrary.assets.CreateAsset import expo.modules.medialibrary.assets.DeleteAssets import expo.modules.medialibrary.assets.GetAssetInfo import expo.modules.medialibrary.assets.GetAssets class MediaLibraryModule( context: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate(), ) : ExportedModule(context), ActivityEventListener { private val uiManager: UIManager by moduleRegistry() private val permissions: Permissions? by moduleRegistry() private val activityProvider: ActivityProvider by moduleRegistry() private val eventEmitter: EventEmitter by moduleRegistry() private var imagesObserver: MediaStoreContentObserver? = null private var videosObserver: MediaStoreContentObserver? = null private var awaitingAction: Action? = null override fun getName() = "ExponentMediaLibrary" override fun getConstants(): Map<String, Any> { return mapOf( "MediaType" to MediaType.getConstants(), "SortBy" to SortBy.getConstants(), "CHANGE_LISTENER_NAME" to LIBRARY_DID_CHANGE_EVENT, ) } override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } @ExpoMethod fun requestPermissionsAsync(writeOnly: Boolean, promise: Promise) { Permissions.askForPermissionsWithPermissionsManager( permissions, promise, *getManifestPermissions(writeOnly) ) } @ExpoMethod fun getPermissionsAsync(writeOnly: Boolean, promise: Promise) { Permissions.getPermissionsWithPermissionsManager( permissions, promise, *getManifestPermissions(writeOnly) ) } @ExpoMethod fun saveToLibraryAsync( localUri: String, promise: Promise ) = rejectUnlessPermissionsGranted(promise, writeOnly = true) { CreateAsset(context, localUri, promise, false) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } @ExpoMethod fun createAssetAsync( localUri: String, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { CreateAsset(context, localUri, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } @ExpoMethod fun addAssetsToAlbumAsync( assetsId: List<String>, albumId: String, copyToAlbum: Boolean, promise: Promise ) = rejectUnlessPermissionsGranted(promise, writeOnly = false) { val action = actionIfUserGrantedPermission(promise) { AddAssetsToAlbum(context, assetsId.toTypedArray(), albumId, copyToAlbum, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } runActionWithPermissions(if (copyToAlbum) emptyList() else assetsId, action, promise) } @ExpoMethod fun removeAssetsFromAlbumAsync( assetsId: List<String>, albumId: String, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { val action = actionIfUserGrantedPermission(promise) { RemoveAssetsFromAlbum(context, assetsId.toTypedArray(), albumId, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } runActionWithPermissions(assetsId, action, promise) } @ExpoMethod fun deleteAssetsAsync( assetsId: List<String>, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { val action = actionIfUserGrantedPermission(promise) { DeleteAssets(context, assetsId.toTypedArray(), promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } runActionWithPermissions(assetsId, action, promise) } @ExpoMethod fun getAssetInfoAsync( assetId: String, options: Map<String, Any?>? /* unused on android atm */, promise: Promise ) = rejectUnlessPermissionsGranted(promise, writeOnly = false) { GetAssetInfo(context, assetId, promise).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } @ExpoMethod fun getAlbumsAsync( options: Map<String, Any?>? /* unused on android atm */, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { GetAlbums(context, promise).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } @ExpoMethod fun getAlbumAsync( albumName: String, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { GetAlbum(context, albumName, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } @ExpoMethod fun createAlbumAsync( albumName: String, assetId: String, copyAsset: Boolean, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { val action = actionIfUserGrantedPermission(promise) { CreateAlbum(context, albumName, assetId, copyAsset, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } runActionWithPermissions(if (copyAsset) emptyList() else listOf(assetId), action, promise) } @ExpoMethod fun deleteAlbumsAsync( albumIds: List<String>, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { val action = actionIfUserGrantedPermission(promise) { DeleteAlbums(context, albumIds, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } val assetIds = getAssetsInAlbums(context, *albumIds.toTypedArray()) runActionWithPermissions(assetIds, action, promise) } @ExpoMethod fun getAssetsAsync( assetOptions: Map<String, Any?>, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { GetAssets(context, assetOptions, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } @ExpoMethod fun migrateAlbumIfNeededAsync(albumId: String, promise: Promise) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { promise.resolve(null) return } val assets = MediaLibraryUtils.getAssetsById( context, null, *getAssetsInAlbums(context, albumId).toTypedArray() ) if (assets == null) { promise.reject(ERROR_NO_ALBUM, "Couldn't find album.") return } val albumsMap = assets // All files should have mime type, but if not, we can safely assume that // those without mime type shouldn't be move .filter { it.mimeType != null } .groupBy { it.parentFile } if (albumsMap.size != 1) { // Empty albums shouldn't be visible to users. That's why this is an error. promise.reject(ERROR_NO_ALBUM, "Found album is empty.") return } val albumDir = assets[0].parentFile if (albumDir == null) { promise.reject(ERROR_NO_ALBUM, "Couldn't get album path.") return } if (albumDir.canWrite()) { // Nothing to migrate promise.resolve(null) return } val action = actionIfUserGrantedPermission(promise) { MigrateAlbum(context, assets, albumDir.name, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } val needsToCheckPermissions = assets.map { it.assetId } runActionWithPermissions(needsToCheckPermissions, action, promise) } @ExpoMethod fun albumNeedsMigrationAsync( albumId: String, promise: Promise ) = rejectUnlessPermissionsGranted(promise) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { CheckIfAlbumShouldBeMigrated(context, albumId, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) return } promise.resolve(false) } // Library change observer @ExpoMethod fun startObserving(promise: Promise) { if (imagesObserver != null) { promise.resolve(null) return } // We need to register an observer for each type of assets, // because it seems that observing a parent directory (EXTERNAL_CONTENT) doesn't work well, // whereas observing directory of images or videos works fine. val handler = Handler() val contentResolver = context.contentResolver imagesObserver = MediaStoreContentObserver(handler, MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) .also { imageObserver -> contentResolver.registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, imageObserver ) } videosObserver = MediaStoreContentObserver(handler, MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) .also { videoObserver -> contentResolver.registerContentObserver( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, videoObserver ) } promise.resolve(null) } @ExpoMethod fun stopObserving(promise: Promise) { val contentResolver = context.contentResolver imagesObserver?.let { contentResolver.unregisterContentObserver(it) imagesObserver = null } videosObserver?.let { contentResolver.unregisterContentObserver(it) videosObserver = null } promise.resolve(null) } override fun onActivityResult( activity: Activity, requestCode: Int, resultCode: Int, data: Intent? ) { awaitingAction?.takeIf { requestCode == WRITE_REQUEST_CODE }?.let { it.runWithPermissions(resultCode == Activity.RESULT_OK) awaitingAction = null uiManager.unregisterActivityEventListener(this) } } override fun onNewIntent(intent: Intent) {} private val isMissingPermissions: Boolean get() = permissions ?.hasGrantedPermissions(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE) ?.not() ?: false private val isMissingWritePermission: Boolean get() = permissions ?.hasGrantedPermissions(WRITE_EXTERNAL_STORAGE) ?.not() ?: false private fun getManifestPermissions(writeOnly: Boolean): Array<String> { return listOfNotNull( WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE.takeIf { !writeOnly }, ACCESS_MEDIA_LOCATION.takeIf { Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q } ).toTypedArray() } private inline fun rejectUnlessPermissionsGranted(promise: Promise, writeOnly: Boolean = false, block: () -> Unit) { val missingPermissionsCondition = if (writeOnly) isMissingWritePermission else isMissingPermissions val missingPermissionsMessage = if (writeOnly) ERROR_NO_WRITE_PERMISSION_MESSAGE else ERROR_NO_PERMISSIONS_MESSAGE if (missingPermissionsCondition) { promise.reject(ERROR_NO_PERMISSIONS, missingPermissionsMessage) return } block() } private fun interface Action { fun runWithPermissions(permissionsWereGranted: Boolean) } private fun runActionWithPermissions(assetsId: List<String>, action: Action, promise: Promise) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val pathsWithoutPermissions = MediaLibraryUtils.getAssetsUris(context, assetsId) .filter { uri -> context.checkUriPermission( uri, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) != PackageManager.PERMISSION_GRANTED } if (pathsWithoutPermissions.isNotEmpty()) { val deleteRequest = MediaStore.createWriteRequest(context.contentResolver, pathsWithoutPermissions) val activity = activityProvider.currentActivity try { uiManager.registerActivityEventListener(this) awaitingAction = action activity.startIntentSenderForResult( deleteRequest.intentSender, WRITE_REQUEST_CODE, null, 0, 0, 0 ) } catch (e: SendIntentException) { promise.reject(ERROR_UNABLE_TO_ASK_FOR_PERMISSIONS, ERROR_UNABLE_TO_ASK_FOR_PERMISSIONS_MESSAGE) awaitingAction = null } return } } action.runWithPermissions(true) } private fun actionIfUserGrantedPermission( promise: Promise, block: () -> Unit ) = Action { permissionsWereGranted -> if (!permissionsWereGranted) { promise.reject(ERROR_NO_PERMISSIONS, ERROR_USER_DID_NOT_GRANT_WRITE_PERMISSIONS_MESSAGE) return@Action } block() } private inner class MediaStoreContentObserver(handler: Handler, private val mMediaType: Int) : ContentObserver(handler) { private var mAssetsTotalCount = getAssetsTotalCount(mMediaType) override fun onChange(selfChange: Boolean) { this.onChange(selfChange, null) } override fun onChange(selfChange: Boolean, uri: Uri?) { val newTotalCount = getAssetsTotalCount(mMediaType) // Send event to JS only when assets count has been changed - to filter out some unnecessary events. // It's not perfect solution if someone adds and deletes the same number of assets in a short period of time, but I hope these events will not be batched. if (mAssetsTotalCount != newTotalCount) { mAssetsTotalCount = newTotalCount eventEmitter.emit(LIBRARY_DID_CHANGE_EVENT, Bundle()) } } private fun getAssetsTotalCount(mediaType: Int): Int = context.contentResolver.query( EXTERNAL_CONTENT_URI, null, "${MediaStore.Files.FileColumns.MEDIA_TYPE} == $mediaType", null, null ).use { countCursor -> countCursor?.count ?: 0 } } private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() companion object { private const val WRITE_REQUEST_CODE = 7463 } }
bsd-3-clause
35a9d85a77dbe48267e475fb73bd1671
32.04698
160
0.720011
4.562075
false
false
false
false
liuche/focus-android
app/src/main/java/org/mozilla/focus/autocomplete/AutocompleteListFragment.kt
1
11641
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.autocomplete import android.app.Fragment import android.content.Context import android.graphics.Color import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.support.v7.widget.helper.ItemTouchHelper.SimpleCallback import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.CompoundButton import android.widget.TextView import kotlinx.android.synthetic.main.fragment_autocomplete_customdomains.* import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.launch import org.mozilla.focus.R import org.mozilla.focus.settings.BaseSettingsFragment import org.mozilla.focus.telemetry.TelemetryWrapper import java.util.Collections import org.mozilla.focus.utils.ViewUtils /** * Fragment showing settings UI listing all custom autocomplete domains entered by the user. */ open class AutocompleteListFragment : Fragment() { /** * ItemTouchHelper for reordering items in the domain list. */ val itemTouchHelper: ItemTouchHelper = ItemTouchHelper( object : SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) { override fun onMove( recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean { if (recyclerView == null || viewHolder == null || target == null) { return false } val from = viewHolder.adapterPosition val to = target.adapterPosition (recyclerView.adapter as DomainListAdapter).move(from, to) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {} override fun getMovementFlags(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?): Int { if (viewHolder is AddActionViewHolder) { return ItemTouchHelper.Callback.makeMovementFlags(0, 0) } return super.getMovementFlags(recyclerView, viewHolder) } override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { super.onSelectedChanged(viewHolder, actionState) if (viewHolder is DomainViewHolder) { viewHolder.onSelected() } } override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?) { super.clearView(recyclerView, viewHolder) if (viewHolder is DomainViewHolder) { viewHolder.onCleared() } } override fun canDropOver( recyclerView: RecyclerView?, current: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean { if (target is AddActionViewHolder) { return false } return super.canDropOver(recyclerView, current, target) } }) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } /** * In selection mode the user can select and remove items. In non-selection mode the list can * be reordered by the user. */ open fun isSelectionMode() = false override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater!!.inflate(R.layout.fragment_autocomplete_customdomains, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { domainList.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) domainList.adapter = DomainListAdapter() domainList.setHasFixedSize(true) if (!isSelectionMode()) { itemTouchHelper.attachToRecyclerView(domainList) } } override fun onResume() { super.onResume() (activity as BaseSettingsFragment.ActionBarUpdater).apply { updateTitle(R.string.preference_autocomplete_subitem_customlist) updateIcon(R.drawable.ic_back) } (domainList.adapter as DomainListAdapter).refresh(activity) { activity?.invalidateOptionsMenu() } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_autocomplete_list, menu) } override fun onPrepareOptionsMenu(menu: Menu?) { val removeItem = menu?.findItem(R.id.remove) removeItem?.let { it.isVisible = isSelectionMode() || domainList.adapter.itemCount > 1 val isEnabled = !isSelectionMode() || (domainList.adapter as DomainListAdapter).selection().isNotEmpty() ViewUtils.setMenuItemEnabled(it, isEnabled) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { R.id.remove -> { fragmentManager .beginTransaction() .replace(R.id.container, AutocompleteRemoveFragment()) .addToBackStack(null) .commit() true } else -> super.onOptionsItemSelected(item) } /** * Adapter implementation for the list of custom autocomplete domains. */ inner class DomainListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val domains: MutableList<String> = mutableListOf() private val selectedDomains: MutableList<String> = mutableListOf() fun refresh(context: Context, body: (() -> Unit)? = null) { launch(UI) { val updatedDomains = async { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }.await() domains.clear() domains.addAll(updatedDomains) notifyDataSetChanged() body?.invoke() } } override fun getItemViewType(position: Int) = when (position) { domains.size -> AddActionViewHolder.LAYOUT_ID else -> DomainViewHolder.LAYOUT_ID } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder = when (viewType) { AddActionViewHolder.LAYOUT_ID -> AddActionViewHolder( this@AutocompleteListFragment, LayoutInflater.from(parent!!.context).inflate(viewType, parent, false)) DomainViewHolder.LAYOUT_ID -> DomainViewHolder( LayoutInflater.from(parent!!.context).inflate(viewType, parent, false)) else -> throw IllegalArgumentException("Unknown view type: $viewType") } override fun getItemCount(): Int = domains.size + if (isSelectionMode()) 0 else 1 override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { if (holder is DomainViewHolder) { holder.bind( domains[position], isSelectionMode(), selectedDomains, itemTouchHelper, this@AutocompleteListFragment) } } override fun onViewRecycled(holder: RecyclerView.ViewHolder?) { if (holder is DomainViewHolder) { holder.checkBoxView.setOnCheckedChangeListener(null) } } fun selection(): List<String> = selectedDomains fun move(from: Int, to: Int) { Collections.swap(domains, from, to) notifyItemMoved(from, to) launch(CommonPool) { CustomAutocomplete.saveDomains(activity.applicationContext, domains) TelemetryWrapper.reorderAutocompleteDomainEvent(from, to) } } } /** * ViewHolder implementation for a domain item in the list. */ private class DomainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val domainView: TextView = itemView.findViewById(R.id.domainView) val checkBoxView: CheckBox = itemView.findViewById(R.id.checkbox) val handleView: View = itemView.findViewById(R.id.handleView) companion object { val LAYOUT_ID = R.layout.item_custom_domain } fun bind( domain: String, isSelectionMode: Boolean, selectedDomains: MutableList<String>, itemTouchHelper: ItemTouchHelper, fragment: AutocompleteListFragment) { domainView.text = domain checkBoxView.visibility = if (isSelectionMode) View.VISIBLE else View.GONE checkBoxView.isChecked = selectedDomains.contains(domain) checkBoxView.setOnCheckedChangeListener({ _: CompoundButton, isChecked: Boolean -> if (isChecked) { selectedDomains.add(domain) } else { selectedDomains.remove(domain) } fragment.activity?.invalidateOptionsMenu() }) handleView.visibility = if (isSelectionMode) View.GONE else View.VISIBLE handleView.setOnTouchListener({ _, event -> if (event.actionMasked == MotionEvent.ACTION_DOWN) { itemTouchHelper.startDrag(this) } false }) if (isSelectionMode) { itemView.setOnClickListener({ checkBoxView.isChecked = !checkBoxView.isChecked }) } } fun onSelected() { itemView.setBackgroundColor(Color.DKGRAY) } fun onCleared() { itemView.setBackgroundColor(0) } } /** * ViewHolder implementation for a "Add custom domain" item at the bottom of the list. */ private class AddActionViewHolder( val fragment: AutocompleteListFragment, itemView: View ) : RecyclerView.ViewHolder(itemView) { init { itemView.setOnClickListener { fragment.fragmentManager .beginTransaction() .replace(R.id.container, AutocompleteAddFragment()) .addToBackStack(null) .commit() } } companion object { val LAYOUT_ID = R.layout.item_add_custom_domain } } }
mpl-2.0
e3dc6fbf0a12810e474c39c8e0bac936
36.430868
119
0.5972
5.673002
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/template/postfix/editable/RsEditablePostfixTemplate.kt
3
3466
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.template.postfix.editable import com.intellij.codeInsight.template.impl.TemplateImpl import com.intellij.codeInsight.template.impl.TextExpression import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider import com.intellij.codeInsight.template.postfix.templates.editable.EditablePostfixTemplateWithMultipleExpressions import com.intellij.openapi.editor.Document import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.containers.ContainerUtil import org.rust.ide.template.postfix.RsExprParentsSelector import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsExprStmt class RsEditablePostfixTemplate( templateId: String, templateName: String, templateText: String, example: String, expressionTypes: Set<RsPostfixTemplateExpressionCondition>, useTopmostExpression: Boolean, provider: PostfixTemplateProvider ) : EditablePostfixTemplateWithMultipleExpressions<RsPostfixTemplateExpressionCondition>( templateId, templateName, createTemplate(templateText), example, expressionTypes, useTopmostExpression, provider ) { override fun getExpressions(context: PsiElement, document: Document, offset: Int): MutableList<PsiElement> { if (DumbService.getInstance(context.project).isDumb) return mutableListOf() val allExpressions = RsExprParentsSelector().getExpressions(context, document, offset) val expressions = if (myUseTopmostExpression) { val topmostExpr = allExpressions.maxByOrNull { it.textLength } ?: return mutableListOf() mutableListOf(topmostExpr) } else { allExpressions } // accept expression of any type if list is empty (it's default state) if (myExpressionConditions.isEmpty() && context is RsExpr) return expressions.toMutableList() return ContainerUtil.filter(expressions, Conditions.and({ e: PsiElement -> (PSI_ERROR_FILTER.value(e) && e is RsExpr && e.textRange.endOffset == offset) }, expressionCompositeCondition)) } override fun getTopmostExpression(element: PsiElement): PsiElement { return if (element.parent is RsExprStmt) element.parent else element } override fun isBuiltin(): Boolean = false companion object { private val PSI_ERROR_FILTER = Condition { element: PsiElement? -> element != null && !PsiTreeUtil.hasErrorElements(element) } fun createTemplate(templateText: String): TemplateImpl { val template = TemplateImpl("fakeKey", templateText, "") template.isToReformat = false template.parseSegments() // turn segments (words surrounded by '$' char) into variables for (i in 0 until template.segmentsCount) { val segmentName = template.getSegmentName(i) val internalName = segmentName == "EXPR" || segmentName == TemplateImpl.ARG || segmentName in TemplateImpl.INTERNAL_VARS_SET if (!internalName) template.addVariable(segmentName, TextExpression(segmentName), true) } return template } } }
mit
9599ff55405a39cb4576c6731bec8942
41.790123
140
0.722447
4.86115
false
false
false
false
nonylene/PhotoLinkViewer
app/src/main/java/net/nonylene/photolinkviewer/TwitterOAuthActivity.kt
1
12646
package net.nonylene.photolinkviewer import android.content.ContentValues import android.content.Context import android.content.Intent import android.database.Cursor import android.database.CursorIndexOutOfBoundsException import android.database.sqlite.SQLiteException import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Base64 import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.ListView import android.widget.Toast import butterknife.bindView import com.twitter.sdk.android.core.Callback import com.twitter.sdk.android.core.Result import com.twitter.sdk.android.core.TwitterSession import com.twitter.sdk.android.core.identity.TwitterLoginButton import net.nonylene.photolinkviewer.dialog.DeleteDialogFragment import net.nonylene.photolinkviewer.tool.* import twitter4j.AsyncTwitter import twitter4j.AsyncTwitterFactory import twitter4j.TwitterAdapter import twitter4j.TwitterException import twitter4j.TwitterFactory import twitter4j.TwitterMethod import twitter4j.User import twitter4j.auth.AccessToken import twitter4j.auth.RequestToken class TwitterOAuthActivity : AppCompatActivity(), DeleteDialogFragment.DeleteDialogCallBack { private var twitter: AsyncTwitter? = null private var requestToken: RequestToken? = null private var myCursorAdapter: MyCursorAdapter? = null private val database by lazy { MySQLiteOpenHelper(applicationContext).writableDatabase } private val preferences by lazy { getSharedPreferences("preference", Context.MODE_PRIVATE) } private val listView : ListView by bindView(R.id.accounts_list) private val twitterOAuthButton : TwitterLoginButton by bindView(R.id.twitter_oauth_button) private val twitterListener = object : TwitterAdapter() { override fun onException(exception: TwitterException?, method: TwitterMethod?) { Log.e("twitter", exception!!.toString()) } override fun gotOAuthRequestToken(token: RequestToken?) { requestToken = token val uri = Uri.parse(requestToken!!.authorizationURL) startActivity(Intent(Intent.ACTION_VIEW, uri)) } override fun gotOAuthAccessToken(token: AccessToken) { fetchAndSaveUserData(token) } } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.toauth) twitterOAuthButton.callback = object: Callback<TwitterSession>() { override fun failure(e: com.twitter.sdk.android.core.TwitterException) { e.printStackTrace() Toast.makeText(this@TwitterOAuthActivity, getString(R.string.toauth_failed_token), Toast.LENGTH_LONG).show() } override fun success(result: Result<TwitterSession>) { result.data.authToken.let { Thread(Runnable { fetchAndSaveUserData(AccessToken(it.token, it.secret)) }).start() } } } setListView() updateProfiles() } private fun setListView() { // radio button listView.choiceMode = ListView.CHOICE_MODE_SINGLE // choose account listView.setOnItemClickListener { parent, view, position, id -> changeAccount(id.toInt()) } listView.setOnItemLongClickListener { parent, view, position, id -> val cursor = listView.getItemAtPosition(position) as Cursor with(DeleteDialogFragment()) { setDeleteDialogCallBack(this@TwitterOAuthActivity) arguments = Bundle().apply { putString("screen_name", cursor.getString(cursor.getColumnIndex("userName"))) } show([email protected], "delete") } true } // not to lock try { val cursor = database.rawQuery("select rowid _id, * from accounts", null) myCursorAdapter = MyCursorAdapter(applicationContext, cursor, true) listView.adapter = myCursorAdapter // check current radio button val accountPosition = preferences.getInt("account", 0) (0..listView.count - 1).forEach { val c = listView.getItemAtPosition(it) as Cursor if (c.getInt(c.getColumnIndex("_id")) == accountPosition) { listView.setItemChecked(it, true) } } } catch (e: SQLiteException) { Log.e("SQLite", e.toString()) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.twitter_oauth_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.twitter_old_oauth -> { try { twitter = AsyncTwitterFactory().instance.apply { setOAuthConsumer(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET) addListener(twitterListener) getOAuthRequestTokenAsync("plvtwitter://callback") } } catch (e: Exception) { Log.e("twitter", e.toString()) } return true } } return super.onOptionsItemSelected(item) } override fun onDeleteConfirmed(userName: String) { var toastText: String? = null try { toastText = getString(R.string.delete_account_toast) with(database) { beginTransaction() // quotation is required. delete("accounts", "userName = ?", arrayOf(userName)) // commit setTransactionSuccessful() endTransaction() } val new_cursor = database.rawQuery("select rowid _id, * from accounts", null) // renew listView // i want to use content provider and cursor loader in future. myCursorAdapter!!.swapCursor(new_cursor) PLVUtils.refreshTwitterTokens(database) } catch (e: SQLiteException) { toastText = getString(R.string.delete_failed_toast) e.printStackTrace() } finally { Toast.makeText(this, toastText, Toast.LENGTH_LONG).show() } } private fun updateProfiles() { if (preferences.isTwitterOAuthed()) { try { val twitter = MyAsyncTwitter.getAsyncTwitterFromDB(database, applicationContext) twitter.addListener(object : TwitterAdapter() { override fun gotUserDetail(user: User) { try { val values = ContentValues() values.put("userName", user.screenName) values.put("icon", user.biggerProfileImageURL) // open database with(database) { beginTransaction() update("accounts", values, "userId = ?", arrayOf(user.id.toString())) setTransactionSuccessful() endTransaction() } runOnUiThread { // renew ui myCursorAdapter!!.swapCursor(database.rawQuery("select rowid _id, * from accounts", null)) } } catch (e: SQLiteException) { Log.e("SQL", e.toString()) } } }) // move cursor focus val cursor = database.rawQuery("select rowid _id, userId from accounts", null) cursor.moveToFirst() PLVUtils.refreshTwitterTokens(database) twitter.showUser(cursor.getLong(cursor.getColumnIndex("userId"))) while (cursor.moveToNext()) { twitter.showUser(cursor.getLong(cursor.getColumnIndex("userId"))) } } catch (e: CursorIndexOutOfBoundsException) { Log.e("cursor", e.toString()) Toast.makeText(applicationContext, getString(R.string.twitter_async_select), Toast.LENGTH_LONG).show() } } } override fun onNewIntent(intent: Intent) { intent.data?.let { val oauth = it.getQueryParameter("oauth_verifier") if (oauth != null) { twitter!!.getOAuthAccessTokenAsync(requestToken, oauth) } else { Toast.makeText(this@TwitterOAuthActivity, getString(R.string.toauth_failed_token), Toast.LENGTH_LONG).show() } } } // this method must be run asynchronously. private fun fetchAndSaveUserData(token: AccessToken) { try { // get oauthed user_name and user_id and icon_url val twitterNotAsync = TwitterFactory().instance.apply { setOAuthConsumer(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET) oAuthAccessToken = token } val myId = twitterNotAsync.id val user = twitterNotAsync.showUser(myId) val screenName = user.screenName val icon = user.biggerProfileImageURL // encrypt twitter tokens by key // save encrypted keys to database val values = ContentValues().apply { put("userName", screenName) put("userId", myId) put("icon", icon) val key = Encryption.generate() put("token", Encryption.encrypt(token.token.toByteArray(), key)) put("token_secret", Encryption.encrypt(token.tokenSecret.toByteArray(), key)) put("key", Base64.encodeToString(key.encoded, Base64.DEFAULT)) } // open database with(database) { beginTransaction() // if exists... delete("accounts", "userId = ?", arrayOf(myId.toString())) // insert account information insert("accounts", null, values) // commit setTransactionSuccessful() endTransaction() } val cursorNew = database.rawQuery("select rowid _id, userId from accounts where userId = ?", arrayOf(myId.toString())).apply { moveToFirst() } val account = cursorNew.getInt(cursorNew.getColumnIndex("_id")) // set oauth_completed frag preferences.edit() .putIsTwitterOAuthed(true) .putDefaultTwitterScreenName(screenName) .putInt("account", account) .apply() PLVUtils.refreshTwitterTokens(database) //putting cue to UI Thread runOnUiThread { Toast.makeText(this@TwitterOAuthActivity, getString(R.string.toauth_succeeded_token) + " @" + screenName, Toast.LENGTH_LONG).show() setListView() } } catch (e: TwitterException) { e.printStackTrace() //putting cue to UI Thread runOnUiThread { Toast.makeText(this@TwitterOAuthActivity, getString(R.string.toauth_failed_twitter4j), Toast.LENGTH_LONG).show() } finish() } catch (e: SQLiteException) { e.printStackTrace() } } private fun changeAccount(rowid: Int) { // save rowid and screen name to preference val cursor = database.rawQuery("select userName from accounts where rowid = ?", arrayOf(rowid.toString())).apply { moveToFirst() } preferences.edit() .putInt("account", rowid) .putDefaultTwitterScreenName(cursor.getString(cursor.getColumnIndex("userName"))) .apply() } override fun onDestroy() { super.onDestroy() database.close() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Pass the activity result to the login button. twitterOAuthButton.onActivityResult(requestCode, resultCode, data); } }
gpl-2.0
9394708ecdfd561050efaeaa4c59559d
39.405751
147
0.584375
5.264779
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/entities/PickerItem.kt
1
1538
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.entities import java.awt.Color data class PickerItem ( val id: String, val title: String = "", val description: String = "", val author: String = "", var image: String = "", val thumbnail: String = "", val footer: String = "", val color: Color? = null, val url: String = "" )
mit
bcb959a96499b37277fd67198070a792
37.475
70
0.684005
4.296089
false
false
false
false
androidx/androidx
wear/watchface/watchface/src/main/java/androidx/wear/watchface/ComplicationSlot.kt
3
53105
/* * 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.wear.watchface import android.graphics.Canvas import android.graphics.Rect import android.graphics.RectF import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import androidx.annotation.ColorInt import androidx.annotation.IntDef import androidx.annotation.Px import androidx.annotation.RestrictTo import androidx.annotation.UiThread import androidx.annotation.WorkerThread import androidx.wear.watchface.complications.ComplicationSlotBounds import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy import androidx.wear.watchface.complications.data.ComplicationData import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.data.EmptyComplicationData import androidx.wear.watchface.complications.data.NoDataComplicationData import androidx.wear.watchface.RenderParameters.HighlightedElement import androidx.wear.watchface.complications.data.ComplicationDisplayPolicies import androidx.wear.watchface.complications.data.ComplicationExperimental import androidx.wear.watchface.complications.data.toApiComplicationData import androidx.wear.watchface.data.BoundingArcWireFormat import androidx.wear.watchface.style.UserStyleSetting import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotOverlay import java.lang.Integer.min import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.sin import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.time.ZonedDateTime import java.util.Objects /** * Interface for rendering complicationSlots onto a [Canvas]. These should be created by * [CanvasComplicationFactory.create]. If state needs to be shared with the [Renderer] that should * be set up inside [onRendererCreated]. */ @JvmDefaultWithCompatibility public interface CanvasComplication { /** Interface for observing when a [CanvasComplication] needs the screen to be redrawn. */ public interface InvalidateCallback { /** Signals that the complication needs to be redrawn. Can be called on any thread. */ public fun onInvalidate() } /** * Called once on a background thread before any subsequent UI thread rendering to inform the * CanvasComplication of the [Renderer] which is useful if they need to share state. Note the * [Renderer] is created asynchronously which is why we can't pass it in via * [CanvasComplicationFactory.create] as it may not be available at that time. */ @WorkerThread public fun onRendererCreated(renderer: Renderer) {} /** * Draws the complication defined by [getData] into the canvas with the specified bounds. * This will usually be called by user watch face drawing code, but the system may also call it * for complication selection UI rendering. The width and height will be the same as that * computed by computeBounds but the translation and canvas size may differ. * * @param canvas The [Canvas] to render into * @param bounds A [Rect] describing the bounds of the complication * @param zonedDateTime The [ZonedDateTime] to render with * @param renderParameters The current [RenderParameters] * @param slotId The Id of the [ComplicationSlot] being rendered */ @UiThread public fun render( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters, slotId: Int ) /** * Draws a highlight for a [ComplicationSlotBoundsType.ROUND_RECT] complication. The default * implementation does this by drawing a dashed line around the complication, other visual * effects may be used if desired. * * @param canvas The [Canvas] to render into * @param bounds A [Rect] describing the bounds of the complication * @param boundsType The [ComplicationSlotBoundsType] of the complication * @param zonedDateTime The [ZonedDateTime] to render the highlight with * @param color The color to render the highlight with */ // TODO(b/230364881): Deprecate this when BoundingArc is no longer experimental. public fun drawHighlight( canvas: Canvas, bounds: Rect, @ComplicationSlotBoundsType boundsType: Int, zonedDateTime: ZonedDateTime, @ColorInt color: Int ) /** * Draws a highlight for a [ComplicationSlotBoundsType.ROUND_RECT] complication. The default * implementation does this by drawing a dashed line around the complication, other visual effects * may be used if desired. * * @param canvas The [Canvas] to render into * @param bounds A [Rect] describing the bounds of the complication * @param boundsType The [ComplicationSlotBoundsType] of the complication * @param zonedDateTime The [ZonedDateTime] to render the highlight with * @param color The color to render the highlight with */ @ComplicationExperimental public fun drawHighlight( canvas: Canvas, bounds: Rect, @ComplicationSlotBoundsType boundsType: Int, zonedDateTime: ZonedDateTime, @ColorInt color: Int, boundingArc: BoundingArc? ) { drawHighlight(canvas, bounds, boundsType, zonedDateTime, color) } /** Returns the [ComplicationData] to render with. */ public fun getData(): ComplicationData /** * Sets the [ComplicationData] to render with and loads any [Drawable]s contained within the * ComplicationData. You can choose whether this is done synchronously or asynchronously via * [loadDrawablesAsynchronous]. When any asynchronous loading has completed * [InvalidateCallback.onInvalidate] must be called. * * @param complicationData The [ComplicationData] to render with * @param loadDrawablesAsynchronous Whether or not any drawables should be loaded asynchronously */ public fun loadData(complicationData: ComplicationData, loadDrawablesAsynchronous: Boolean) } /** Interface for determining whether a tap hits a complication. */ @JvmDefaultWithCompatibility public interface ComplicationTapFilter { /** * Performs a hit test, returning `true` if the supplied coordinates in pixels are within the * the provided [complicationSlot] scaled to [screenBounds]. * * @param complicationSlot The [ComplicationSlot] to perform a hit test for. * @param screenBounds A [Rect] describing the bounds of the display. * @param x The screen space X coordinate in pixels. * @param y The screen space Y coordinate in pixels. * @param includeMargins Whether or not the margins should be included */ @Suppress("DEPRECATION") public fun hitTest( complicationSlot: ComplicationSlot, screenBounds: Rect, @Px x: Int, @Px y: Int, includeMargins: Boolean ): Boolean = hitTest(complicationSlot, screenBounds, x, y) /** * Performs a hit test, returning `true` if the supplied coordinates in pixels are within the * the provided [complicationSlot] scaled to [screenBounds]. * * @param complicationSlot The [ComplicationSlot] to perform a hit test for. * @param screenBounds A [Rect] describing the bounds of the display. * @param x The screen space X coordinate in pixels. * @param y The screen space Y coordinate in pixels. */ @Deprecated( "hitTest without specifying includeMargins is deprecated", replaceWith = ReplaceWith("hitTest(ComplicationSlot, Rect, Int, Int, Boolean)") ) public fun hitTest( complicationSlot: ComplicationSlot, screenBounds: Rect, @Px x: Int, @Px y: Int ): Boolean = hitTest(complicationSlot, screenBounds, x, y, false) } /** Default [ComplicationTapFilter] for [ComplicationSlotBoundsType.ROUND_RECT] complicationSlots. */ public class RoundRectComplicationTapFilter : ComplicationTapFilter { override fun hitTest( complicationSlot: ComplicationSlot, screenBounds: Rect, @Px x: Int, @Px y: Int, includeMargins: Boolean ): Boolean = complicationSlot.computeBounds(screenBounds, includeMargins).contains(x, y) } /** Default [ComplicationTapFilter] for [ComplicationSlotBoundsType.BACKGROUND] complicationSlots. */ public class BackgroundComplicationTapFilter : ComplicationTapFilter { override fun hitTest( complicationSlot: ComplicationSlot, screenBounds: Rect, @Px x: Int, @Px y: Int, includeMargins: Boolean ): Boolean = false } /** @hide */ @IntDef( value = [ ComplicationSlotBoundsType.ROUND_RECT, ComplicationSlotBoundsType.BACKGROUND, ComplicationSlotBoundsType.EDGE ] ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public annotation class ComplicationSlotBoundsType { public companion object { /** The default, most complication slots are either circular or rounded rectangles. */ public const val ROUND_RECT: Int = 0 /** * For a full screen image complication slot drawn behind the watch face. Note you can only * have a single background complication slot. */ public const val BACKGROUND: Int = 1 /** For edge of screen complication slots. */ public const val EDGE: Int = 2 } } /** * In combination with a bounding [Rect], BoundingArc describes the geometry of an edge * complication. * * @property startAngle The staring angle of the arc in degrees (0 degrees = 12 o'clock position). * @property totalAngle The total angle of the arc on degrees. * @property thickness The thickness of the arc as a fraction of * min(boundingRect.width, boundingRect.height). */ @ComplicationExperimental public class BoundingArc(val startAngle: Float, val totalAngle: Float, @Px val thickness: Float) { /** * Detects whether the supplied point falls within the edge complication's arc. * * @param rect The bounding [Rect] of the edge complication * @param x The x-coordinate of the point to test in pixels * @param y The y-coordinate of the point to test in pixels * @return Whether or not the point is within the arc */ fun hitTest(rect: Rect, @Px x: Float, @Px y: Float): Boolean { val width = rect.width() val height = rect.height() val thicknessPx = min(width, height).toDouble() * thickness val halfWidth = width.toDouble() * 0.5 val halfHeight = height.toDouble() * 0.5 // Rotate to a local coordinate space where the y axis is in the middle of the arc var x0 = (x - rect.left).toDouble() - halfWidth var y0 = (y - rect.top).toDouble() - halfHeight val angle = startAngle + 0.5f * totalAngle val rotAngle = -Math.toRadians(angle.toDouble()) x0 = x0 * cos(rotAngle) - y0 * sin(rotAngle) + halfWidth y0 = x0 * sin(rotAngle) + y0 * cos(rotAngle) + halfHeight // Copied from WearCurvedTextView... val radius2 = min(width, height).toDouble() / 2.0 val radius1 = radius2 - thicknessPx val dx = x0 - (width.toDouble() / 2.0) val dy = y0 - (height.toDouble() / 2.0) val r2 = dx * dx + dy * dy if (r2 < radius1 * radius1 || r2 > radius2 * radius2) { return false } // Since we are symmetrical on the Y-axis, we can constrain the angle to the x>=0 quadrants. return Math.toDegrees(atan2(abs(dx), -dy)) < (totalAngle / 2.0) } override fun toString(): String { return "ArcParams(startAngle=$startAngle, totalArcAngle=$totalAngle, " + "thickness=$thickness)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BoundingArc if (startAngle != other.startAngle) return false if (totalAngle != other.totalAngle) return false if (thickness != other.thickness) return false return true } override fun hashCode(): Int { var result = startAngle.hashCode() result = 31 * result + totalAngle.hashCode() result = 31 * result + thickness.hashCode() return result } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun toWireFormat() = BoundingArcWireFormat(startAngle, totalAngle, thickness) } /** * Represents the slot an individual complication on the screen may go in. The number of * ComplicationSlots is fixed (see [ComplicationSlotsManager]) but ComplicationSlots can be * enabled or disabled via [UserStyleSetting.ComplicationSlotsUserStyleSetting]. * * Taps on the watch are tested first against each ComplicationSlot's * [ComplicationSlotBounds.perComplicationTypeBounds] for the relevant [ComplicationType]. Its * assumed that [ComplicationSlotBounds.perComplicationTypeBounds] don't overlap. If no intersection * was found then taps are checked against [ComplicationSlotBounds.perComplicationTypeBounds] * expanded by [ComplicationSlotBounds.perComplicationTypeMargins]. Expanded bounds can overlap * so the [ComplicationSlot] with the lowest id that intersects the coordinates, if any, is * selected. * * @property id The Watch Face's ID for the complication slot. * @param accessibilityTraversalIndex Used to sort Complications when generating accessibility * content description labels. * @property boundsType The [ComplicationSlotBoundsType] of the complication slot. * @param bounds The complication slot's [ComplicationSlotBounds]. * @property canvasComplicationFactory The [CanvasComplicationFactory] used to generate a * [CanvasComplication] for rendering the complication. The factory allows us to decouple * ComplicationSlot from potentially expensive asset loading. * @param supportedTypes The list of [ComplicationType]s accepted by this complication slot. Used * during complication data source selection, this list should be non-empty. * @param defaultPolicy The [DefaultComplicationDataSourcePolicy] which controls the * initial complication data source when the watch face is first installed. * @param defaultDataSourceType The default [ComplicationType] for the default complication data * source. * @property initiallyEnabled At creation a complication slot is either enabled or disabled. This * can be overridden by a [ComplicationSlotsUserStyleSetting] (see * [ComplicationSlotOverlay.enabled]). * Editors need to know the initial state of a complication slot to predict the effects of making a * style change. * @param configExtras Extras to be merged into the Intent sent when invoking the complication data * source chooser activity. This features is intended for OEM watch faces where they have elements * that behave like a complication but are in fact entirely watch face specific. * @property fixedComplicationDataSource Whether or not the complication data source is fixed (i.e. * can't be changed by the user). This is useful for watch faces built around specific * complications. * @property tapFilter The [ComplicationTapFilter] used to determine whether or not a tap hit the * complication slot. */ public class ComplicationSlot @ComplicationExperimental internal constructor( public val id: Int, accessibilityTraversalIndex: Int, @ComplicationSlotBoundsType public val boundsType: Int, bounds: ComplicationSlotBounds, public val canvasComplicationFactory: CanvasComplicationFactory, public val supportedTypes: List<ComplicationType>, defaultPolicy: DefaultComplicationDataSourcePolicy, defaultDataSourceType: ComplicationType, @get:JvmName("isInitiallyEnabled") public val initiallyEnabled: Boolean, configExtras: Bundle, @get:JvmName("isFixedComplicationDataSource") public val fixedComplicationDataSource: Boolean, public val tapFilter: ComplicationTapFilter, nameResourceId: Int?, screenReaderNameResourceId: Int?, // TODO(b/230364881): This should really be public but some metalava bug is preventing // @ComplicationExperimental from working on the getter so it's currently hidden. /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public val boundingArc: BoundingArc? ) { /** * The [ComplicationSlotsManager] this is attached to. Only set after the * [ComplicationSlotsManager] has been created. */ internal lateinit var complicationSlotsManager: ComplicationSlotsManager /** * Extras to be merged into the Intent sent when invoking the complication data source chooser * activity. */ public var configExtras: Bundle = configExtras set(value) { field = value complicationSlotsManager.configExtrasChangeCallback ?.onComplicationSlotConfigExtrasChanged() } /** * The [CanvasComplication] used to render the complication. This can't be used until after * [WatchFaceService.createWatchFace] has completed. */ public val renderer: CanvasComplication by lazy { canvasComplicationFactory.create( complicationSlotsManager.watchState, object : CanvasComplication.InvalidateCallback { override fun onInvalidate() { if (this@ComplicationSlot::invalidateListener.isInitialized) { invalidateListener.onInvalidate() } } } ) } private var lastComplicationUpdate = Instant.EPOCH private class ComplicationDataHistoryEntry( val complicationData: ComplicationData, val time: Instant ) /** * There doesn't seem to be a convenient ring buffer in the standard library so implement our * own one. */ private class RingBuffer(val size: Int) : Iterable<ComplicationDataHistoryEntry> { private val entries = arrayOfNulls<ComplicationDataHistoryEntry>(size) private var readIndex = 0 private var writeIndex = 0 fun push(entry: ComplicationDataHistoryEntry) { writeIndex = (writeIndex + 1) % size if (writeIndex == readIndex) { readIndex = (readIndex + 1) % size } entries[writeIndex] = entry } override fun iterator() = object : Iterator<ComplicationDataHistoryEntry> { var iteratorReadIndex = readIndex override fun hasNext() = iteratorReadIndex != writeIndex override fun next(): ComplicationDataHistoryEntry { iteratorReadIndex = (iteratorReadIndex + 1) % size return entries[iteratorReadIndex]!! } } } /** * In userdebug builds maintain a history of the last [MAX_COMPLICATION_HISTORY_ENTRIES]-1 * complications, which is logged in dumpsys to help debug complication issues. */ private val complicationHistory = if (Build.TYPE.equals("userdebug")) { RingBuffer(MAX_COMPLICATION_HISTORY_ENTRIES) } else { null } init { require(id >= 0) { "id must be >= 0" } require(accessibilityTraversalIndex >= 0) { "accessibilityTraversalIndex must be >= 0" } } public companion object { /** The maximum number of entries in [complicationHistory] plus one. */ private const val MAX_COMPLICATION_HISTORY_ENTRIES = 50 internal val unitSquare = RectF(0f, 0f, 1f, 1f) internal val screenLockedFallback = NoDataComplicationData() /** * Constructs a [Builder] for a complication with bounds type * [ComplicationSlotBoundsType.ROUND_RECT]. This is the most common type of complication. These * can be tapped by the user to trigger the associated intent. * * @param id The watch face's ID for this complication. Can be any integer but should be * unique within the watch face. * @param canvasComplicationFactory The [CanvasComplicationFactory] to supply the * [CanvasComplication] to use for rendering. Note renderers should not be shared between * complicationSlots. * @param supportedTypes The types of complication supported by this ComplicationSlot. Used * during complication, this list should be non-empty. * @param defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] used to select * the initial complication data source when the watch is first installed. * @param bounds The complication's [ComplicationSlotBounds]. */ @JvmStatic public fun createRoundRectComplicationSlotBuilder( id: Int, canvasComplicationFactory: CanvasComplicationFactory, supportedTypes: List<ComplicationType>, defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy, bounds: ComplicationSlotBounds ): Builder = Builder( id, canvasComplicationFactory, supportedTypes, defaultDataSourcePolicy, ComplicationSlotBoundsType.ROUND_RECT, bounds, RoundRectComplicationTapFilter(), null ) /** * Constructs a [Builder] for a complication with bound type * [ComplicationSlotBoundsType.BACKGROUND] whose bounds cover the entire screen. A * background complication is for watch faces that wish to have a full screen user * selectable backdrop. This sort of complication isn't clickable and at most one may be * present in the list of complicationSlots. * * @param id The watch face's ID for this complication. Can be any integer but should be * unique within the watch face. * @param canvasComplicationFactory The [CanvasComplicationFactory] to supply the * [CanvasComplication] to use for rendering. Note renderers should not be shared between * complicationSlots. * @param supportedTypes The types of complication supported by this ComplicationSlot. Used * during complication, this list should be non-empty. * @param defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] used to select * the initial complication data source when the watch is first installed. */ @JvmStatic public fun createBackgroundComplicationSlotBuilder( id: Int, canvasComplicationFactory: CanvasComplicationFactory, supportedTypes: List<ComplicationType>, defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy ): Builder = Builder( id, canvasComplicationFactory, supportedTypes, defaultDataSourcePolicy, ComplicationSlotBoundsType.BACKGROUND, ComplicationSlotBounds(RectF(0f, 0f, 1f, 1f)), BackgroundComplicationTapFilter(), null ) /** * Constructs a [Builder] for a complication with bounds type * [ComplicationSlotBoundsType.EDGE]. * * An edge complication is drawn around the border of the display and has custom hit test * logic (see [complicationTapFilter]). When tapped the associated intent is * dispatched. Edge complicationSlots should have a custom [renderer] with * [CanvasComplication.drawHighlight] overridden. * * Note hit detection in an editor for [ComplicationSlot]s created with this method is not * supported. * * @param id The watch face's ID for this complication. Can be any integer but should be * unique within the watch face. * @param canvasComplicationFactory The [CanvasComplicationFactory] to supply the * [CanvasComplication] to use for rendering. Note renderers should not be shared between * complicationSlots. * @param supportedTypes The types of complication supported by this ComplicationSlot. Used * during complication, this list should be non-empty. * @param defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] used to select * the initial complication data source when the watch is first installed. * @param bounds The complication's [ComplicationSlotBounds]. Its likely the bounding rect * will be much larger than the complication and shouldn't directly be used for hit testing. * @param complicationTapFilter The [ComplicationTapFilter] used to determine whether or * not a tap hit the complication. */ // TODO(b/230364881): Deprecate when BoundingArc is no longer experimental. @JvmStatic public fun createEdgeComplicationSlotBuilder( id: Int, canvasComplicationFactory: CanvasComplicationFactory, supportedTypes: List<ComplicationType>, defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy, bounds: ComplicationSlotBounds, complicationTapFilter: ComplicationTapFilter ): Builder = Builder( id, canvasComplicationFactory, supportedTypes, defaultDataSourcePolicy, ComplicationSlotBoundsType.EDGE, bounds, complicationTapFilter, null ) /** * Constructs a [Builder] for a complication with bounds type * [ComplicationSlotBoundsType.EDGE], whose contents are contained within [boundingArc]. * * @param id The watch face's ID for this complication. Can be any integer but should be * unique within the watch face. * @param canvasComplicationFactory The [CanvasComplicationFactory] to supply the * [CanvasComplication] to use for rendering. Note renderers should not be shared between * complicationSlots. * @param supportedTypes The types of complication supported by this ComplicationSlot. Used * during complication, this list should be non-empty. * @param defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] used to select * the initial complication data source when the watch is first installed. * @param bounds The complication's [ComplicationSlotBounds]. Its likely the bounding rect * will be much larger than the complication and shouldn't directly be used for hit testing. */ @JvmStatic @JvmOverloads @ComplicationExperimental public fun createEdgeComplicationSlotBuilder( id: Int, canvasComplicationFactory: CanvasComplicationFactory, supportedTypes: List<ComplicationType>, defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy, bounds: ComplicationSlotBounds, boundingArc: BoundingArc, complicationTapFilter: ComplicationTapFilter = object : ComplicationTapFilter { override fun hitTest( complicationSlot: ComplicationSlot, screenBounds: Rect, x: Int, y: Int, @Suppress("UNUSED_PARAMETER") includeMargins: Boolean ) = boundingArc.hitTest( complicationSlot.computeBounds(screenBounds), x.toFloat(), y.toFloat() ) } ): Builder = Builder( id, canvasComplicationFactory, supportedTypes, defaultDataSourcePolicy, ComplicationSlotBoundsType.EDGE, bounds, complicationTapFilter, boundingArc ) } /** * Builder for constructing [ComplicationSlot]s. * * @param id The watch face's ID for this complication. Can be any integer but should be unique * within the watch face. * @param canvasComplicationFactory The [CanvasComplicationFactory] to supply the * [CanvasComplication] to use for rendering. Note renderers should not be shared between * complicationSlots. * @param supportedTypes The types of complication supported by this ComplicationSlot. Used * during complication, this list should be non-empty. * @param defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] used to select * the initial complication data source when the watch is first installed. * @param boundsType The [ComplicationSlotBoundsType] of the complication. * @param bounds The complication's [ComplicationSlotBounds]. * @param complicationTapFilter The [ComplicationTapFilter] used to perform hit testing for this * complication. */ @OptIn(ComplicationExperimental::class) public class Builder internal constructor( private val id: Int, private val canvasComplicationFactory: CanvasComplicationFactory, private val supportedTypes: List<ComplicationType>, private var defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy, @ComplicationSlotBoundsType private val boundsType: Int, private val bounds: ComplicationSlotBounds, private val complicationTapFilter: ComplicationTapFilter, private val boundingArc: BoundingArc? ) { private var accessibilityTraversalIndex = id private var defaultDataSourceType = ComplicationType.NOT_CONFIGURED private var initiallyEnabled = true private var configExtras: Bundle = Bundle.EMPTY private var fixedComplicationDataSource = false private var nameResourceId: Int? = null private var screenReaderNameResourceId: Int? = null init { require(id >= 0) { "id must be >= 0" } } /** * Sets the initial value used to sort Complications when generating accessibility content * description labels. By default this is [id]. */ public fun setAccessibilityTraversalIndex(accessibilityTraversalIndex: Int): Builder { this.accessibilityTraversalIndex = accessibilityTraversalIndex require(accessibilityTraversalIndex >= 0) { "accessibilityTraversalIndex must be >= 0" } return this } /** * Sets the initial [ComplicationType] to use with the initial complication data source. * Note care should be taken to ensure [defaultDataSourceType] is compatible with the * [DefaultComplicationDataSourcePolicy]. */ @Deprecated( "Instead set DefaultComplicationDataSourcePolicy" + ".systemDataSourceFallbackDefaultType." ) public fun setDefaultDataSourceType( defaultDataSourceType: ComplicationType ): Builder { defaultDataSourcePolicy = when { defaultDataSourcePolicy.secondaryDataSource != null -> DefaultComplicationDataSourcePolicy( defaultDataSourcePolicy.primaryDataSource!!, defaultDataSourcePolicy.primaryDataSourceDefaultType ?: defaultDataSourceType, defaultDataSourcePolicy.secondaryDataSource!!, defaultDataSourcePolicy.secondaryDataSourceDefaultType ?: defaultDataSourceType, defaultDataSourcePolicy.systemDataSourceFallback, defaultDataSourceType ) defaultDataSourcePolicy.primaryDataSource != null -> DefaultComplicationDataSourcePolicy( defaultDataSourcePolicy.primaryDataSource!!, defaultDataSourcePolicy.primaryDataSourceDefaultType ?: defaultDataSourceType, defaultDataSourcePolicy.systemDataSourceFallback, defaultDataSourceType ) else -> DefaultComplicationDataSourcePolicy( defaultDataSourcePolicy.systemDataSourceFallback, defaultDataSourceType ) } this.defaultDataSourceType = defaultDataSourceType return this } /** * Whether the complication is initially enabled or not (by default its enabled). This can * be overridden by [ComplicationSlotsUserStyleSetting]. */ public fun setEnabled(enabled: Boolean): Builder { this.initiallyEnabled = enabled return this } /** * Sets optional extras to be merged into the Intent sent when invoking the complication * data source chooser activity. */ public fun setConfigExtras(extras: Bundle): Builder { this.configExtras = extras return this } /** * Whether or not the complication source is fixed (i.e. the user can't change it). */ @Suppress("MissingGetterMatchingBuilder") public fun setFixedComplicationDataSource(fixedComplicationDataSource: Boolean): Builder { this.fixedComplicationDataSource = fixedComplicationDataSource return this } /** * If non-null sets the ID of a string resource containing the name of this complication * slot, for use visually in an editor. This resource should be short and should not contain * the word "Complication". E.g. "Left" for the left complication. */ public fun setNameResourceId( @Suppress("AutoBoxing") nameResourceId: Int? ): Builder { this.nameResourceId = nameResourceId return this } /** * If non-null sets the ID of a string resource containing the name of this complication * slot, for use by a screen reader. This resource should be a short sentence. E.g. * "Left complication" for the left complication. */ public fun setScreenReaderNameResourceId( @Suppress("AutoBoxing") screenReaderNameResourceId: Int? ): Builder { this.screenReaderNameResourceId = screenReaderNameResourceId return this } /** Constructs the [ComplicationSlot]. */ public fun build(): ComplicationSlot = ComplicationSlot( id, accessibilityTraversalIndex, boundsType, bounds, canvasComplicationFactory, supportedTypes, defaultDataSourcePolicy, defaultDataSourceType, initiallyEnabled, configExtras, fixedComplicationDataSource, complicationTapFilter, nameResourceId, screenReaderNameResourceId, boundingArc ) } internal interface InvalidateListener { /** Requests redraw. Can be called on any thread */ fun onInvalidate() } private lateinit var invalidateListener: InvalidateListener internal var complicationBoundsDirty = true /** * The complication's [ComplicationSlotBounds] which are converted to pixels during rendering. * * Note it's not allowed to change the bounds of a background complication because * they are assumed to always cover the entire screen. */ public var complicationSlotBounds: ComplicationSlotBounds = bounds @UiThread get @UiThread internal set(value) { require(boundsType != ComplicationSlotBoundsType.BACKGROUND) if (field == value) { return } field = value complicationBoundsDirty = true } internal var enabledDirty = true /** Whether or not the complication should be drawn and accept taps. */ public var enabled: Boolean = initiallyEnabled @JvmName("isEnabled") @UiThread get @UiThread internal set(value) { if (field == value) { return } field = value enabledDirty = true } internal var defaultDataSourcePolicyDirty = true /** * The [DefaultComplicationDataSourcePolicy] which defines the default complicationSlots * providers selected when the user hasn't yet made a choice. See also [defaultDataSourceType]. */ public var defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy = defaultPolicy @UiThread get @UiThread internal set(value) { if (field == value) { return } field = value defaultDataSourcePolicyDirty = true } internal var defaultDataSourceTypeDirty = true /** * The default [ComplicationType] to use alongside [defaultDataSourcePolicy]. */ @Deprecated("Use DefaultComplicationDataSourcePolicy." + "systemDataSourceFallbackDefaultType instead") public var defaultDataSourceType: ComplicationType = defaultDataSourceType @UiThread get @UiThread internal set(value) { if (field == value) { return } field = value defaultDataSourceTypeDirty = true } internal var accessibilityTraversalIndexDirty = true /** * This is used to determine the order in which accessibility labels for the watch face are * read to the user. Accessibility labels are automatically generated for the time and * complicationSlots. See also [Renderer.additionalContentDescriptionLabels]. */ public var accessibilityTraversalIndex: Int = accessibilityTraversalIndex @UiThread get @UiThread internal set(value) { require(value >= 0) { "accessibilityTraversalIndex must be >= 0" } if (field == value) { return } field = value accessibilityTraversalIndexDirty = true } internal var nameResourceIdDirty = true /** * The optional ID of string resource (or `null` if absent) to identify the complication slot on * screen in an editor. These strings should be short (perhaps 10 characters max) E.g. * complication slots named 'left' and 'right' might be shown by the editor in a list from which * the user selects a complication slot for editing. */ public var nameResourceId: Int? = nameResourceId @Suppress("AutoBoxing") @UiThread get @UiThread internal set(value) { require(value != 0) if (field == value) { return } field = value nameResourceIdDirty = true } internal var screenReaderNameResourceIdDirty = true /** * The optional ID of a string resource (or `null` if absent) for use by a * watch face editor to identify the complication slot in a screen reader. While similar to * [nameResourceId] this string can be longer and should be more descriptive. E.g. saying * 'left complication' rather than just 'left'. */ public var screenReaderNameResourceId: Int? = screenReaderNameResourceId @Suppress("AutoBoxing") @UiThread get @UiThread internal set(value) { if (field == value) { return } field = value screenReaderNameResourceIdDirty = true } internal var dataDirty = true /** * The [androidx.wear.watchface.complications.data.ComplicationData] associated with the * [ComplicationSlot]. This defaults to [NoDataComplicationData]. */ public val complicationData: StateFlow<ComplicationData> = MutableStateFlow(NoDataComplicationData()) /** * The complication data sent by the system. This may contain a timeline out of which * [complicationData] is selected. */ private var timelineComplicationData: ComplicationData = NoDataComplicationData() private var timelineEntries: List<WireComplicationData>? = null /** * Sets the current [ComplicationData] and if it's a timeline, the correct override for * [instant] is chosen. */ internal fun setComplicationData( complicationData: ComplicationData, loadDrawablesAsynchronous: Boolean, instant: Instant ) { lastComplicationUpdate = instant complicationHistory?.push(ComplicationDataHistoryEntry(complicationData, instant)) timelineComplicationData = complicationData timelineEntries = complicationData.asWireComplicationData().timelineEntries?.map { it } selectComplicationDataForInstant(instant, loadDrawablesAsynchronous, true) } /** * If the current [ComplicationData] is a timeline, the correct override for [instant] is * chosen. */ internal fun selectComplicationDataForInstant( instant: Instant, loadDrawablesAsynchronous: Boolean, forceUpdate: Boolean ) { var previousShortest = Long.MAX_VALUE val time = instant.epochSecond var best = timelineComplicationData // Select the shortest valid timeline entry. timelineEntries?.let { for (wireEntry in it) { val start = wireEntry.timelineStartEpochSecond val end = wireEntry.timelineEndEpochSecond if (start != null && end != null && time >= start && time < end) { val duration = end - start if (duration < previousShortest) { previousShortest = duration best = wireEntry.toApiComplicationData() } } } } // If the screen is locked and our policy is to not display it when locked then select // screenLockedFallback instead. if ((best.displayPolicy and ComplicationDisplayPolicies.DO_NOT_SHOW_WHEN_DEVICE_LOCKED) != 0 && complicationSlotsManager.watchState.isLocked.value ) { best = screenLockedFallback // This is NoDataComplicationData. } if (forceUpdate || complicationData.value != best) { renderer.loadData(best, loadDrawablesAsynchronous) (complicationData as MutableStateFlow).value = best } } /** * Whether or not the complication should be considered active and should be rendered at the * specified time. */ public fun isActiveAt(instant: Instant): Boolean { return when (complicationData.value.type) { ComplicationType.NO_DATA -> false ComplicationType.NO_PERMISSION -> false ComplicationType.EMPTY -> false else -> complicationData.value.validTimeRange.contains(instant) } } /** * Watch faces should use this method to render a complication. Note the system may call this. * * @param canvas The [Canvas] to render into * @param zonedDateTime The [ZonedDateTime] to render with * @param renderParameters The current [RenderParameters] */ @UiThread public fun render( canvas: Canvas, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters ) { val bounds = computeBounds(Rect(0, 0, canvas.width, canvas.height)) renderer.render(canvas, bounds, zonedDateTime, renderParameters, id) } /** * Watch faces should use this method to render non-fixed complicationSlots for any highlight * layer pass. Note the system may call this. * * @param canvas The [Canvas] to render into * @param zonedDateTime The [ZonedDateTime] to render with * @param renderParameters The current [RenderParameters] */ @UiThread @OptIn(ComplicationExperimental::class) public fun renderHighlightLayer( canvas: Canvas, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters ) { // It's only sensible to render a highlight for non-fixed ComplicationSlots because you // can't edit fixed complicationSlots. if (fixedComplicationDataSource) { return } val bounds = computeBounds(Rect(0, 0, canvas.width, canvas.height)) when (val highlightedElement = renderParameters.highlightLayer?.highlightedElement) { is HighlightedElement.AllComplicationSlots -> { renderer.drawHighlight( canvas, bounds, boundsType, zonedDateTime, renderParameters.highlightLayer.highlightTint, boundingArc ) } is HighlightedElement.ComplicationSlot -> { if (highlightedElement.id == id) { renderer.drawHighlight( canvas, bounds, boundsType, zonedDateTime, renderParameters.highlightLayer.highlightTint, boundingArc ) } } is HighlightedElement.UserStyle -> { // Nothing } null -> { // Nothing } } } internal fun init(invalidateListener: InvalidateListener, isHeadless: Boolean) { this.invalidateListener = invalidateListener if (isHeadless) { timelineComplicationData = EmptyComplicationData() (complicationData as MutableStateFlow).value = EmptyComplicationData() } } /** * Computes the bounds of the complication by converting the unitSquareBounds of the specified * [complicationType] to pixels based on the [screen]'s dimensions. * * @param screen A [Rect] describing the dimensions of the screen. * @param complicationType The [ComplicationType] to use when looking up the slot's * [ComplicationSlotBounds.perComplicationTypeBounds]. * @param applyMargins Whether or not the margins should be applied to the computed [Rect]. * @hide */ @JvmOverloads @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun computeBounds( screen: Rect, complicationType: ComplicationType, applyMargins: Boolean = false ): Rect { val unitSquareBounds = RectF(complicationSlotBounds.perComplicationTypeBounds[complicationType]!!) if (applyMargins) { val unitSquareMargins = complicationSlotBounds.perComplicationTypeMargins[complicationType]!! // Apply the margins unitSquareBounds.set( unitSquareBounds.left - unitSquareMargins.left, unitSquareBounds.top - unitSquareMargins.top, unitSquareBounds.right + unitSquareMargins.right, unitSquareBounds.bottom + unitSquareMargins.bottom ) } unitSquareBounds.intersect(unitSquare) // We add 0.5 to make toInt() round to the nearest whole number rather than truncating. return Rect( (0.5f + unitSquareBounds.left * screen.width()).toInt(), (0.5f + unitSquareBounds.top * screen.height()).toInt(), (0.5f + unitSquareBounds.right * screen.width()).toInt(), (0.5f + unitSquareBounds.bottom * screen.height()).toInt() ) } /** * Computes the bounds of the complication by converting the unitSquareBounds of the current * complication type to pixels based on the [screen]'s dimensions. * * @param screen A [Rect] describing the dimensions of the screen. * @param applyMargins Whether or not the margins should be applied to the computed [Rect]. */ @JvmOverloads public fun computeBounds( screen: Rect, applyMargins: Boolean = false ): Rect = computeBounds(screen, complicationData.value.type, applyMargins) @UiThread internal fun dump(writer: IndentingPrintWriter) { writer.println("ComplicationSlot $id:") writer.increaseIndent() writer.println("fixedComplicationDataSource=$fixedComplicationDataSource") writer.println("enabled=$enabled") writer.println("boundsType=$boundsType") writer.println("configExtras=$configExtras") writer.println("supportedTypes=${supportedTypes.joinToString { it.toString() }}") writer.println("initiallyEnabled=$initiallyEnabled") writer.println( "defaultDataSourcePolicy.primaryDataSource=${defaultDataSourcePolicy.primaryDataSource}" ) writer.println("defaultDataSourcePolicy.primaryDataSourceDefaultDataSourceType=" + defaultDataSourcePolicy.primaryDataSourceDefaultType) writer.println( "defaultDataSourcePolicy.secondaryDataSource=" + defaultDataSourcePolicy.secondaryDataSource ) writer.println("defaultDataSourcePolicy.secondaryDataSourceDefaultDataSourceType=" + defaultDataSourcePolicy.secondaryDataSourceDefaultType) writer.println( "defaultDataSourcePolicy.systemDataSourceFallback=" + defaultDataSourcePolicy.systemDataSourceFallback ) writer.println("defaultDataSourcePolicy.systemDataSourceFallbackDefaultType=" + defaultDataSourcePolicy.systemDataSourceFallbackDefaultType) writer.println("timelineComplicationData=$timelineComplicationData") writer.println("timelineEntries=" + timelineEntries?.joinToString()) writer.println("data=${renderer.getData()}") @OptIn(ComplicationExperimental::class) writer.println("boundingArc=$boundingArc") writer.println("complicationSlotBounds=$complicationSlotBounds") writer.println("lastComplicationUpdate=$lastComplicationUpdate") writer.println("data history") complicationHistory?.let { writer.increaseIndent() for (entry in it) { val localDateTime = LocalDateTime.ofInstant(entry.time, ZoneId.systemDefault()) writer.println("${entry.complicationData} @ $localDateTime") } writer.decreaseIndent() } writer.decreaseIndent() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ComplicationSlot if (id != other.id) return false if (accessibilityTraversalIndex != other.accessibilityTraversalIndex) return false if (boundsType != other.boundsType) return false if (complicationSlotBounds != other.complicationSlotBounds) return false if (supportedTypes.size != other.supportedTypes.size || !supportedTypes.containsAll(other.supportedTypes)) return false if (defaultDataSourcePolicy != other.defaultDataSourcePolicy) return false if (initiallyEnabled != other.initiallyEnabled) return false if (fixedComplicationDataSource != other.fixedComplicationDataSource) return false if (nameResourceId != other.nameResourceId) return false if (screenReaderNameResourceId != other.screenReaderNameResourceId) return false @OptIn(ComplicationExperimental::class) if (boundingArc != other.boundingArc) return false return true } override fun hashCode(): Int { @OptIn(ComplicationExperimental::class) return Objects.hash(id, accessibilityTraversalIndex, boundsType, complicationSlotBounds, supportedTypes.sorted(), defaultDataSourcePolicy, initiallyEnabled, fixedComplicationDataSource, nameResourceId, screenReaderNameResourceId, boundingArc) } }
apache-2.0
a23c3d0687b555ca58ad36e93cf1a953
40.880915
111
0.666171
5.427184
false
false
false
false
Yusspy/Jolt-Sphere
core/src/org/joltsphere/mechanics/StreamBeamContactListener.kt
1
1478
package org.joltsphere.mechanics import com.badlogic.gdx.physics.box2d.Contact import com.badlogic.gdx.physics.box2d.ContactImpulse import com.badlogic.gdx.physics.box2d.ContactListener import com.badlogic.gdx.physics.box2d.Fixture import com.badlogic.gdx.physics.box2d.Manifold class StreamBeamContactListener : ContactListener { private var fa: Fixture? = null private var fb: Fixture? = null var streamBeamGroundContacts = 0 var mountainClimberGroundContacts = 0 override fun beginContact(contact: Contact) { fa = contact.fixtureA fb = contact.fixtureB if (isContacting("mountainClimber", "ground")) mountainClimberGroundContacts++ if (isContacting("streamBeam", "ground")) streamBeamGroundContacts++ } override fun endContact(contact: Contact) { fa = contact.fixtureA fb = contact.fixtureB if (isContacting("mountainClimber", "ground")) mountainClimberGroundContacts-- if (isContacting("streamBeam", "ground")) streamBeamGroundContacts-- } override fun preSolve(contact: Contact, oldManifold: Manifold) {} override fun postSolve(contact: Contact, impulse: ContactImpulse) {} private fun isContacting(f1: String, f2: String): Boolean { if (fa!!.userData === f1 && fb!!.userData === f2) return true else if (fa!!.userData === f2 && fb!!.userData === f1) return true else return false } }
agpl-3.0
7114709718316be2d1455275331fa06b
28.56
86
0.684032
3.973118
false
false
false
false
klazuka/intellij-elm
src/test/kotlin/org/elm/ide/inspections/inference/TypeInferenceInspectionTest2.kt
1
19259
package org.elm.ide.inspections.inference import org.elm.ide.inspections.ElmInspectionsTestBase import org.elm.ide.inspections.ElmTypeInferenceInspection class TypeInferenceInspectionTest2 : ElmInspectionsTestBase(ElmTypeInferenceInspection()) { override fun getProjectDescriptor() = ElmWithStdlibDescriptor fun `test mismatched record subset pattern in parameter`() = checkByText(""" type alias Foo = { foo : (), bar : Int } main : Foo -> () main {bar} = <error descr="Type mismatch.Required: ()Found: Int">bar</error> """) // https://github.com/klazuka/intellij-elm/issues/122 fun `test matched record pattern from extension alias`() = checkByText(""" type alias Foo a = { a | foo : ()} type alias Bar = { bar : () } main : Foo Bar -> () main {bar} = bar """) fun `test mismatched record pattern from extension alias`() = checkByText(""" type alias Foo a = { a | foo : ()} type alias Bar = { bar : () } main : Foo Bar -> Int main {bar} = <error descr="Type mismatch.Required: IntFound: ()">bar</error> """) fun `test mismatched record pattern from extension alias redefining a field`() = checkByText(""" type alias Foo a = { a | foo : ()} type alias Bar = Foo { foo : Int } main : Bar -> Int main {foo} = <error descr="Type mismatch.Required: IntFound: ()">foo</error> """) fun `test extension record parameter`() = checkByText(""" type alias Extension base = { base | field : () } foo : Extension base -> () foo e = () main = foo { field = (), field2 = () } """) fun `test record pattern parameter for record type literal`() = checkByText(""" main : { field : () } -> Int main { field } = <error descr="Type mismatch.Required: IntFound: ()">field</error> """) fun `test let-in with mismatched type in annotated inner func`() = checkByText(""" main : () main = let foo : () foo = <error descr="Type mismatch.Required: ()Found: String">""</error> in foo """) // https://github.com/klazuka/intellij-elm/issues/153 fun `test let-in with tuple with too small arity`() = checkByText(""" main : () main = let <error descr="Invalid pattern.Required type: ((), ())Pattern type: (a, b, c)">(x, y, z)</error> = ((), ()) in y """) fun `test let-in with tuple with too large arity`() = checkByText(""" main : () main = let <error descr="Invalid pattern.Required type: ((), (), ())Pattern type: (a, b)">(x, y)</error> = ((), (), ()) in y """) fun `test let-in with mismatched type from annotated inner func`() = checkByText(""" type Foo = Bar main : Foo main = let foo : () foo = () in <error descr="Type mismatch.Required: FooFound: ()">foo</error> """) fun `test let-in function without annotation and one parameter`() = checkByText(""" main : () main = let foo a = () in foo 1 """) fun `test let-in function without annotation and two parameters`() = checkByText(""" main : () main = let foo a b = () in foo 1 2 """) fun `test mismatched return value from let-in record binding`() = checkByText(""" main : () main = let {x, y} = {x = 1, y = ""} in <error descr="Type mismatch.Required: ()Found: String">y</error> """) fun `test mismatched return value from let-in tuple binding`() = checkByText(""" main : () main = let (x, y) = (1, "") in <error descr="Type mismatch.Required: ()Found: String">y</error> """) fun `test matched record argument to let-in function`() = checkByText(""" main : () main = let foo {x, y} = x in foo {x=(), y=()} """) fun `test cyclic definition in let-in record binding`() = checkByText(""" main : () main = let {x, y} = {x = 1, y = <error descr="Value cannot be defined in terms of itself">y</error>} in y """) fun `test invalid let-in record binding`() = checkByText(""" main : () main = let <error descr="Invalid pattern.Required type: ()Pattern type: { x : a, y : b }">{x, y}</error> = () in y """) fun `test invalid let-in tuple binding`() = checkByText(""" main : () main = let <error descr="Invalid pattern.Required type: ()Pattern type: (a, b)">(x, y)</error> = () in y """) fun `test mismatch in chained let-in tuple binding`() = checkByText(""" main : () main = let (x, y) = ((), "") (z, w) = (x, y) in <error descr="Type mismatch.Required: ()Found: String">w</error> """) fun `test returning function`() = checkByText(""" main : () -> () main = let foo a = a in foo """) fun `test returning partially applied function`() = checkByText(""" main : () -> () main = let foo a b = b in foo () """) fun `test matched function type alias in annotation`() = checkByText(""" type Foo = Bar type alias F = Foo -> () foo : F -> F foo a b = a b """) fun `test mismatched function type alias in annotation`() = checkByText(""" type Foo = Bar type alias F = Foo -> () foo : F -> F foo a b = <error descr="Type mismatch.Required: ()Found: Foo">b</error> """) fun `test partial pattern in function parameter from cons`() = checkByText(""" main (<error descr="Pattern does not cover all possibilities">x :: []</error>) = () """) fun `test partial pattern in function parameter from list`() = checkByText(""" main (<error descr="Pattern does not cover all possibilities">[x]</error>) = () """) fun `test partial pattern in function parameter from constant`() = checkByText(""" main (<error descr="Pattern does not cover all possibilities">""</error>) = () """) fun `test partial pattern in lambda parameter from constant`() = checkByText(""" main = (\<error descr="Pattern does not cover all possibilities">""</error> -> "") """) fun `test bad self-recursion in annotated value`() = checkByText(""" main : () <error descr="Infinite recursion">main = main</error> """) fun `test bad self-recursion in unannotated value`() = checkByText(""" <error descr="Infinite recursion">main = main</error> """) // #https://github.com/klazuka/intellij-elm/issues/142 // this tests for infinite recursion; the diagnostic is tested in TypeDeclarationInspectionTest fun `test bad self-recursion in type alias`() = checkByText(""" type alias A = A foo : A foo = () """) fun `test allowed self-recursion in annotated function`() = checkByText(""" main : () -> () main a = main a -- This is a runtime error, not compile time """) fun `test allowed self-recursion in unannotated function`() = checkByText(""" main a = main a -- This is a runtime error, not compile time """) fun `test allowed self-recursion in lambda`() = checkByText(""" main : () main = (\_ -> main) 1 """) fun `test allowed self-recursion in lambda in unannotated function`() = checkByText(""" main = (\_ -> main) 1 """) fun `test bad mutual recursion`() = checkByText(""" <error descr="Infinite recursion">foo = bar</error> bar = foo """) fun `test bad mutual recursion in let`() = checkByText(""" main = let <error descr="Infinite recursion">foo = bar</error> bar = foo in () """) fun `test mapping over recursive container in annotated function`() = checkByText(""" type Box a = Box a type Tree a = Node (List (Tree a)) main : Tree (Box a) -> Box (Tree a) main (Node trees) = <error descr="Type mismatch.Required: Box (Tree a)Found: List (Box (Tree a))">List.map main trees</error> """) fun `test uncurrying function passed as argument`() = checkByText(""" foo : a -> a foo a = a main : () main = <error descr="Type mismatch.Required: ()Found: String">foo foo foo ""</error> """) fun `test uncurrying return value from unannotated function`() = checkByText(""" lazy3 : (a -> b -> c -> ()) -> a -> b -> c -> () lazy3 a = a apply1 fn a = embed (fn a) embed : () -> () -> () embed a b = a main : (a -> ()) -> a -> a -> () main fn a = <error descr="Type mismatch.Required: a → ()Found: () → ()">lazy3 apply1 fn a</error> """) fun `test function argument mismatch in case expression`() = checkByText(""" foo : () -> () foo a = a main = case foo <error descr="Type mismatch.Required: ()Found: String">""</error> of _ -> () """) fun `test function argument mismatch in case branch`() = checkByText(""" foo : () -> () foo a = a main = case () of _ -> foo <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test value mismatch from case`() = checkByText(""" main : () main = case () of _ -> <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test case branches with mismatched types`() = checkByText(""" main : () main = case () of "" -> () "x" -> <error descr="Type mismatch.Required: ()Found: String">""</error> _ -> () """) fun `test case branches with multiple mismatched types`() = checkByText(""" main : () main = case () of "" -> <error descr="Type mismatch.Required: ()Found: String">""</error> "x" -> <error descr="Type mismatch.Required: ()Found: String">""</error> _ -> () """) fun `test case branches with mismatched types from pattern`() = checkByText(""" main = case Just 42 of Nothing -> "" Just x -> <error descr="Type mismatch.Required: StringFound: number">x</error> """) fun `test case branches with mismatched types in lambda`() = checkByText(""" main = \_ -> case "" of "" -> () _ -> <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test case branches with mismatched types in let`() = checkByText(""" main = let f = () in case "" of "" -> () _ -> <error descr="Type mismatch.Required: ()Found: String">""</error> """) // https://github.com/klazuka/intellij-elm/issues/113 fun `test case branches with union value call`() = checkByText(""" foo : Maybe (List a) foo = Nothing main = case foo of Just [] -> () _ -> () """) // https://github.com/klazuka/intellij-elm/issues/113 fun `test field access on field subset`() = checkByText(""" type alias Subset a = { a | extra : () } type alias Foo = { bar : () } main : Subset Foo -> () main a = a.bar """) fun `test case branches with mismatched tuple type`() = checkByText(""" type Foo = Bar type Baz = Qux(Foo, Foo) main : Baz -> () main x = case x of Qux (y, z) -> <error descr="Type mismatch.Required: ()Found: Foo">z</error> """) fun `test case branches with mismatched union pattern`() = checkByText(""" type Foo = Bar type Baz = Qux main : Foo -> () main arg = case arg of <error descr="Type mismatch.Required: BazFound: Foo">Qux</error> -> () """) fun `test case branches with mismatched record pattern`() = checkByText(""" type alias Foo = { a : (), b : ()} main : Foo -> () main arg = case arg of <error descr="Invalid pattern.Required type: FooPattern type: { b : a, c : b }Extra fields: { c : b }">{ b, c }</error> -> () """) fun `test case branches using union patterns with constructor argument`() = checkByText(""" type Foo = Bar () | Baz () | Qux (Maybe ()) () main : Foo -> () main arg = case arg of Bar x -> () Baz x -> x Qux Nothing x -> x """) fun `test case branches using union patterns with tuple destructuring of var`() = checkByText(""" type Foo = Bar (Maybe ((), ())) | Baz () main : Foo -> () main arg = case arg of Bar (Just (x, y)) -> y Baz x -> x _ -> () """) fun `test case branches using union patterns with record destructuring of var`() = checkByText(""" type Foo = Bar (Maybe {x: ()}) | Baz () main : Foo -> () main arg = case arg of Bar (Just {x}) -> x Baz x -> x _ -> () """) fun `test case branches using union patterns to unresolved type`() = checkByText(""" -- This will lead to unresolved reference errors, but we need to test that we're still -- binding the parameters so that we can infer the branch expressions. main arg = case arg of Bar (Just {x}) -> x Baz x -> x _ -> () """) fun `test case branches using union patterns to mismatched type`() = checkByText(""" type Foo a = Bar (Maybe a) | Baz a type Qux = Qux main : Qux -> () main arg = case arg of <error descr="Type mismatch.Required: Foo aFound: Qux">Bar (Just {x})</error> -> x <error descr="Type mismatch.Required: Foo aFound: Qux">Baz x</error> -> x Qux -> () _ -> () """) fun `test case branches with union pattern referencing invalid arg`() = checkByText(""" type Foo = Bar main : Foo -> () main arg = case arg of <error descr="The type expects 0 arguments, but it got 1 instead.">Bar foo</error> -> foo """) fun `test mismatched case branch union pattern`() = checkByText(""" main = case Just 42 of Just x -> "" ++ <error descr="Type mismatch.Required: StringFound: number">x</error> Nothing -> "" """) fun `test case branch with cons pattern head`() = checkByText(""" main = case [()] of x :: xs -> x _ -> <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test case branch with cons pattern tail`() = checkByText(""" main : List () main = case [""] of x :: xs -> <error descr="Type mismatch.Required: List ()Found: List String">xs</error> _ -> [] """) fun `test case branch with list pattern`() = checkByText(""" main = case [()] of [x, y] -> y _ -> <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test case branch with cons and list pattern`() = checkByText(""" main = case [()] of z :: [x, y] -> y _ -> <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test case branches binding the same names`() = checkByText(""" type Foo a = Foo () | Bar String | Baz () | Qux () | Quz () bar : () -> () bar a = a foo : Foo a -> () foo f = case f of Foo x -> bar x Bar x -> bar <error descr="Type mismatch.Required: ()Found: String">x</error> Baz x -> bar x Qux x -> bar x Quz x -> bar x """) fun `test case branches with record pattern on different field than previously accessed through pipeline`() = checkByText(""" foo : (a -> ()) -> a -> a foo _ a = a main : String main = case { f1 = (), f2 = () } |> foo .f2 of { f1 } -> <error descr="Type mismatch.Required: StringFound: ()">f1</error> """) fun `test case branch with record pattern from previous mutable record`() = checkByText(""" foo r = let f = r.f1 in case r of { f2 } -> r main : () main = <error descr="Type mismatch.Required: ()Found: { f1 : (), f2 : String }">foo { f1 = (), f2 = "" }</error> """) fun `test invalid return value from cons pattern`() = checkByText(""" main : () main = case [""] of x :: xs -> <error descr="Type mismatch.Required: ()Found: String">x</error> """) // https://github.com/klazuka/intellij-elm/issues/247 fun `test nested destructuring`() = checkByText(""" main : () main = let (a, b) = let (c, d) = ("", "") in (c, d) in <error descr="Type mismatch.Required: ()Found: String">a</error> """) fun `test forward reference to destructured pattern`() = checkByText(""" main : () main = let a = b (b, c) = ("", "") in <error descr="Type mismatch.Required: ()Found: String">a</error> """) fun `test nested forward references`() = checkByText(""" main : () -> () main m = let x a = y a y a = z r m z a b = a (q, r) = (m, ()) in x () """) fun `test referenced pattern as`() = checkByText(""" main : { field : String } -> () main r = let ({field} as record) = r in <error descr="Type mismatch.Required: ()Found: String">record.field</error> """) fun `test nested param as`() = checkByText(""" main : (String, String) -> () main ( (x) as foo, _ ) = <error descr="Type mismatch.Required: ()Found: String">foo</error> """) fun `test mismatched left operand to non-associative operator`() = checkByText(""" foo : () -> () -> () foo a b = a infix non 4 (~~) = foo main a = <error descr="Type mismatch.Required: ()Found: String">""</error> ~~ () """) fun `test mismatched right operand to non-associative operator`() = checkByText(""" foo : () -> () -> () foo a b = a infix non 4 (~~) = foo main a = () ~~ <error descr="Type mismatch.Required: ()Found: String">""</error> """) fun `test chained non-associative operator`() = checkByText(""" foo : () -> () -> () foo a b = a infix non 4 (~~) = foo main a = <error descr="Operator (~~) is not associative, and so cannot be chained">() ~~ () ~~ ()</error> """) fun `test matched left associative chain`() = checkByText(""" type Foo = Bar foo : Foo -> () -> Foo foo a b = a infix left 4 (~~) = foo main : Foo main = Bar ~~ () ~~ () """) fun `test matched right associative chain`() = checkByText(""" type Foo = Bar foo : () -> Foo -> Foo foo a b = b infix right 4 (~~) = foo main : Foo main = () ~~ () ~~ Bar """) fun `test mismatched left associative chain`() = checkByText(""" type Foo = Bar foo : () -> () -> Foo foo a b = Bar infix left 4 (~~) = foo main a = <error descr="Type mismatch.Required: ()Found: Foo">() ~~ ()</error> ~~ () """) fun `test mismatched right associative chain`() = checkByText(""" type Foo = Bar foo : () -> () -> Foo foo a b = Bar infix right 4 (~~) = foo main a = () ~~ <error descr="Type mismatch.Required: ()Found: Foo">() ~~ ()</error> """) fun `test apply-right into Maybe`() = checkByText(""" apR : a -> (a -> b) -> b apR x f = f x infix left 0 (|>) = apR main : Maybe () main = () |> Just """) fun `test multiple non-associative operators`() = checkByText(""" lt : a -> a -> Bool lt a b = True and : Bool -> Bool -> Bool and a b = False infix right 3 (&&) = and infix non 4 (<) = lt main : Bool main = 1 < 2 && 3 < 4 """) fun `test operator mixed with function call`() = checkByText(""" type Foo = Bar foo : Foo -> () -> Foo foo a b = a infix left 4 (~~) = foo main = foo Bar () ~~ () """) fun `test self reference in union variant`() = checkByText(""" type Foo a = FooVariant Foo a type Bar = BarVariant Bar (Foo Bar) main : Foo () main = <error descr="Type mismatch.Required: Foo ()Found: Bar → Foo Bar → Bar">BarVariant</error> """) // https://github.com/klazuka/intellij-elm/issues/201 fun `test returning bound recursive union variant`() = checkByText(""" type Tree a = Tree a (List (Tree a)) directChildren : Tree a -> () directChildren tree = case tree of Tree _ children -> <error descr="Type mismatch.Required: ()Found: List (Tree a)">children</error> """) }
mit
5d39675c137f4a32f5676ddde47071fb
24.397098
134
0.5701
3.701404
false
true
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_texture_compression.kt
1
9437
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_texture_compression = "ARBTextureCompression".nativeClassGL("ARB_texture_compression", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. Compressing texture images can reduce texture memory utilization and improve performance when rendering textured primitives. This extension allows OpenGL applications to use compressed texture images by providing: ${ol( "A framework upon which extensions providing specific compressed image formats can be built.", """ A set of generic compressed internal formats that allow applications to specify that texture images should be stored in compressed form without needing to code for specific compression formats. """ )} An application can define compressed texture images by providing a texture image stored in a specific compressed image format. This extension does not define any specific compressed image formats, but it does provide the mechanisms necessary to enable other extensions that do. An application can also define compressed texture images by providing an uncompressed texture image but specifying a compressed internal format. In this case, the GL will automatically compress the texture image using the appropriate image format. Compressed internal formats can either be specific (as above) or generic. Generic compressed internal formats are not actual image formats, but are instead mapped into one of the specific compressed formats provided by the GL (or to an uncompressed base internal format if no appropriate compressed format is available). Generic compressed internal formats allow applications to use texture compression without needing to code to any particular compression algorithm. Generic compressed formats allow the use of texture compression across a wide range of platforms with differing compression algorithms and also allow future GL implementations to substitute improved compression methods transparently. ${GL13.promoted} """ IntConstant( "Accepted by the {@code internalformat} parameter of TexImage1D, TexImage2D, TexImage3D, CopyTexImage1D, and CopyTexImage2D.", "COMPRESSED_ALPHA_ARB"..0x84E9, "COMPRESSED_LUMINANCE_ARB"..0x84EA, "COMPRESSED_LUMINANCE_ALPHA_ARB"..0x84EB, "COMPRESSED_INTENSITY_ARB"..0x84EC, "COMPRESSED_RGB_ARB"..0x84ED, "COMPRESSED_RGBA_ARB"..0x84EE ) IntConstant( "Accepted by the {@code target} parameter of Hint and the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.", "TEXTURE_COMPRESSION_HINT_ARB"..0x84EF ) IntConstant( "Accepted by the {@code value} parameter of GetTexLevelParameter.", "TEXTURE_COMPRESSED_IMAGE_SIZE_ARB"..0x86A0, "TEXTURE_COMPRESSED_ARB"..0x86A1 ) IntConstant( "Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.", "NUM_COMPRESSED_TEXTURE_FORMATS_ARB"..0x86A2, "COMPRESSED_TEXTURE_FORMATS_ARB"..0x86A3 ) // KHR_texture_compression_astc_ldr formats are only accepted in CompressedTexImage* functions val CompressTexImageFormats = "$SPECIFIC_COMPRESSED_TEXTURE_INTERNAL_FORMATS @##KHRTextureCompressionASTCLDR" void( "CompressedTexImage3DARB", "Specifies a three-dimensional texture image in a compressed format.", GLenum.IN("target", "the target texture", "$TEXTURE_3D_TARGETS $PROXY_TEXTURE_3D_TARGETS"), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), GLenum.IN("internalformat", "the format of the compressed image data", CompressTexImageFormats), GLsizei.IN("width", "the width of the texture image"), GLsizei.IN("height", "the height of the texture image"), GLsizei.IN("depth", "the depth of the texture image"), Expression("0")..GLint.IN("border", "must be 0"), AutoSize("data")..GLsizei.IN("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"), PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "a pointer to the compressed image data") ) void( "CompressedTexImage2DARB", "Specifies a two-dimensional texture image in a compressed format.", GLenum.IN("target", "the target texture", "$TEXTURE_2D_TARGETS $PROXY_TEXTURE_2D_TARGETS"), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), GLenum.IN("internalformat", "the format of the compressed image data", CompressTexImageFormats), GLsizei.IN("width", "the width of the texture image"), GLsizei.IN("height", "the height of the texture image"), Expression("0")..GLint.IN("border", "must be 0"), AutoSize("data")..GLsizei.IN("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"), PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "a pointer to the compressed image data") ) void( "CompressedTexImage1DARB", "Specifies a one-dimensional texture image in a compressed format.", GLenum.IN("target", "the target texture", "GL11#TEXTURE_1D GL11#PROXY_TEXTURE_1D"), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), GLenum.IN("internalformat", "the format of the compressed image data", CompressTexImageFormats), GLsizei.IN("width", "the width of the texture image"), Expression("0")..GLint.IN("border", "must be 0"), AutoSize("data")..GLsizei.IN("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"), PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "a pointer to the compressed image data") ) void( "CompressedTexSubImage3DARB", "Respecifies only a cubic subregion of an existing 3D texel array, with incoming data stored in a specific compressed image format.", GLenum.IN("target", "the target texture", TEXTURE_3D_TARGETS), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), GLint.IN("xoffset", "a texel offset in the x direction within the texture array"), GLint.IN("yoffset", "a texel offset in the y direction within the texture array"), GLint.IN("zoffset", "a texel offset in the z direction within the texture array"), GLsizei.IN("width", "the width of the texture subimage"), GLsizei.IN("height", "the height of the texture subimage"), GLsizei.IN("depth", "the depth of the texture subimage"), GLenum.IN("format", "the format of the compressed image data stored at address {@code data}", CompressTexImageFormats), AutoSize("data")..GLsizei.IN("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"), PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "a pointer to the compressed image data") ) void( "CompressedTexSubImage2DARB", "Respecifies only a rectangular subregion of an existing 2D texel array, with incoming data stored in a specific compressed image format.", GLenum.IN("target", "the target texture", TEXTURE_2D_TARGETS), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), GLint.IN("xoffset", "a texel offset in the x direction within the texture array"), GLint.IN("yoffset", "a texel offset in the y direction within the texture array"), GLsizei.IN("width", "the width of the texture subimage"), GLsizei.IN("height", "the height of the texture subimage"), GLenum.IN("format", "the format of the compressed image data stored at address {@code data}", CompressTexImageFormats), AutoSize("data")..GLsizei.IN("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"), PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "a pointer to the compressed image data") ) void( "CompressedTexSubImage1DARB", "Respecifies only a subregion of an existing 1D texel array, with incoming data stored in a specific compressed image format.", GLenum.IN("target", "the target texture", "GL11#TEXTURE_1D"), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), GLint.IN("xoffset", "a texel offset in the x direction within the texture array"), GLsizei.IN("width", "the width of the texture subimage"), GLenum.IN("format", "the format of the compressed image data stored at address {@code data}", CompressTexImageFormats), AutoSize("data")..GLsizei.IN("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"), PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "a pointer to the compressed image data") ) void( "GetCompressedTexImageARB", "Returns a compressed texture image.", GLenum.IN("target", "the target texture", "GL11#TEXTURE_1D $TEXTURE_2D_FACE_TARGETS $TEXTURE_3D_TARGETS"), GLint.IN("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."), Check( expression = "GL11.glGetTexLevelParameteri(target, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB)", debug = true )..PIXEL_PACK_BUFFER..void_p.OUT("pixels", "a buffer in which to return the compressed texture image") ) }
bsd-3-clause
7b0013925f1f13ebc91cc1fed5f31636
54.517647
154
0.749285
3.963461
false
false
false
false
Adonai/Man-Man
app/src/main/java/com/adonai/manman/ManLocalArchiveFragment.kt
1
11845
package com.adonai.manman import android.content.* import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import android.util.Log import android.view.* import android.widget.AdapterView.OnItemClickListener import android.widget.ListView import android.widget.SearchView import androidx.annotation.UiThread import androidx.annotation.WorkerThread import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.lifecycleScope import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.preference.PreferenceManager import com.adonai.manman.adapters.LocalArchiveArrayAdapter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request import org.apache.commons.compress.utils.CountingInputStream import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* import java.util.zip.ZipFile /** * Fragment for uploading and parsing local man page distributions * * @author Kanedias */ class ManLocalArchiveFragment : Fragment(), OnSharedPreferenceChangeListener { private var mUserAgreedToDownload = false private val mBroadcastHandler: BroadcastReceiver = LocalArchiveBroadcastReceiver() private lateinit var mPreferences: SharedPreferences // needed for folder list retrieval private lateinit var mLocalPageList: ListView private lateinit var mSearchLocalPage: SearchView private lateinit var mLocalArchive: File /** * Click listener for loading man page from selected archive file (or show config if no folders are present) * <br></br> * Archives are pretty small, so gzip decompression and parsing won't take loads of time... * <br></br> * Long story short, let's try to do this in UI and look at the performance * */ private val mManArchiveClickListener = OnItemClickListener { parent, _, position, _ -> mSearchLocalPage.clearFocus() // otherwise we have to click "back" twice val data = parent.getItemAtPosition(position) as? File if (data == null) { // header is present, start config tool when (position) { 0 -> showFolderSettingsDialog() 1 -> downloadArchive() } } else { val mpdf = ManPageDialogFragment.newInstance(data.name, data.path) parentFragmentManager .beginTransaction() .addToBackStack("PageFromLocalArchive") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .replace(R.id.replacer, mpdf) .commit() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { setHasOptionsMenu(true) mLocalArchive = File(requireContext().cacheDir, "manpages.zip") mPreferences = PreferenceManager.getDefaultSharedPreferences(activity) mPreferences.registerOnSharedPreferenceChangeListener(this) val root = inflater.inflate(R.layout.fragment_local_storage, container, false) mLocalPageList = root.findViewById<View>(R.id.local_storage_page_list) as ListView mSearchLocalPage = root.findViewById<View>(R.id.local_search_edit) as SearchView mLocalPageList.onItemClickListener = mManArchiveClickListener mSearchLocalPage.setOnQueryTextListener(FilterLocalStorage()) triggerReloadLocalContent() LocalBroadcastManager.getInstance(requireContext()).registerReceiver(mBroadcastHandler, IntentFilter(MainPagerActivity.LOCAL_CHANGE_NOTIFY)) return root } override fun onDestroyView() { super.onDestroyView() mPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.local_archive_menu, menu) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) // don't show it if we already have archive menu.findItem(R.id.download_archive).isVisible = !mLocalArchive.exists() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.folder_settings -> { showFolderSettingsDialog() return true } R.id.download_archive -> { downloadArchive() return true } } return super.onOptionsItemSelected(item) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (key == MainPagerActivity.FOLDER_LIST_KEY) { // the only needed key triggerReloadLocalContent() } } @UiThread private fun triggerReloadLocalContent() { lifecycleScope.launch { val localPages = withContext(Dispatchers.IO) { doLoadContent() } if (mLocalPageList.headerViewsCount > 0) { mLocalPageList.removeHeaderView(mLocalPageList.getChildAt(0)) mLocalPageList.removeHeaderView(mLocalPageList.getChildAt(1)) } mLocalPageList.adapter = null // for android < kitkat for header to work properly if (localPages.isEmpty()) { mSearchLocalPage.visibility = View.GONE val header1 = View.inflate(activity, R.layout.add_folder_header, null) val header2 = View.inflate(activity, R.layout.load_archive_header, null) mLocalPageList.addHeaderView(header1) mLocalPageList.addHeaderView(header2) } else { mSearchLocalPage.visibility = View.VISIBLE } mLocalPageList.adapter = LocalArchiveArrayAdapter(requireContext(), R.layout.chapter_command_list_item, R.id.command_name_label, localPages) } } @WorkerThread private fun doLoadContent(): List<File> { val collectedPages: MutableList<File> = ArrayList() // results from locally-defined folders val folderList = mPreferences.getStringSet(MainPagerActivity.FOLDER_LIST_KEY, HashSet())!! for (path in folderList) { val targetedFolder = File(path) if (targetedFolder.exists() && targetedFolder.isDirectory) { // paranoid check, we already checked in dialog! walkFileTree(targetedFolder, collectedPages) } } // results from local archive, if exists if (mLocalArchive.exists()) { // it's a tar-gzipped archive with standard structure populateWithLocal(collectedPages) } // sort results alphabetically... collectedPages.sort() return collectedPages } @WorkerThread private fun populateWithLocal(result: MutableList<File>) { try { val zip = ZipFile(mLocalArchive) val entries = zip.entries() while (entries.hasMoreElements()) { val zEntry = entries.nextElement() if (zEntry.isDirectory) continue result.add(File("local:", zEntry.name)) } } catch (e: IOException) { Log.e(Utils.MM_TAG, "Exception while parsing local archive", e) Utils.showToastFromAnyThread(activity, R.string.error_parsing_local_archive) } } @WorkerThread private fun walkFileTree(directoryRoot: File, resultList: MutableList<File>) { val list = directoryRoot.listFiles() ?: // unknown, happens on some devices return for (f in list) { if (f.isDirectory) { walkFileTree(f, resultList) } else if (f.name.toLowerCase().endsWith(".gz")) { // take only gzipped files resultList.add(f) } } } private fun showFolderSettingsDialog() { FolderChooseFragment().show(parentFragmentManager, "FolderListFragment") } /** * Load archive to app data folder from my GitHub releases page */ @UiThread private fun downloadArchive() { if (mLocalArchive.exists()) { return } if (!mUserAgreedToDownload) { AlertDialog.Builder(requireContext()) .setTitle(R.string.confirm_action) .setMessage(R.string.confirm_action_load_archive) .setPositiveButton(android.R.string.ok) { _, _ -> mUserAgreedToDownload = true downloadArchive() }.setNegativeButton(android.R.string.no, null) .create().show() return } // kind of stupid to make a loader just for oneshot DL task... // OK, let's do it old way... lifecycleScope.launch { val pd = AlertDialog.Builder(requireContext()) .setTitle(R.string.downloading) .setMessage(R.string.please_wait) .create() pd.show() withContext(Dispatchers.IO) { doDownloadArchive(pd, LOCAL_ARCHIVE_URL) } pd.dismiss() triggerReloadLocalContent() } } @WorkerThread private suspend fun doDownloadArchive(pd: AlertDialog, archiveUrl: String) { try { val client = OkHttpClient() val request = Request.Builder().url(archiveUrl).build() val response = client.newCall(request).execute() if (!response.isSuccessful) { withContext(Dispatchers.Main) { Utils.showToastFromAnyThread(activity, R.string.no_archive_on_server) } return } val contentLength = response.body!!.contentLength() val cis = CountingInputStream(response.body!!.byteStream()) FileOutputStream(mLocalArchive).use { fos -> val buffer = ByteArray(8096) var read: Int while (cis.read(buffer).also { read = it } != -1) { fos.write(buffer, 0, read) val downloadedPct = cis.bytesRead * 100 / contentLength withContext(Dispatchers.Main) { pd.setMessage(getString(R.string.please_wait) + " ${downloadedPct}%") } } } } catch (e: IOException) { Log.e(Utils.MM_TAG, "Exception while downloading man pages archive", e) Utils.showToastFromAnyThread(activity, e.message) } } private inner class FilterLocalStorage : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { applyFilter(query) return true } override fun onQueryTextChange(newText: String): Boolean { applyFilter(newText) return true } private fun applyFilter(text: CharSequence) { // safe to cast, we have only this type of adapter here val adapter = mLocalPageList.adapter as? LocalArchiveArrayAdapter adapter?.filter?.filter(text) } } /** * Handler to receive notifications for changes in local archive (to update local list view) */ private inner class LocalArchiveBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { triggerReloadLocalContent() } } companion object { private const val LOCAL_ARCHIVE_URL = "https://github.com/Adonai/Man-Man/releases/download/1.6.0/manpages.zip" } }
gpl-3.0
4af0337bd5d8edb37a371f7b304f9d75
37.712418
152
0.639341
5.036139
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/common/domain/criteria/ClientSearchCriteria.kt
3
2831
package com.mycollab.common.domain.criteria import com.mycollab.common.i18n.ClientI18nEnum import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.db.arguments.NumberSearchField import com.mycollab.db.arguments.SearchCriteria import com.mycollab.db.arguments.SetSearchField import com.mycollab.db.arguments.StringSearchField import com.mycollab.db.query.* import com.mycollab.module.project.ProjectTypeConstants class ClientSearchCriteria : SearchCriteria() { var name: StringSearchField? = null var assignUser: StringSearchField? = null var website: StringSearchField? = null var types: SetSearchField<String>? = null var industries: SetSearchField<String>? = null var assignUsers: SetSearchField<String>? = null var anyCity: StringSearchField? = null var anyPhone: StringSearchField? = null var anyAddress: StringSearchField? = null var anyMail: StringSearchField? = null var id: NumberSearchField? = null companion object { private val serialVersionUID = 1L @JvmField val p_name = CacheParamMapper.register(ProjectTypeConstants.CLIENT, ClientI18nEnum.FORM_ACCOUNT_NAME, StringParam("name", "m_client", "name")) @JvmField val p_website = CacheParamMapper.register(ProjectTypeConstants.CLIENT, ClientI18nEnum.FORM_WEBSITE, StringParam("website", "m_client", "website")) @JvmField val p_numemployees = CacheParamMapper.register(ProjectTypeConstants.CLIENT, ClientI18nEnum.FORM_EMPLOYEES, NumberParam("employees", "m_client", "numemployees")) @JvmField val p_assignee: PropertyListParam<*> = CacheParamMapper.register(ProjectTypeConstants.CLIENT, GenericI18Enum .FORM_ASSIGNEE, PropertyListParam<String>("assignuser", "m_client", "assignUser")) @JvmField val p_createdtime = CacheParamMapper.register(ProjectTypeConstants.CLIENT, GenericI18Enum.FORM_CREATED_TIME, DateParam("createdtime", "m_client", "createdTime")) @JvmField val p_lastupdatedtime = CacheParamMapper.register(ProjectTypeConstants.CLIENT, GenericI18Enum.FORM_LAST_UPDATED_TIME, DateParam("lastupdatedtime", "m_client", "lastUpdatedTime")) @JvmField val p_anyCity = CacheParamMapper.register(ProjectTypeConstants.CLIENT, ClientI18nEnum.FORM_ANY_CITY, CompositionStringParam("anyCity", StringParam("", "m_client", "city"), StringParam("", "m_client", "shippingCity"))) @JvmField val p_anyPhone = CacheParamMapper.register(ProjectTypeConstants.CLIENT, ClientI18nEnum.FORM_ANY_PHONE, CompositionStringParam("anyPhone", StringParam("", "m_client", "alternatePhone"), StringParam("", "m_client", "phoneOffice"))) } }
agpl-3.0
0846b15064be2d9ab1e7aafddd38325e
48.684211
126
0.710703
4.395963
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/EventCardsProvider.kt
1
1069
package de.tum.`in`.tumcampusapp.component.ui.ticket import android.content.Context import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card import de.tum.`in`.tumcampusapp.component.ui.overview.card.ProvidesCard import de.tum.`in`.tumcampusapp.component.ui.ticket.repository.EventsLocalRepository import java.util.* import javax.inject.Inject class EventCardsProvider @Inject constructor(private val context: Context, private val localRepository: EventsLocalRepository) : ProvidesCard { fun setDismissed(id: Int) { localRepository.setDismissed(id) } override fun getCards(cacheControl: CacheControl): List<Card> { val results = ArrayList<Card>() // Add the next upcoming event that is not the next kino event val event = localRepository.getNextEventWithoutMovie() if (event != null) { val eventCard = EventCard(context) eventCard.event = event results.add(eventCard) } return results } }
gpl-3.0
a897a3c9c6fbfbe78e89528bb7bcbe86
33.483871
110
0.721235
4.345528
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/AImageListQuestAnswerFragment.kt
1
4103
package de.westnordost.streetcomplete.quests import android.content.Context import android.os.Bundle import androidx.recyclerview.widget.GridLayoutManager import android.view.View import androidx.preference.PreferenceManager import java.util.ArrayList import java.util.LinkedList import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.view.image_select.DisplayItem import de.westnordost.streetcomplete.view.image_select.ImageSelectAdapter import kotlinx.android.synthetic.main.quest_generic_list.* /** * Abstract class for quests with a list of images and one or several to select. * * I is the type of each item in the image list (a simple model object). In MVC, this would * be the view model. * * T is the type of the answer object (also a simple model object) created by the quest * form and consumed by the quest type. In MVC, this would be the model. */ abstract class AImageListQuestAnswerFragment<I,T> : AbstractQuestFormAnswerFragment<T>() { override val contentLayoutResId = R.layout.quest_generic_list override val defaultExpanded = false protected lateinit var imageSelector: ImageSelectAdapter<I> private lateinit var favs: LastPickedValuesStore<I> protected open val itemsPerRow = 4 /** return -1 for any number. Default: 1 */ protected open val maxSelectableItems = 1 /** return true to move last picked items to the front. On by default. Only respected if the * items do not all fit into one line */ protected open val moveFavoritesToFront = true protected abstract val items: List<DisplayItem<I>> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) imageSelector = ImageSelectAdapter(maxSelectableItems) } override fun onAttach(ctx: Context) { super.onAttach(ctx) favs = LastPickedValuesStore(PreferenceManager.getDefaultSharedPreferences(ctx.applicationContext)) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) list.layoutManager = GridLayoutManager(activity, itemsPerRow) list.isNestedScrollingEnabled = false selectHintLabel.setText(if (maxSelectableItems == 1) R.string.quest_roofShape_select_one else R.string.quest_select_hint) imageSelector.listeners.add(object : ImageSelectAdapter.OnItemSelectionListener { override fun onIndexSelected(index: Int) { checkIsFormComplete() } override fun onIndexDeselected(index: Int) { checkIsFormComplete() } }) showMoreButton.visibility = View.GONE imageSelector.items = moveFavouritesToFront(items) if (savedInstanceState != null) { val selectedIndices = savedInstanceState.getIntegerArrayList(SELECTED_INDICES)!! imageSelector.select(selectedIndices) } list.adapter = imageSelector } override fun onClickOk() { val values = imageSelector.selectedItems if (values.isNotEmpty()) { favs.add(javaClass.simpleName, values) onClickOk(values) } } protected abstract fun onClickOk(selectedItems: List<I>) override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // note: the view might be not available anymore at this point! outState.putIntegerArrayList(SELECTED_INDICES, ArrayList(imageSelector.selectedIndices)) } override fun isFormComplete() = imageSelector.selectedIndices.isNotEmpty() private fun moveFavouritesToFront(originalList: List<DisplayItem<I>>): List<DisplayItem<I>> { val result: LinkedList<DisplayItem<I>> = LinkedList(originalList) if (result.size > itemsPerRow && moveFavoritesToFront) { favs.moveLastPickedDisplayItemsToFront(javaClass.simpleName, result, originalList) } return result } companion object { private const val SELECTED_INDICES = "selected_indices" } }
gpl-3.0
ff5e5aa67145d16f99f71941d033a3bd
35.633929
129
0.71533
4.943373
false
false
false
false
savvasdalkitsis/gameframe
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/layer/view/LayerViewHolder.kt
1
3707
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.element.layer.view import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.savvasdalkitsis.gameframe.feature.workspace.R import com.savvasdalkitsis.gameframe.feature.workspace.element.grid.view.LedGridView import com.savvasdalkitsis.gameframe.feature.workspace.element.layer.model.Layer import com.savvasdalkitsis.gameframe.kotlin.* internal class LayerViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_layer_view, parent, false)) { private val ledGridView: LedGridView = itemView.findViewById(R.id.view_layer_thumbnail) private val visibilityVisible: View = itemView.findViewById(R.id.view_layer_visibility_visible) private val visibilityInvisible: View = itemView.findViewById(R.id.view_layer_visibility_invisible) private val delete: View = itemView.findViewById(R.id.view_layer_delete) private val duplicate: View = itemView.findViewById(R.id.view_layer_duplicate) private val settings: View = itemView.findViewById(R.id.view_layer_settings) private val title: TextView = itemView.findViewById(R.id.view_layer_title) init { ledGridView.setThumbnailMode() } fun bind(layer: Layer) { itemView.isSelected = layer.isSelected title.text = layer.layerSettings.title ledGridView.display(layer.colorGrid) delete.visible() duplicate.visible() settings.visible() visibilityVisible.visibleOrGone(layer.isVisible) visibilityInvisible.visibleOrGone(!layer.isVisible) if (layer.isBackground) { listOf(delete, duplicate, settings, visibilityInvisible, visibilityVisible) .forEach { it.gone() } } } fun clearListeners() { setOnClickListener(null) setOnItemDeletedListener(null) setOnLayerDuplicatedListener(null) setOnLayerSettingsClickedListener(null) setOnLayerVisibilityChangedListener(null) } fun setOnClickListener(onClickListener: ViewAction?) = itemView.setOnClickListener(onClickListener) fun setOnItemDeletedListener(onItemDeletedListener: Action?) = delete.setOnClickListener { onItemDeletedListener?.invoke() } fun setOnLayerDuplicatedListener(onLayerDuplicatedListener: Action?) = duplicate.setOnClickListener { onLayerDuplicatedListener?.invoke() } fun setOnLayerSettingsClickedListener(onLayerSettingsClickedListener: Action?) = settings.setOnClickListener { onLayerSettingsClickedListener?.invoke() } fun setOnLayerVisibilityChangedListener(onLayerVisibilityChangedListener: OnLayerVisibilityChangedListener?) { visibilityVisible.setOnClickListener { onLayerVisibilityChangedListener?.invoke(false) } visibilityInvisible.setOnClickListener { onLayerVisibilityChangedListener?.invoke(true) } } }
apache-2.0
56a8b8d12a5c8af6a0cf9268e837b21c
43.674699
119
0.755328
4.698352
false
false
false
false
jdiazcano/modulartd
editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/CoinEditor.kt
1
3697
package com.jdiazcano.modulartd.ui.widgets import com.jdiazcano.modulartd.beans.Coin import com.jdiazcano.modulartd.bus.Bus import com.jdiazcano.modulartd.bus.BusTopic import com.jdiazcano.modulartd.ui.AnimatedActor import com.jdiazcano.modulartd.utils.changeListener import com.jdiazcano.modulartd.utils.clickListener import com.jdiazcano.modulartd.utils.input import com.jdiazcano.modulartd.utils.translate import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.VisTable import com.kotcrab.vis.ui.widget.VisTextButton import com.kotcrab.vis.ui.widget.VisValidatableTextField /** * This will let you edit (add, modify or delete) all the coins that you have in your map */ class CoinEditor(val coins: MutableList<Coin>): VisTable(true) { private val list = CoinListView(coins) private val addCoin = VisTextButton(translate("coin.add")) // TODO translate private val renameCoin = VisTextButton(translate("coin.rename")) init { Bus.register<Coin>(BusTopic.DELETED) { deletedCoin -> list.removeItem(deletedCoin) list.notifyDataSetChanged() } Bus.register<Coin>(BusTopic.CREATED) { addedCoin -> list.addItem(addedCoin) list.notifyDataSetChanged() } // TODO something to add a coin, it should ask only for the name or also the icon... buildTable() setUpListeners() } private fun setUpListeners() { addCoin.changeListener { _, _ -> input("Coin name", "Coin name") { Bus.post(Coin(it), BusTopic.CREATED) } } renameCoin.changeListener { _, _ -> input("Coin name", "Coin name") { list.selectedItem.name = it list.notifyDataSetChanged() } } } private fun buildTable() { add(list).colspan(999).expand().fill().row() add(addCoin).expandX().center() add(renameCoin).expandX().center() } } class CoinListView(objects: MutableList<Coin>): TableList<Coin, CoinEditorRow>(objects) { override fun getView(position: Int, lastView: CoinEditorRow?): CoinEditorRow { val coin = getItem(position) val view = if (lastView == null) { val objectView = CoinEditorRow(coin) objectView.clickListener { _, _, _ -> Bus.post(getItem(position), BusTopic.SELECTED) } objectView } else { lastView.name.setText(coin.name) lastView.icon.swapResource(coin.resource) lastView } return view } } /** * Defines how the row of a coin while editing it will look like * * Will look like: * * ICON: Name StartingValue (x) */ class CoinEditorRow(val coin: Coin): VisTable() { val name = VisLabel(coin.name) val icon = AnimatedActor(coin.resource) val startingValue = VisValidatableTextField("0") private val delete = VisTextButton("x") init { buildTable() setUpListeners() setUpValidatableForm() } private fun setUpValidatableForm() { startingValue.addValidator { input -> input.toIntOrNull() != null } } private fun setUpListeners() { delete.changeListener { _, _ -> Bus.post(coin, BusTopic.DELETED) } name.clickListener { _, _, _ -> Bus.post(coin, BusTopic.SELECTED) } } private fun buildTable() { name.setWrap(true) add(icon).size(24F) add(name).expandX().left().maxWidth(200F).padRight(10F) add(startingValue).width(50F).padRight(3F) add(delete) } }
apache-2.0
aec3f5fed188b56f4f64e9099ee02668
27.446154
92
0.622938
4.225143
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOption.kt
1
3005
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject class DanaRSPacketOptionSetUserOption( injector: HasAndroidInjector ) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION aapsLogger.debug(LTag.PUMPCOMM, "Setting user settings") } override fun getRequestParams(): ByteArray { aapsLogger.debug( LTag.PUMPCOMM, "UserOptions:" + (System.currentTimeMillis() - danaPump.lastConnection) / 1000 + " s ago" + "\ntimeDisplayType24:" + danaPump.timeDisplayType24 + "\nbuttonScroll:" + danaPump.buttonScrollOnOff + "\nbeepAndAlarm:" + danaPump.beepAndAlarm + "\nlcdOnTimeSec:" + danaPump.lcdOnTimeSec + "\nbacklight:" + danaPump.backlightOnTimeSec + "\ndanaRPumpUnits:" + danaPump.units + "\nlowReservoir:" + danaPump.lowReservoirRate + "\ncannulaVolume:" + danaPump.cannulaVolume + "\nrefillAmount:" + danaPump.refillAmount + "\ntarget:" + danaPump.target) val size = if (danaPump.hwModel >= 7) 15 else 13 val request = ByteArray(size) request[0] = if (danaPump.timeDisplayType24) 0.toByte() else 1.toByte() request[1] = if (danaPump.buttonScrollOnOff) 1.toByte() else 0.toByte() request[2] = (danaPump.beepAndAlarm and 0xff).toByte() request[3] = (danaPump.lcdOnTimeSec and 0xff).toByte() request[4] = (danaPump.backlightOnTimeSec and 0xff).toByte() request[5] = (danaPump.selectedLanguage and 0xff).toByte() request[6] = (danaPump.units and 0xff).toByte() request[7] = (danaPump.shutdownHour and 0xff).toByte() request[8] = (danaPump.lowReservoirRate and 0xff).toByte() request[9] = (danaPump.cannulaVolume and 0xff).toByte() request[10] = (danaPump.cannulaVolume ushr 8 and 0xff).toByte() request[11] = (danaPump.refillAmount and 0xff).toByte() request[12] = (danaPump.refillAmount ushr 8 and 0xff).toByte() if (danaPump.hwModel >= 7) { request[13] = (danaPump.target and 0xff).toByte() request[14] = (danaPump.target ushr 8 and 0xff).toByte() } return request } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override val friendlyName: String = "OPTION__SET_USER_OPTION" }
agpl-3.0
a5a066ec866f531dd89c474c6583abd0
42.565217
101
0.634942
4.386861
false
false
false
false
realm/realm-java
realm/realm-annotations-processor/src/main/java/io/realm/processor/RealmProxyInterfaceGenerator.kt
1
2980
/* * Copyright 2019 Realm 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 io.realm.processor import com.squareup.javawriter.JavaWriter import java.io.BufferedWriter import java.io.IOException import java.util.EnumSet import java.util.Locale import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Modifier import io.realm.annotations.Ignore class RealmProxyInterfaceGenerator(private val processingEnvironment: ProcessingEnvironment, private val metaData: ClassMetaData) { private val className: QualifiedClassName = metaData.qualifiedClassName @Throws(IOException::class) fun generate() { val qualifiedGeneratedInterfaceName = String.format(Locale.US, "%s.%s", Constants.REALM_PACKAGE_NAME, Utils.getProxyInterfaceName(className)) val sourceFile = processingEnvironment.filer.createSourceFile(qualifiedGeneratedInterfaceName) val writer = JavaWriter(BufferedWriter(sourceFile.openWriter()!!)) writer.apply { indent = Constants.INDENT emitPackage(Constants.REALM_PACKAGE_NAME) emitEmptyLine() beginType(qualifiedGeneratedInterfaceName, "interface", EnumSet.of(Modifier.PUBLIC)) for (field in metaData.fields) { if (field.modifiers.contains(Modifier.STATIC) || field.getAnnotation(Ignore::class.java) != null) { continue } // The field is neither static nor ignored val fieldName = field.simpleName.toString() val fieldTypeCanonicalName = field.asType().toString() beginMethod(fieldTypeCanonicalName, metaData.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC)) endMethod() // MutableRealmIntegers do not have setters. if (Utils.isMutableRealmInteger(field)) { continue } beginMethod("void", metaData.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value") endMethod() } // backlinks are final and have only a getter. for (backlink in metaData.backlinkFields) { beginMethod(backlink.targetFieldType, metaData.getInternalGetter(backlink.targetField), EnumSet.of(Modifier.PUBLIC)) endMethod() } endType() close() } } }
apache-2.0
d34edc837c2616b3524648170086b321
39.27027
149
0.677517
4.92562
false
false
false
false
orbite-mobile/monastic-jerusalem-community
app/src/main/java/pl/orbitemobile/wspolnoty/data/remote/mapper/ArticlesMapper.kt
1
1427
package pl.orbitemobile.wspolnoty.data.remote.mapper import android.util.Log import org.jsoup.Connection import org.jsoup.nodes.Element import org.jsoup.select.Elements import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO class ArticlesMapper private constructor() { companion object { val instance = ArticlesMapper() } fun mapArticles(response: Connection.Response): Array<ArticleDTO> { val articles = getArticles(response) return articles.map { getArticle(it) }.toTypedArray() } private fun getArticles(response: Connection.Response): Elements = response.parse().getElementsByAttributeValue("class", "vce-featured") private fun getArticle(element: Element): ArticleDTO { val title = getTitle(element) val imgUrl = getImgUrl(element) val articleUrl = getArticleUrl(element) return ArticleDTO(title, imgUrl, articleUrl) } private fun getTitle(article: Element): String = article.getElementsByAttributeValue("class", "vce-featured-title").text() private fun getArticleUrl(article: Element): String { val elements = article.getElementsByAttributeValue("class", "vce-featured-link-article") return elements[0].absUrl("href") } private fun getImgUrl(article: Element): String { val elements = article.getElementsByTag("img") return elements[0].absUrl("src") } }
agpl-3.0
698371d18a166d78fcf40e9bbee06c38
32.209302
96
0.702873
4.417957
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/accessors/PluginAccessorsClassPathTest.kt
3
6354
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.kotlin.dsl.accessors import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import org.gradle.kotlin.dsl.codegen.pluginEntriesFrom import org.gradle.kotlin.dsl.concurrent.withSynchronousIO import org.gradle.kotlin.dsl.fixtures.assertFailsWith import org.gradle.kotlin.dsl.fixtures.classLoaderFor import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.kotlin.dsl.fixtures.pluginDescriptorEntryFor import org.gradle.kotlin.dsl.support.useToRun import org.gradle.kotlin.dsl.support.zipTo import org.gradle.plugin.use.PluginDependenciesSpec import org.gradle.plugin.use.PluginDependencySpec import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.hasItems import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import java.io.File import java.util.zip.ZipException class PluginAccessorsClassPathTest : TestWithClassPath() { @Test fun `exception caused by empty jar carries file information`() { // given: val emptyJar = file("plugins.jar").apply { createNewFile() } // when: val exception = assertFailsWith(IllegalArgumentException::class) { pluginEntriesFrom(emptyJar) } // then: assertThat( exception.localizedMessage, containsString(emptyJar.name) ) assertThat( exception.cause, instanceOf(ZipException::class.java) ) } @Test fun `#buildPluginAccessorsFor`() { // given: val pluginsJar = jarWithPluginDescriptors( file("plugins.jar"), "my-plugin" to "MyPlugin", "my.own.plugin" to "my.own.Plugin" ) val srcDir = newFolder("src") val binDir = newFolder("bin") // when: withSynchronousIO { buildPluginAccessorsFor( pluginDescriptorsClassPath = classPathOf(pluginsJar), srcDir = srcDir, binDir = binDir ) } // then: val generatedAccessors = String(srcDir.resolve("org/gradle/kotlin/dsl/PluginAccessors.kt").readBytes()) assertThat( generatedAccessors, allOf( not(containsString("\r")), containsString("import MyPlugin"), containsMultiLineString( """ /** * The `my` plugin group. */ @org.gradle.api.Generated class `MyPluginGroup`(internal val plugins: PluginDependenciesSpec) /** * Plugin ids starting with `my`. */ val `PluginDependenciesSpec`.`my`: `MyPluginGroup` get() = `MyPluginGroup`(this) /** * The `my.own` plugin group. */ @org.gradle.api.Generated class `MyOwnPluginGroup`(internal val plugins: PluginDependenciesSpec) /** * Plugin ids starting with `my.own`. */ val `MyPluginGroup`.`own`: `MyOwnPluginGroup` get() = `MyOwnPluginGroup`(plugins) /** * The `my.own.plugin` plugin implemented by [my.own.Plugin]. */ val `MyOwnPluginGroup`.`plugin`: PluginDependencySpec get() = plugins.id("my.own.plugin") """ ) ) ) // and: classLoaderFor(binDir).useToRun { val className = "org.gradle.kotlin.dsl.PluginAccessorsKt" val accessorsClass = loadClass(className) assertThat( accessorsClass.declaredMethods.map { it.name }, hasItems("getMy", "getOwn", "getPlugin") ) val expectedPluginSpec = mock<PluginDependencySpec>() val plugins = mock<PluginDependenciesSpec> { on { id(any()) } doReturn expectedPluginSpec } accessorsClass.run { val myPluginGroup = getDeclaredMethod("getMy", PluginDependenciesSpec::class.java) .invoke(null, plugins)!! val myOwnPluginGroup = getDeclaredMethod("getOwn", myPluginGroup.javaClass) .invoke(null, myPluginGroup)!! val actualPluginSpec = getDeclaredMethod("getPlugin", myOwnPluginGroup.javaClass) .invoke(null, myOwnPluginGroup) as PluginDependencySpec assertThat( actualPluginSpec, sameInstance(expectedPluginSpec) ) } verify(plugins).id("my.own.plugin") verifyNoMoreInteractions(plugins) } } private fun jarWithPluginDescriptors(file: File, vararg pluginIdsToImplClasses: Pair<String, String>) = file.also { zipTo( it, pluginIdsToImplClasses.asSequence().map { (id, implClass) -> pluginDescriptorEntryFor(id, implClass) } ) } }
apache-2.0
34c7ec76ffd2c47b02530389183e7472
31.253807
111
0.581838
5.07103
false
false
false
false
JStege1206/AdventOfCode
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day01.kt
1
654
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.head import nl.jstege.adventofcode.aoccommon.utils.extensions.scan /** * * @author Jelle Stege */ class Day01 : Day(title = "Not Quite Lisp") { override fun first(input: Sequence<String>): Any = input.head .asSequence() .map { if (it == '(') 1 else -1 } .sum() override fun second(input: Sequence<String>): Any = input.head .asSequence() .map { if (it == '(') 1 else -1 } .scan(0, Int::plus) .takeWhile { it >= 0 } .count() }
mit
fbf61ab0dae4beb1931430515fe92551
27.434783
66
0.622324
3.593407
false
false
false
false
ingokegel/intellij-community
plugins/github/src/org/jetbrains/plugins/github/GithubCopyPathProvider.kt
1
1585
// 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.plugins.github import com.intellij.ide.actions.DumbAwareCopyPathProvider import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vfs.VirtualFile import git4idea.GitUtil import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager class GithubCopyPathProvider: DumbAwareCopyPathProvider() { override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?): String? { if (virtualFile == null) return null val fileStatus = ChangeListManager.getInstance(project).getStatus(virtualFile) if (fileStatus == FileStatus.UNKNOWN || fileStatus == FileStatus.ADDED || fileStatus == FileStatus.IGNORED) return null val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile) if (repository == null) return null val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository) if (accessibleRepositories.isEmpty()) return null val refs = accessibleRepositories .mapNotNull { GHPathUtil.getFileURL(repository, it.ghRepositoryCoordinates, virtualFile, editor) } .distinct() return if (refs.isNotEmpty()) refs.joinToString("\n") else null } }
apache-2.0
37d3ababd12facc9ed7e99926755d0cb
47.060606
158
0.796845
4.832317
false
false
false
false