repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jwren/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/ShowTypeBookmarksAction.kt | 3 | 4991 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.ide.bookmark.BookmarksManager
import com.intellij.ide.bookmark.ui.tree.BookmarkNode
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.ide.util.treeView.AbstractTreeNodeCache
import com.intellij.ide.util.treeView.AbstractTreeStructure
import com.intellij.ide.util.treeView.NodeDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.NAVIGATABLE
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.popup.PopupState
import com.intellij.ui.tree.AsyncTreeModel
import com.intellij.ui.tree.StructureTreeModel
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.EditSourceOnDoubleClickHandler
import com.intellij.util.containers.toArray
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.tree.TreeUtil
import java.awt.Dimension
import javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION
internal class ShowTypeBookmarksAction : DumbAwareAction(BookmarkBundle.messagePointer("show.type.bookmarks.action.text")) {
private val popupState = PopupState.forPopup()
private val BookmarksManager.typeBookmarks
get() = BookmarkType.values().mapNotNull { getBookmark(it)?.run { it to this } }.ifEmpty { null }
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = event.bookmarksManager?.assignedTypes?.isNotEmpty() ?: false
}
override fun actionPerformed(event: AnActionEvent) {
if (popupState.isRecentlyHidden) return
if (popupState.isShowing) return popupState.hidePopup()
val bookmarks = event.bookmarksManager?.typeBookmarks ?: return
val root = MyRoot(bookmarks.map { it.second })
val tree = Tree(AsyncTreeModel(StructureTreeModel(MyStructure(root), root), root)).apply {
isRootVisible = false
showsRootHandles = false
visibleRowCount = bookmarks.size
selectionModel.selectionMode = SINGLE_TREE_SELECTION
}
bookmarks.forEach { tree.registerBookmarkTypeAction(root, it.first) }
tree.registerEditSourceAction(root)
tree.registerNavigateOnEnterAction()
EditSourceOnDoubleClickHandler.install(tree)
TreeUtil.promiseSelectFirstLeaf(tree).onSuccess {
// show popup when tree is loaded
val popup = JBPopupFactory.getInstance()
.createComponentPopupBuilder(MyScrollPane(tree), tree)
.setTitle(BookmarkBundle.message("popup.title.type.bookmarks"))
.setFocusable(true)
.setRequestFocus(true)
.setCancelOnOtherWindowOpen(true)
.createPopup()
Disposer.register(popup, root)
popupState.prepareToShow(popup)
popup.showCenteredInCurrentWindow(event.project!!)
}
}
private class MyScrollPane(val tree: Tree) : DataProvider, JBScrollPane(tree) {
init {
border = JBUI.Borders.empty()
viewportBorder = JBUI.Borders.empty()
horizontalScrollBarPolicy = HORIZONTAL_SCROLLBAR_NEVER
}
override fun getPreferredSize(): Dimension? = super.getPreferredSize()?.also {
if (!isPreferredSizeSet) it.width = it.width.coerceAtMost(JBUI.scale(640))
}
override fun getData(dataId: String): Any? = when {
NAVIGATABLE.`is`(dataId) -> TreeUtil.getAbstractTreeNode(tree.selectionPath)
else -> null
}
}
private class MyRoot(bookmarks: List<Bookmark>) : Disposable, AbstractTreeNode<List<Bookmark>>(null, bookmarks) {
private val cache = AbstractTreeNodeCache<Bookmark, AbstractTreeNode<*>>(this) { it.createNode() }
override fun isAlwaysShowPlus() = true
override fun getChildren() = cache.getNodes(value).onEach {
if (it is BookmarkNode) it.bookmarkGroup = it.value.firstGroupWithDescription
}
override fun shouldUpdateData() = false
override fun update(presentation: PresentationData) = Unit
override fun dispose() = Unit
}
private class MyStructure(val root: MyRoot) : AbstractTreeStructure() {
override fun commit() = Unit
override fun hasSomethingToCommit() = false
override fun createDescriptor(element: Any, parent: NodeDescriptor<*>?) = element as NodeDescriptor<*>
override fun getRootElement() = root
override fun getParentElement(element: Any): Any? = (element as? AbstractTreeNode<*>)?.parent
override fun getChildElements(element: Any) = when (element) {
root -> root.children.toArray(arrayOf())
else -> emptyArray()
}
}
}
| apache-2.0 | da3e3d721bae51efa919a66f75c72828 | 40.591667 | 124 | 0.761771 | 4.557991 | false | false | false | false |
stefanmedack/cccTV | app/src/main/java/de/stefanmedack/ccctv/ui/main/MainActivity.kt | 1 | 921 | package de.stefanmedack.ccctv.ui.main
import android.os.Bundle
import android.view.KeyEvent
import de.stefanmedack.ccctv.R
import de.stefanmedack.ccctv.ui.base.BaseInjectableActivity
import de.stefanmedack.ccctv.util.replaceFragmentInTransaction
class MainActivity : BaseInjectableActivity() {
private val MAIN_TAG = "MAIN_TAG"
var fragment: MainFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_activity)
fragment = supportFragmentManager.findFragmentByTag(MAIN_TAG) as? MainFragment ?: MainFragment()
fragment?.let { frag ->
replaceFragmentInTransaction(frag, R.id.fragment, MAIN_TAG)
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return (fragment?.onKeyDown(keyCode) == true) || super.onKeyDown(keyCode, event)
}
}
| apache-2.0 | c8b400b98bd27a7ac46d1f8c11256075 | 30.758621 | 104 | 0.72747 | 4.492683 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/support/ShortcutUtils.kt | 1 | 990 | package com.maubis.scarlet.base.support
import android.app.PendingIntent
import android.content.Context
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import com.maubis.scarlet.base.support.utils.OsVersionUtils
fun addShortcut(context: Context, shortcut: ShortcutInfo) {
if (!OsVersionUtils.canAddLauncherShortcuts()) {
return
}
val shortcutManager = context.getSystemService(ShortcutManager::class.java)
if (shortcutManager === null) {
return
}
shortcutManager.dynamicShortcuts = listOf(shortcut)
if (shortcutManager.isRequestPinShortcutSupported) {
val pinShortcutInfo = ShortcutInfo.Builder(context, shortcut.id).build()
val pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo)
val successCallback = PendingIntent.getBroadcast(
context, 0,
pinnedShortcutCallbackIntent, 0)
shortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.intentSender)
}
} | gpl-3.0 | cd3beca87eb97dcb840d94db91cf5940 | 33.172414 | 98 | 0.79798 | 4.829268 | false | false | false | false |
chemickypes/Glitchy | glitchappcore/src/main/java/me/bemind/glitchappcore/history/HistoryLogic.kt | 1 | 2857 | package me.bemind.glitchappcore.history
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Bitmap
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import me.bemind.glitch.Effect
import me.bemind.glitchappcore.ImageDescriptor
import me.bemind.glitchappcore.ImageStorage
import java.util.*
/**
* Created by angelomoroni on 14/04/17.
*/
interface IHistoryLogic {
fun getStack(): ArrayList<ImageDescriptor>
fun setStack(list: List<ImageDescriptor>?)
fun back() : Bitmap?
fun canBack() : Boolean
fun addBitmap(bitmap: Bitmap, newImage:Boolean = false)
fun clearHistory()
var lastBitmap : Bitmap?
var firstBitmap : Bitmap?
var sizeHistory : Int
var hasHistory : Boolean
}
class HistoryLogic(val context:Context) : IHistoryLogic {
private val PREFERENCES_NAME = "history_preferences"
private val STACK_K: String? = "stack_k"
private val imageStorage = ImageStorage
private val historyPref : SharedPreferences by lazy {
context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE)
}
init {
imageStorage.context = context
}
override var lastBitmap: Bitmap?
get() = imageStorage.getLastBitmap()
set(value) {/*nothing*/ }
override var firstBitmap: Bitmap?
get() = imageStorage.firstBitmap()
set(value) {/*nothing*/}
override var sizeHistory: Int
get() = imageStorage.size()
set(value) {/*nothing*/}
override var hasHistory: Boolean
get() = sizeHistory>0
set(value) {/*nothing*/}
override fun addBitmap(bitmap: Bitmap,newImage: Boolean) {
if(newImage) clearHistory()
imageStorage.addBitmap(bitmap,Effect.BASE,newImage)
}
override fun clearHistory() {
imageStorage.clear()
historyPref.edit().putString(STACK_K,"").apply()
}
override fun setStack(list: List<ImageDescriptor>?) {
imageStorage.stack.clear()
if(list !=null) {
imageStorage.stack.addAll(list )
}else{
imageStorage.stack.addAll(getListFromStorage())
}
}
override fun back(): Bitmap? = imageStorage.back()
override fun getStack(): ArrayList<ImageDescriptor> {
val l = imageStorage.stack.getAllAsList()
historyPref.edit().putString(STACK_K,Gson().toJson(l)).apply()
return l
}
override fun canBack(): Boolean = imageStorage.canBack()
private fun getListFromStorage(): Collection<ImageDescriptor> {
val list = historyPref.getString(STACK_K,"")
if (list.isEmpty()){
return LinkedList()
}else{
val listType = object : TypeToken<LinkedList<ImageDescriptor>>() {}.type
return Gson().fromJson(list,listType)
}
}
} | apache-2.0 | 461d6e68952a8f85c4c2beee7d531c6a | 23.637931 | 84 | 0.658383 | 4.408951 | false | false | false | false |
androidx/androidx | buildSrc/public/src/main/kotlin/androidx/build/KmpPlatforms.kt | 3 | 3545 | /*
* 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.build
import java.util.Locale
import org.gradle.api.Project
/**
* A comma separated list of KMP target platforms you wish to enable / disable.
* e.g. '-jvm,+mac,+linux,+js'
*/
const val ENABLED_KMP_TARGET_PLATFORMS = "androidx.enabled.kmp.target.platforms"
enum class KmpPlatform {
JVM,
// Do _not_ enable unless you have read and understand this:
// https://blog.jetbrains.com/kotlin/2021/10/important-ua-parser-js-exploit-and-kotlin-js/
JS,
MAC,
LINUX;
companion object {
val native = listOf(MAC, LINUX)
val enabledByDefault = listOf(JVM)
private const val JVM_PLATFORM = "jvm"
private const val JS_PLATFORM = "js"
private const val MAC_ARM_64 = "macosarm64"
private const val MAC_OSX_64 = "macosx64"
private const val LINUX_64 = "linuxx64"
private const val IOS_SIMULATOR_ARM_64 = "iossimulatorarm64"
private const val IOS_X_64 = "iosx64"
private const val IOS_ARM_64 = "iosarm64"
val macPlatforms = listOf(MAC_ARM_64, MAC_OSX_64)
val linuxPlatforms = listOf(LINUX_64)
val iosPlatforms = listOf(IOS_SIMULATOR_ARM_64, IOS_ARM_64, IOS_X_64)
val nativePlatforms = macPlatforms + linuxPlatforms + iosPlatforms
}
}
object KmpFlagParser {
fun parse(flag: String?): Set<KmpPlatform> {
if (flag.isNullOrBlank()) {
return KmpPlatform.enabledByDefault.toSortedSet()
}
val enabled = KmpPlatform.enabledByDefault.toMutableList()
flag.split(",").forEach {
val directive = it.firstOrNull() ?: ""
val platform = it.drop(1)
when (directive) {
'+' -> enabled.addAll(matchingPlatforms(platform))
'-' -> enabled.removeAll(matchingPlatforms(platform))
else -> {
throw RuntimeException("Invalid value $flag for $ENABLED_KMP_TARGET_PLATFORMS")
}
}
}
return enabled.toSortedSet()
}
private fun matchingPlatforms(flag: String) = if (flag == "native") {
KmpPlatform.native
} else {
listOf(KmpPlatform.valueOf(flag.uppercase(Locale.getDefault())))
}
}
fun Project.enabledKmpPlatforms(): Set<KmpPlatform> {
val enabledPlatformsFlag = project.findProperty(ENABLED_KMP_TARGET_PLATFORMS) as? String
return KmpFlagParser.parse(enabledPlatformsFlag)
}
fun Project.enableJs(): Boolean = enabledKmpPlatforms().contains(KmpPlatform.JS)
fun Project.enableMac(): Boolean =
enabledKmpPlatforms().contains(KmpPlatform.MAC) || Multiplatform.isKotlinNativeEnabled(this)
fun Project.enableLinux(): Boolean =
enabledKmpPlatforms().contains(KmpPlatform.LINUX) || Multiplatform.isKotlinNativeEnabled(this)
fun Project.enableJvm(): Boolean = enabledKmpPlatforms().contains(KmpPlatform.JVM)
fun Project.enableNative(): Boolean = enableMac() && enableLinux() | apache-2.0 | 94cca60b34c5ea1daf9b164791ef4f51 | 37.967033 | 99 | 0.676164 | 4.160798 | false | false | false | false |
GunoH/intellij-community | platform/webSymbols/src/com/intellij/webSymbols/WebSymbolOrigin.kt | 1 | 1059 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.webSymbols
import com.intellij.webSymbols.impl.WebSymbolOriginImpl
import javax.swing.Icon
/*
* INAPPLICABLE_JVM_NAME -> https://youtrack.jetbrains.com/issue/KT-31420
* DEPRECATION -> @JvmDefault
**/
interface WebSymbolOrigin {
val framework: FrameworkId?
get() = null
val library: String?
get() = null
val version: String?
get() = null
val defaultIcon: Icon?
get() = null
val typeSupport: WebSymbolTypeSupport?
get() = null
companion object {
@JvmStatic
fun create(framework: FrameworkId? = null,
library: String? = null,
version: String? = null,
defaultIcon: Icon? = null,
typeSupport: WebSymbolTypeSupport? = null): WebSymbolOrigin =
WebSymbolOriginImpl(framework, library, version, defaultIcon, typeSupport)
@JvmStatic
fun empty(): WebSymbolOrigin =
WebSymbolOriginImpl.empty
}
} | apache-2.0 | 1df43ddd60e341012d7bb2ae4b965408 | 24.853659 | 120 | 0.674221 | 4.304878 | false | false | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/JpsLanguageLevelQuickFix.kt | 2 | 6913 | // 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.idea.maven.externalSystemIntegration.output.quickfixes
import com.intellij.build.events.MessageEvent
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.compiler.progress.BuildIssueContributor
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ui.configuration.ClasspathEditor
import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.pom.java.LanguageLevel
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectBundle.message
import org.jetbrains.idea.maven.project.MavenProjectsManager
import java.util.concurrent.CompletableFuture
class JpsLanguageLevelQuickFix : BuildIssueContributor {
private val matchersList = listOf(
listOf("source release", "requires target release"),
listOf("release version", "not supported"),
listOf("invalid source release:"),
listOf("invalid target release")
)
override fun createBuildIssue(project: Project,
moduleNames: Collection<String>,
title: String,
message: String,
kind: MessageEvent.Kind,
virtualFile: VirtualFile?,
navigatable: Navigatable?): BuildIssue? {
if (project.isDisposed) return null
val mavenManager = MavenProjectsManager.getInstance(project)
if (!mavenManager.isMavenizedProject) return null
if (moduleNames.size != 1) {
return null
}
val moduleName = moduleNames.first()
val module = ModuleManager.getInstance(project).findModuleByName(moduleName) ?: return null
val mavenProject = mavenManager.findProject(module) ?: return null
val moduleRootManager = ModuleRootManager.getInstance(module) ?: return null
val moduleJdk = moduleRootManager.sdk
val moduleProjectLanguageLevel = moduleJdk?.let { LanguageLevel.parse(it.versionString) } ?: return null
val sourceLanguageLevel = getLanguageLevelFromError(message) ?: return null
if (sourceLanguageLevel.isLessThan(moduleProjectLanguageLevel)) {
return getBuildIssueSourceVersionLess(sourceLanguageLevel, moduleProjectLanguageLevel, message, mavenProject, moduleRootManager)
}
else {
return getBuildIssueSourceVersionGreat(sourceLanguageLevel, moduleProjectLanguageLevel, message, moduleRootManager)
}
}
fun getLanguageLevelFromError(message: String): LanguageLevel? {
val targetMessage = matchersList
.filter { it.all { message.contains(it) } }
.map { message.substring(message.indexOf(it.first())) }
.firstOrNull() ?: return null
return targetMessage.replace("[^.0123456789]".toRegex(), " ")
.trim().split(" ")
.firstOrNull()?.let { LanguageLevel.parse(it) }
}
private fun getBuildIssueSourceVersionGreat(sourceLanguageLevel: LanguageLevel,
moduleProjectLanguageLevel: LanguageLevel,
errorMessage: String,
moduleRootManager: ModuleRootManager): BuildIssue {
val moduleName = moduleRootManager.module.name
val setupModuleSdkQuickFix = SetupModuleSdkQuickFix(moduleName, moduleRootManager.isSdkInherited)
val quickFixes = listOf(setupModuleSdkQuickFix)
val issueDescription = StringBuilder(errorMessage)
issueDescription.append("\n\n")
issueDescription.append(message("maven.quickfix.source.version.great", moduleName,
moduleProjectLanguageLevel.toJavaVersion(), sourceLanguageLevel.toJavaVersion(),
setupModuleSdkQuickFix.id))
return object : BuildIssue {
override val title: String = errorMessage
override val description: String = issueDescription.toString()
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
private fun getBuildIssueSourceVersionLess(sourceLanguageLevel: LanguageLevel,
moduleProjectLanguageLevel: LanguageLevel,
errorMessage: String,
mavenProject: MavenProject,
moduleRootManager: ModuleRootManager): BuildIssue {
val moduleName = moduleRootManager.module.name
val quickFixes = mutableListOf<BuildIssueQuickFix>()
val issueDescription = StringBuilder(errorMessage)
issueDescription.append("\n\n")
issueDescription.append(message("maven.quickfix.source.version.less.header", moduleName,
moduleProjectLanguageLevel.toJavaVersion(), sourceLanguageLevel.toJavaVersion()))
val setupModuleSdkQuickFix = SetupModuleSdkQuickFix(moduleName, moduleRootManager.isSdkInherited)
quickFixes.add(setupModuleSdkQuickFix)
issueDescription.append("\n")
issueDescription.append(message("maven.quickfix.source.version.less.part1",
sourceLanguageLevel.toJavaVersion(), setupModuleSdkQuickFix.id))
val updateSourceLevelQuickFix = UpdateSourceLevelQuickFix(mavenProject)
quickFixes.add(updateSourceLevelQuickFix)
issueDescription.append("\n")
issueDescription.append(message("maven.quickfix.source.version.less.part2",
moduleProjectLanguageLevel.toJavaVersion(), updateSourceLevelQuickFix.id))
return object : BuildIssue {
override val title: String = errorMessage
override val description: String = issueDescription.toString()
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
}
class SetupModuleSdkQuickFix(val moduleName: String, private val isSdkInherited: Boolean) : BuildIssueQuickFix {
override val id: String = "setup_module_sdk_quick_fix"
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
if (isSdkInherited) {
ProjectSettingsService.getInstance(project).openProjectSettings()
}
else {
ProjectSettingsService.getInstance(project).showModuleConfigurationDialog(moduleName, ClasspathEditor.getName())
}
return CompletableFuture.completedFuture<Any>(null)
}
} | apache-2.0 | 719d47f15b38310d0eed5ccdf0f34cf7 | 50.214815 | 158 | 0.701866 | 5.888416 | false | false | false | false |
Fotoapparat/Fotoapparat | fotoapparat/src/main/java/io/fotoapparat/view/FocusView.kt | 1 | 2401 | package io.fotoapparat.view
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.FrameLayout
import io.fotoapparat.hardware.metering.FocalRequest
import io.fotoapparat.hardware.metering.PointF
import io.fotoapparat.parameter.Resolution
/**
* A view which is metering the focus & exposure of the camera to specific areas, if possible.
*
* If the camera doesn't support focus metering on specific area this will only display a visual feedback.
*/
class FocusView
@JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), FocalPointSelector {
private val visualFeedbackCircle = FeedbackCircleView(context, attrs, defStyleAttr)
private var focusMeteringListener: ((FocalRequest) -> Unit)? = null
init {
clipToPadding = false
clipChildren = false
addView(visualFeedbackCircle)
}
override fun setFocalPointListener(listener: (FocalRequest) -> Unit) {
focusMeteringListener = listener
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
tapDetector.onTouchEvent(event)
return true
}
private val gestureDetectorListener = object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return focusMeteringListener
?.let {
it(FocalRequest(
point = PointF(
x = e.x,
y = e.y),
previewResolution = Resolution(
width = width,
height = height)))
visualFeedbackCircle.showAt(
x = e.x - visualFeedbackCircle.width / 2,
y = e.y - visualFeedbackCircle.height / 2)
performClick()
true
}
?: super.onSingleTapUp(e)
}
}
private val tapDetector = GestureDetector(context, gestureDetectorListener)
}
| apache-2.0 | 41f5fb1a8362aa228cc05b434aa31acb | 34.835821 | 106 | 0.600167 | 5.662736 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/java/src/service/project/GradleDependencyCollector.kt | 4 | 2183 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service.project
import com.intellij.ide.plugins.DependencyCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginAdvertiserService
import org.jetbrains.plugins.gradle.util.GradleConstants
class GradleDependencyCollector : DependencyCollector {
override fun collectDependencies(project: Project): List<String> {
val projectInfoList = ProjectDataManager.getInstance().getExternalProjectsData(project, GradleConstants.SYSTEM_ID)
val result = mutableListOf<String>()
for (externalProjectInfo in projectInfoList) {
val projectStructure = externalProjectInfo.externalProjectStructure ?: continue
val libraries = ExternalSystemApiUtil.findAll(projectStructure, ProjectKeys.LIBRARY)
for (libraryNode in libraries) {
val groupId = libraryNode.data.groupId
val artifactId = libraryNode.data.artifactId
if (groupId != null && artifactId != null) {
result.add("$groupId:$artifactId")
}
}
}
return result
}
}
class GradleDependencyUpdater : ExternalSystemTaskNotificationListenerAdapter() {
override fun onEnd(id: ExternalSystemTaskId) {
if (id.projectSystemId == GradleConstants.SYSTEM_ID && id.type == ExternalSystemTaskType.RESOLVE_PROJECT) {
id.findProject()?.let {
ApplicationManager.getApplication().executeOnPooledThread {
PluginAdvertiserService.getInstance().rescanDependencies(it)
}
}
}
}
}
| apache-2.0 | f68b8f2e66956d2afcd68c98dd0b57eb | 47.511111 | 120 | 0.78699 | 5.185273 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt | 5 | 7135 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.ui.NonFocusableCheckBox
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.types.KotlinType
import javax.swing.JCheckBox
class KotlinVariableInplaceIntroducer(
addedVariable: KtProperty,
originalExpression: KtExpression?,
occurrencesToReplace: Array<KtExpression>,
suggestedNames: Collection<String>,
val isVar: Boolean,
val doNotChangeVar: Boolean,
val expressionType: KotlinType?,
val noTypeInference: Boolean,
project: Project,
editor: Editor,
private val postProcess: (KtDeclaration) -> Unit
) : AbstractKotlinInplaceIntroducer<KtProperty>(
localVariable = addedVariable.takeIf { it.isLocal },
expression = originalExpression,
occurrences = occurrencesToReplace,
title = KotlinIntroduceVariableHandler.INTRODUCE_VARIABLE,
project = project,
editor = editor,
) {
private val suggestedNames = suggestedNames.toTypedArray()
private var expressionTypeCheckBox: JCheckBox? = null
private val addedVariablePointer = addedVariable.createSmartPointer()
private val addedVariable get() = addedVariablePointer.element
init {
initFormComponents {
if (!doNotChangeVar) {
val varCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.declare.with.var"))
varCheckBox.isSelected = isVar
varCheckBox.addActionListener {
myProject.executeWriteCommand(commandName, commandName) {
PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.document)
val psiFactory = KtPsiFactory(myProject)
val keyword = if (varCheckBox.isSelected) psiFactory.createVarKeyword() else psiFactory.createValKeyword()
addedVariable.valOrVarKeyword.replace(keyword)
}
}
addComponent(varCheckBox)
}
if (expressionType != null && !noTypeInference) {
val renderedType = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(expressionType)
expressionTypeCheckBox =
NonFocusableCheckBox(KotlinBundle.message("checkbox.text.specify.type.explicitly")).apply {
isSelected = false
addActionListener {
runWriteCommandAndRestart {
updateVariableName()
if (isSelected) {
addedVariable.typeReference = KtPsiFactory(myProject).createType(renderedType)
} else {
addedVariable.typeReference = null
}
}
}
addComponent(this)
}
}
}
}
override fun getVariable() = addedVariable
override fun suggestNames(replaceAll: Boolean, variable: KtProperty?) = suggestedNames
override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>) = addedVariable
override fun addAdditionalVariables(builder: TemplateBuilderImpl) {
val variable = addedVariable ?: return
variable.typeReference?.let {
val expression = SpecifyTypeExplicitlyIntention.createTypeExpressionForTemplate(expressionType!!, variable) ?: return@let
builder.replaceElement(it, "TypeReferenceVariable", expression, false)
}
}
override fun buildTemplateAndStart(
refs: Collection<PsiReference>,
stringUsages: Collection<Pair<PsiElement, TextRange>>,
scope: PsiElement,
containingFile: PsiFile
): Boolean {
myNameSuggestions = myNameSuggestions.mapTo(LinkedHashSet(), String::quoteIfNeeded)
myEditor.caretModel.moveToOffset(nameIdentifier!!.startOffset)
val result = super.buildTemplateAndStart(refs, stringUsages, scope, containingFile)
val templateState = TemplateManagerImpl
.getTemplateState(com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil.getTopLevelEditor(myEditor))
val variable = addedVariable
if (templateState != null && variable?.typeReference != null) {
templateState.addTemplateStateListener(SpecifyTypeExplicitlyIntention.createTypeReferencePostprocessor(variable))
}
return result
}
override fun getInitialName() = super.getInitialName().quoteIfNeeded()
override fun updateTitle(variable: KtProperty?, value: String?) {
expressionTypeCheckBox?.isEnabled = value == null || value.isIdentifier()
// No preview to update
}
override fun deleteTemplateField(psiField: KtProperty?) {
// Do not delete introduced variable as it was created outside of in-place refactoring
}
override fun isReplaceAllOccurrences() = true
override fun setReplaceAllOccurrences(allOccurrences: Boolean) {
}
override fun getComponent() = myWholePanel
override fun performIntroduce() {
val newName = inputName ?: return
val replacement = KtPsiFactory(myProject).createExpression(newName)
runWriteAction {
addedVariable?.setName(newName)
occurrences.forEach {
if (it.isValid) {
it.replace(replacement)
}
}
}
}
override fun moveOffsetAfter(success: Boolean) {
super.moveOffsetAfter(success)
if (success) {
addedVariable?.let { postProcess(it) }
}
}
} | apache-2.0 | fda86db40ca00c1bffcf27a6050d9bfd | 40.730994 | 158 | 0.686475 | 5.676213 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/styles/TextInputLayoutStyles.kt | 1 | 2748 | /*
* Copyright 2019-2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.material.styles
import android.content.Context
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StyleRes
import com.google.android.material.textfield.TextInputLayout
import splitties.views.dsl.core.NO_THEME
import splitties.views.dsl.core.styles.styledView
import splitties.views.dsl.material.R
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@JvmInline
value class TextInputLayoutStyles @PublishedApi internal constructor(
@PublishedApi internal val ctx: Context
) {
inline fun filledBox(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: TextInputLayout.() -> Unit = {}
): TextInputLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::TextInputLayout,
styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_FilledBox,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledBoxDense(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: TextInputLayout.() -> Unit = {}
): TextInputLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::TextInputLayout,
styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_FilledBox_Dense,
id = id,
theme = theme,
initView = initView
)
}
inline fun outlinedBox(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: TextInputLayout.() -> Unit = {}
): TextInputLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::TextInputLayout,
styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_OutlinedBox,
id = id,
theme = theme,
initView = initView
)
}
inline fun outlinedBoxDense(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: TextInputLayout.() -> Unit = {}
): TextInputLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::TextInputLayout,
styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_OutlinedBox_Dense,
id = id,
theme = theme,
initView = initView
)
}
}
| apache-2.0 | 45d321c075da7af9efdfa2f10405e9fe | 32.925926 | 114 | 0.63901 | 4.737931 | false | false | false | false |
cy6erGn0m/kotlin-frontend-plugin | examples/frontend-only/src/main/kotlin/test/hello/WebLinesView.kt | 1 | 1611 | package test.hello
import org.w3c.dom.*
import org.w3c.dom.events.*
import kotlin.browser.*
import kotlin.dom.*
class WebLinesView(val linesHolder: Element, formRoot: Element) : LinesView {
lateinit override var presenter: LinesPresenter
@Suppress("UNCHECKED_CAST_TO_NATIVE_INTERFACE")
private val input = formRoot.querySelector("input") as HTMLInputElement
@Suppress("UNCHECKED_CAST_TO_NATIVE_INTERFACE")
private val addButton = formRoot.querySelector("button") as HTMLButtonElement
private val buttonHandler: (Event) -> Unit = {
presenter.addButtonClicked()
}
private val inputHandler: (Event) -> Unit = { e ->
if (e is KeyboardEvent && e.keyCode == 13) {
presenter.inputEnterPressed()
}
}
init {
register()
}
override var inputText: String
get() = input.value
set(newValue) { input.value = newValue }
override fun focusInput() {
input.focus()
}
override fun addLine(lineText: String) {
document.createElement("p").apply {
textContent = " + " + lineText
linesHolder.appendChild(this)
}
}
override fun clearLines() {
linesHolder.clear()
}
override fun dispose() {
unregister()
}
private fun register() {
addButton.addEventListener("click", buttonHandler)
input.addEventListener("keypress", inputHandler)
}
private fun unregister() {
addButton.removeEventListener("click", buttonHandler)
input.removeEventListener("keypress", inputHandler)
}
}
| apache-2.0 | 7bf20a2759205eb26348d69104d22016 | 24.171875 | 81 | 0.636251 | 4.538028 | false | false | false | false |
gregcockroft/AndroidMath | mathdisplaylib/src/main/java/com/agog/mathdisplay/render/MTMathListDisplay.kt | 1 | 21741 | @file:Suppress("ConstantConditionIf")
package com.agog.mathdisplay.render
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import com.agog.mathdisplay.parse.NSNotFound
import com.agog.mathdisplay.parse.NSRange
import com.agog.mathdisplay.parse.*
import com.agog.mathdisplay.render.MTLinePosition.*
const val DEBUG = false
data class CGPoint(var x: Float = 0.0f, var y: Float = 0.0f)
data class CGRect(var x: Float = 0.0f, var y: Float = 0.0f, var width: Float = 0.0f, var height: Float = 0.0f)
open class MTDisplay(open var ascent: Float = 0.0f, open var descent: Float = 0.0f, open var width: Float = 0.0f,
var range: NSRange = NSRange(), var hasScript: Boolean = false) {
var shiftDown: Float = 0.0f
/// The distance from the axis to the top of the display
/// The distance from the axis to the bottom of the display
/// The width of the display
/// position: Position of the display with respect to the parent view or display.
// range: The range of characters supported by this item
/// Whether the display has a subscript/superscript following it.
/// The text color for this display
// The local color, if the color was mutated local with the color
// command
var position: CGPoint = CGPoint()
set(value) {
field = value.copy()
positionChanged()
}
var textColor: Int = Color.BLACK
set(value) {
field = value
colorChanged()
}
var localTextColor: Int = Color.TRANSPARENT
set(value) {
field = value
colorChanged()
}
init {
this.range = range.copy()
}
open fun positionChanged() {
}
open fun colorChanged() {
}
open fun draw(canvas: Canvas) {
if (DEBUG) {
val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
strokePaint.setColor(Color.RED)
canvas.drawLine(0.0f, -descent, width, ascent, strokePaint)
strokePaint.setColor(Color.GREEN)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawArc(position.x - 2, position.y - 2, position.x + 2, position.y + 2, 0f, 360f, false, strokePaint)
}
}
}
fun displayBounds(): CGRect {
return CGRect(position.x, position.y - descent, width, ascent + descent)
}
}
// List of normal atoms to display that would be an attributed string on iOS
// Since we do not allow kerning attribute changes this is a string displayed using the advances for the font
// Normally this is a single character. In some cases the string will be fused atoms
class MTCTLineDisplay(val str: String, range: NSRange, val font: MTFont, val atoms: List<MTMathAtom>) :
MTDisplay(range = range) {
init {
computeDimensions()
}
// Our own implementation of the ios6 function to get glyph path bounds.
fun computeDimensions() {
val glyphs = font.getGidListForString(str)
val num = glyphs.count()
val bboxes: Array<BoundingBox?> = arrayOfNulls(num)
val advances: Array<Float> = Array(num, { 0.0f })
// Get the bounds for these glyphs
font.mathTable.getBoundingRectsForGlyphs(glyphs.toList(), bboxes, num)
font.mathTable.getAdvancesForGlyphs(glyphs.toList(), advances, num)
this.width = 0.0f
for (i in 0 until num) {
val b = bboxes[i]
if (b != null) {
val ascent = maxOf(0.0f, b.upperRightY - 0)
// Descent is how much the line goes below the origin. However if the line is all above the origin, then descent can't be negative.
val descent = maxOf(0.0f, 0.0f - b.lowerLeftY)
if (ascent > this.ascent) {
this.ascent = ascent
}
if (descent > this.descent) {
this.descent = descent
}
this.width += advances[i]
}
}
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
val textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
textPaint.setColor(textColor)
val drawer = MTDrawFreeType(font.mathTable)
val glyphs = font.getGidListForString(str)
val num = glyphs.count()
val advances: Array<Float> = Array(num, { 0.0f })
font.mathTable.getAdvancesForGlyphs(glyphs, advances, num)
canvas.save()
canvas.translate(position.x, position.y)
canvas.scale(1.0f, -1.0f)
var x = 0.0f
for (i in 0 until num) {
drawer.drawGlyph(canvas, textPaint, glyphs[i], x, 0.0f)
x += advances[i]
}
textPaint.setColor(Color.RED)
canvas.restore()
}
}
/**
@typedef MTLinePosition
@brief The type of position for a line, i.e. subscript/superscript or regular.
*/
enum class MTLinePosition {
/// Regular
KMTLinePositionRegular,
/// Positioned at a subscript
KMTLinePositionSubscript,
/// Positioned at a superscript
KMTLinePositionSuperscript
}
class MTMathListDisplay(displays: List<MTDisplay>, range: NSRange) : MTDisplay(range = range) {
/// Where the line is positioned
var type: MTLinePosition = KMTLinePositionRegular
/// An array of MTDisplays which are positioned relative to the position of the
/// the current display.
var subDisplays: List<MTDisplay>? = null
/// If a subscript or superscript this denotes the location in the parent MTList. For a
/// regular list this is NSNotFound
var index = NSNotFound
init {
this.subDisplays = displays
this.recomputeDimensions()
}
override fun colorChanged() {
val sd = this.subDisplays
if (sd != null) {
for (displayAtom in sd.toList()) {
// set the global color, if there is no local color
if (displayAtom.localTextColor == Color.TRANSPARENT) {
displayAtom.textColor = this.textColor
} else {
displayAtom.textColor = displayAtom.localTextColor
}
}
}
}
override fun draw(canvas: Canvas) {
canvas.save()
if (DEBUG) {
val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
strokePaint.setColor(Color.BLACK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawArc(-4f, -4f, 4f, 4f, 4f, 180f, false, strokePaint)
}
}
canvas.translate(position.x, position.y)
if (DEBUG) {
val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
strokePaint.setColor(Color.BLUE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawArc(-3f, -3f, 3f, 3f, 0f, 360f, false, strokePaint)
}
}
// draw each atom separately
val sd = this.subDisplays
if (sd != null) {
for (displayAtom in sd.toList()) {
displayAtom.draw(canvas)
}
}
canvas.restore()
}
fun recomputeDimensions() {
var max_ascent = 0.0f
var max_descent = 0.0f
var max_width = 0.0f
val sd = this.subDisplays
if (sd != null) {
for (atom in sd.toList()) {
val ascent = maxOf(0.0f, atom.position.y + atom.ascent)
if (ascent > max_ascent) {
max_ascent = ascent
}
val descent = maxOf(0.0f, 0 - (atom.position.y - atom.descent))
if (descent > max_descent) {
max_descent = descent
}
val width = atom.width + atom.position.x
if (width > max_width) {
max_width = width
}
}
}
this.ascent = max_ascent
this.descent = max_descent
this.width = max_width
}
}
// MTFractionDisplay
class MTFractionDisplay(var numerator: MTMathListDisplay, var denominator: MTMathListDisplay, range: NSRange) :
MTDisplay(range = range) {
var linePosition = 0.0f
var lineThickness = 0.0f
// NSAssert(self.range.length == 1, @"Fraction range length not 1 - range (%lu, %lu)", (unsigned long)range.location, (unsigned long)range.length)
var numeratorUp: Float = 0.0f
set(value) {
field = value
this.updateNumeratorPosition()
}
var denominatorDown: Float = 0.0f
set(value) {
field = value
this.updateDenominatorPosition()
}
override var ascent: Float
get() = this.numerator.ascent + this.numeratorUp
set(value) {
}
override var descent: Float
get() = this.denominator.descent + this.denominatorDown
set(value) {
}
override var width: Float
get() = maxOf(this.numerator.width, this.denominator.width)
set(value) {
}
fun updateDenominatorPosition() {
this.denominator.position = CGPoint(this.position.x + (this.width - this.denominator.width) / 2, this.position.y - this.denominatorDown)
}
fun updateNumeratorPosition() {
this.numerator.position = CGPoint(this.position.x + (this.width - this.numerator.width) / 2, this.position.y + this.numeratorUp)
}
override fun positionChanged() {
this.updateDenominatorPosition()
this.updateNumeratorPosition()
}
override fun colorChanged() {
this.numerator.textColor = this.textColor
this.denominator.textColor = this.textColor
}
override fun draw(canvas: Canvas) {
this.numerator.draw(canvas)
this.denominator.draw(canvas)
if (lineThickness != 0f) {
val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
strokePaint.setColor(textColor)
strokePaint.strokeWidth = lineThickness
canvas.drawLine(position.x, position.y + linePosition, position.x + width, position.y + linePosition,
strokePaint)
}
}
}
// MTRadicalDisplay
class MTRadicalDisplay(val radicand: MTMathListDisplay, val radicalGlyph: MTDisplay, range: NSRange) :
MTDisplay(range = range) {
init {
updateRadicandPosition()
}
var radicalShift: Float = 0.0f
var degree: MTMathListDisplay? = null
var topKern: Float = 0.0f
var lineThickness: Float = 0.0f
fun setDegree(degree: MTMathListDisplay, fontMetrics: MTFontMathTable) {
// sets up the degree of the radical
var kernBefore = fontMetrics.radicalKernBeforeDegree
val kernAfter = fontMetrics.radicalKernAfterDegree
val raise = fontMetrics.radicalDegreeBottomRaisePercent * (this.ascent - this.descent)
// The layout is:
// kernBefore, raise, degree, kernAfter, radical
this.degree = degree
// the radical is now shifted by kernBefore + degree.width + kernAfter
this.radicalShift = kernBefore + degree.width + kernAfter
if (radicalShift < 0) {
// we can't have the radical shift backwards, so instead we increase the kernBefore such
// that _radicalShift will be 0.
kernBefore -= radicalShift
radicalShift = 0.0f
}
// Note: position of degree is relative to parent.
val deg = this.degree
if (deg != null) {
deg.position = CGPoint(this.position.x + kernBefore, this.position.y + raise)
// Update the width by the _radicalShift
this.width = radicalShift + radicalGlyph.width + this.radicand.width
}
// update the position of the radicand
this.updateRadicandPosition()
}
override fun positionChanged() {
updateRadicandPosition()
}
fun updateRadicandPosition() {
// The position of the radicand includes the position of the MTRadicalDisplay
// This is to make the positioning of the radical consistent with fractions and
// have the cursor position finding algorithm work correctly.
// move the radicand by the width of the radical sign
this.radicand.position = CGPoint(this.position.x + radicalShift + radicalGlyph.width, this.position.y)
}
override fun colorChanged() {
this.radicand.textColor = this.textColor
this.radicalGlyph.textColor = this.textColor
val deg = this.degree
if (deg != null) {
deg.textColor = this.textColor
}
}
override fun draw(canvas: Canvas) {
this.radicand.draw(canvas)
degree?.draw(canvas)
canvas.save()
// Make the current position the origin as all the positions of the sub atoms are relative to the origin.
canvas.translate(position.x + radicalShift, position.y)
// Draw the glyph.
radicalGlyph.draw(canvas)
// Draw the VBOX
// for the kern of, we don't need to draw anything.
val heightFromTop = topKern
// draw the horizontal line with the given thickness
val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
strokePaint.setColor(textColor)
strokePaint.strokeWidth = lineThickness
strokePaint.strokeCap = Paint.Cap.ROUND
val x = radicalGlyph.width
val y = ascent - heightFromTop - lineThickness / 2
canvas.drawLine(x, y, x + radicand.width, y, strokePaint)
canvas.restore()
}
}
// MTGlyphDisplay
class MTGlyphDisplay(val glyph: CGGlyph, range: NSRange, val myfont: MTFont) :
MTDisplay(range = range) {
override fun draw(canvas: Canvas) {
super.draw(canvas)
val textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
textPaint.setColor(textColor)
val drawer = MTDrawFreeType(myfont.mathTable)
canvas.save()
canvas.translate(position.x, position.y - this.shiftDown)
canvas.scale(1.0f, -1.0f)
drawer.drawGlyph(canvas, textPaint, glyph.gid, 0.0f, 0.0f)
canvas.restore()
}
override var ascent: Float
get() = super.ascent - this.shiftDown
set(value) {
super.ascent = value
}
override var descent: Float
get() = super.descent + this.shiftDown
set(value) {
super.descent = value
}
}
// MTGlyphConstructionDisplay
class MTGlyphConstructionDisplay(val glyphs: MutableList<Int>, val offsets: MutableList<Float>, val myfont: MTFont) :
MTDisplay() {
init {
assert(glyphs.size == offsets.size)
}
override fun draw(canvas: Canvas) {
val drawer = MTDrawFreeType(myfont.mathTable)
canvas.save()
// Make the current position the origin as all the positions of the sub atoms are relative to the origin.
canvas.translate(position.x, position.y - shiftDown)
// Draw the glyphs.
// positions these are x&y (0,offsets[i])
val textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
textPaint.setColor(textColor)
//textPaint.setTextSize(myfont.fontSize)
//textPaint.setTypeface(myfont.typeface)
for (i in 0 until glyphs.count()) {
//val textstr = myfont.getGlyphString(glyphs[i])
canvas.save()
canvas.translate(0f, offsets[i])
canvas.scale(1.0f, -1.0f)
drawer.drawGlyph(canvas, textPaint, glyphs[i], 0.0f, 0.0f)
//canvas.drawText(textstr, 0.0f, 0.0f, textPaint)
canvas.restore()
}
canvas.restore()
}
override var ascent: Float
get() = super.ascent - this.shiftDown
set(value) {
super.ascent = value
}
override var descent: Float
get() = super.descent + this.shiftDown
set(value) {
super.descent = value
}
}
// MTLargeOpLimitsDisplay
class MTLargeOpLimitsDisplay(val nucleus: MTDisplay, var upperLimit: MTMathListDisplay?, var lowerLimit: MTMathListDisplay?, var limitShift: Float, var extraPadding: Float) :
MTDisplay() {
init {
var maxWidth: Float = nucleus.width
if (upperLimit != null) {
maxWidth = maxOf(maxWidth, upperLimit!!.width)
}
if (lowerLimit != null) {
maxWidth = maxOf(maxWidth, lowerLimit!!.width)
}
this.width = maxWidth
}
override var ascent
get() = if (this.upperLimit != null) {
nucleus.ascent + extraPadding + upperLimit!!.ascent + upperLimitGap + upperLimit!!.descent
} else {
nucleus.ascent
}
set(value) {
}
override var descent: Float
get() = if (this.lowerLimit != null) {
nucleus.descent + extraPadding + lowerLimitGap + lowerLimit!!.descent + lowerLimit!!.ascent
} else {
nucleus.descent
}
set(value) {
}
var lowerLimitGap: Float = 0.0f
set(value) {
field = value
this.updateLowerLimitPosition()
}
var upperLimitGap: Float = 0.0f
set(value) {
field = value
this.updateUpperLimitPosition()
}
override fun positionChanged() {
this.updateLowerLimitPosition()
this.updateUpperLimitPosition()
this.updateNucleusPosition()
}
fun updateLowerLimitPosition() {
val ll = this.lowerLimit
if (ll != null) {
// The position of the lower limit includes the position of the MTLargeOpLimitsDisplay
// This is to make the positioning of the radical consistent with fractions and radicals
// Move the starting point to below the nucleus leaving a gap of _lowerLimitGap and subtract
// the ascent to to get the baseline. Also center and shift it to the left by _limitShift.
ll.position = CGPoint(position.x - limitShift + (this.width - ll.width) / 2,
position.y - nucleus.descent - lowerLimitGap - ll.ascent)
}
}
fun updateUpperLimitPosition() {
val ul = this.upperLimit
if (ul != null) {
// The position of the upper limit includes the position of the MTLargeOpLimitsDisplay
// This is to make the positioning of the radical consistent with fractions and radicals
// Move the starting point to above the nucleus leaving a gap of _upperLimitGap and add
// the descent to to get the baseline. Also center and shift it to the right by _limitShift.
ul.position = CGPoint(position.x + limitShift + (this.width - ul.width) / 2,
position.y + nucleus.ascent + upperLimitGap + ul.descent)
}
}
fun updateNucleusPosition() {
// Center the nucleus
nucleus.position = CGPoint(position.x + (this.width - nucleus.width) / 2, position.y)
}
override fun colorChanged() {
this.nucleus.textColor = this.textColor
val ul = this.upperLimit
if (ul != null) {
ul.textColor = this.textColor
}
val ll = this.lowerLimit
if (ll != null) {
ll.textColor = this.textColor
}
}
override fun draw(canvas: Canvas) {
// Draw the elements.
upperLimit?.draw(canvas)
lowerLimit?.draw(canvas)
nucleus.draw(canvas)
}
}
// MTLineDisplay overline or underline
class MTLineDisplay(val inner: MTMathListDisplay, range: NSRange) :
MTDisplay(range = range) {
// How much the line should be moved up.
var lineShiftUp: Float = 0.0f
var lineThickness: Float = 0.0f
override fun colorChanged() {
this.inner.textColor = this.textColor
}
override fun draw(canvas: Canvas) {
this.inner.draw(canvas)
if (lineThickness != 0f) {
val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG)
strokePaint.setColor(textColor)
strokePaint.strokeWidth = lineThickness
canvas.drawLine(position.x, position.y + lineShiftUp, position.x + width, position.y + lineShiftUp,
strokePaint)
}
}
override fun positionChanged() {
this.updateInnerPosition()
}
fun updateInnerPosition() {
this.inner.position = CGPoint(this.position.x, this.position.y)
}
}
// MTAccentDisplay
class MTAccentDisplay(val accent: MTGlyphDisplay, val accentee: MTMathListDisplay, range: NSRange) :
MTDisplay(range = range) {
init {
accentee.position = CGPoint()
super.range = range.copy()
}
override fun colorChanged() {
this.accentee.textColor = this.textColor
this.accent.textColor = this.textColor
}
override fun positionChanged() {
this.updateAccenteePosition()
}
fun updateAccenteePosition() {
this.accentee.position = CGPoint(this.position.x, this.position.y)
}
override fun draw(canvas: Canvas) {
this.accentee.draw(canvas)
canvas.save()
canvas.translate(position.x, position.y)
this.accent.draw(canvas)
canvas.restore()
}
}
| mit | 8644926d633370a0018aac7848fb3db9 | 30.554427 | 174 | 0.60954 | 4.288166 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/kotlin/Locator.kt | 1 | 6178 | package org.maxur.mserv.frame.kotlin
import org.maxur.mserv.frame.LocatorImpl
import javax.inject.Inject
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
/**
* @author Maxim Yunusov
* @version 1.0
* @since <pre>26.08.2017</pre>
*/
class Locator @Inject constructor(val impl: LocatorImpl) : LocatorImpl by impl {
companion object {
/**
* Current Locator's property.
*/
val current get() = Locator(LocatorImpl.holder.get())
/**
* Gets the best service from this locator that implements
* this contract or has this implementation and has the given name (Kotlin edition).
* <p>
* @param contractOrImpl May not be null, and is the contract
* or concrete implementation to get the best instance of
* @param name Is the name of the implementation to be returned
* @return An instance of the contract or impl. May return
* null if there is no provider that provides the given
* implementation or contract
*/
fun <T : Any> bean(contractOrImpl: KClass<T>, name: String? = null): T? = current.service(contractOrImpl, name)
@Suppress("UNCHECKED_CAST")
/**
* Gets the best service from this locator that satisfied to function's parameter.
* <p>
* @param parameter The function's parameter
* @return An instance of the contract or impl. May return
* null if there is no provider that provides the given
* implementation or contract
*/
fun <T : Any> bean(parameter: KParameter): T? = current.service(parameter.type.classifier as KClass<T>)
/**
* Gets all services from this locator that implement this contract or have this
* implementation (Kotlin edition).
* <p>
* @param contractOrImpl May not be null, and is the contract
* or concrete implementation to get the best instance of
* @return A list of services implementing this contract
* or concrete implementation. May return an empty list
*/
fun <T : Any> beans(contractOrImpl: KClass<T>): List<T> = current.services(contractOrImpl)
/**
* This method will shutdown every service associated with this Locator.
* Those services that have a preDestroy shall have their preDestroy called
*/
fun stop() = current.shutdown()
}
/**
* Gets the best service from this locator that implements
* this contract or has this implementation and has the given name (Kotlin edition).
* <p>
* @param contractOrImpl May not be null, and is the contract
* or concrete implementation to get the best instance of
* @param name Is the name of the implementation to be returned
* @return An instance of the contract or impl.
* @throw IllegalStateException if there is no provider that
* provides the given implementation or contract
*/
fun <T : Any> locate(contractOrImpl: KClass<T>, name: String?): T = locate(contractOrImpl.java, name)
/**
* Gets the best service from this locator that satisfied to function's parameter.
* <p>
* @param parameter The function's parameter
* @return An instance of the contract or impl. May return
* null if there is no provider that provides the given
* implementation or contract
*/
@Suppress("UNCHECKED_CAST")
fun <T : Any> service(parameter: KParameter): T? = service(parameter.type.classifier as KClass<T>)
/**
* Gets the best service from this locator that implements
* this contract or has this implementation and has the given name (Java edition).
* <p>
* @param contractOrImpl May not be null, and is the contract
* or concrete implementation to get the best instance of
* @param name Is the name of the implementation to be returned
* @return An instance of the contract or impl. May return
* null if there is no provider that provides the given
* implementation or contract
*/
fun <T : Any> service(contractOrImpl: KClass<T>, name: String? = null): T? = service(contractOrImpl.java, name)
/**
* Gets all services from this locator that implement this contract or have this
* implementation (Java edition).
* <p>
* @param contractOrImpl May not be null, and is the contract
* or concrete implementation to get the best instance of
* @return A list of services implementing this contract
* or concrete implementation. May return an empty list
*/
fun <T : Any> services(contractOrImpl: KClass<T>): List<T> = services(contractOrImpl.java)
/**
* Gets all services names from this locator that implement this contract or have this
* implementation (Kotlin edition).
* <p>
* @param contractOrImpl May not be null, and is the contract
* or concrete implementation to get the best instance of
* @return A list of services names implementing this contract
* or concrete implementation. May return an empty list
*/
fun <T : Any> names(contractOrImpl: KClass<T>): List<String> = names(contractOrImpl.java)
/**
* Gets property value by key name.
* <p>
* @param key The key name
* @return The property value as String or nul
*/
fun property(key: String): String? = property(key, String::class)
/**
* Gets property value by key name (Kotlin edition).
* <p>
* @param key The key name
* @param clazz The required type.
* @return The property value of required type or nul
*/
fun <T : Any> property(key: String, clazz: KClass<T>): T? = property(key, clazz.java)
/** {@inheritDoc} */
override fun toString(): String = name
/** {@inheritDoc} */
override fun equals(other: Any?): Boolean = other is Locator && other.name.equals(name)
/** {@inheritDoc} */
override fun hashCode(): Int {
return name.hashCode()
}
inline fun <reified R : Any> service(name: String? = null): R? {
return service(R::class, name) as R
}
} | apache-2.0 | 76b3bede93e2c7e8fb9de9404ac29eaf | 39.123377 | 119 | 0.648916 | 4.579689 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/source/remote/ZhihuDailyContentRemoteDataSource.kt | 1 | 3793 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data.source.remote
import android.support.annotation.VisibleForTesting
import com.marktony.zhihudaily.BuildConfig
import com.marktony.zhihudaily.data.ZhihuDailyContent
import com.marktony.zhihudaily.data.source.RemoteDataNotFoundException
import com.marktony.zhihudaily.data.source.Result
import com.marktony.zhihudaily.data.source.datasource.ZhihuDailyContentDataSource
import com.marktony.zhihudaily.retrofit.RetrofitService
import com.marktony.zhihudaily.util.AppExecutors
import kotlinx.coroutines.experimental.withContext
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by lizhaotailang on 2017/5/26.
*
* Implementation of the [ZhihuDailyContent] data source that accesses network.
*/
class ZhihuDailyContentRemoteDataSource private constructor(
private val mAppExecutors: AppExecutors
) : ZhihuDailyContentDataSource {
private val mZhihuDailyService: RetrofitService.ZhihuDailyService by lazy {
val httpClientBuilder = OkHttpClient.Builder()
if (BuildConfig.DEBUG) {
httpClientBuilder.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
}
httpClientBuilder.retryOnConnectionFailure(true)
val retrofit = Retrofit.Builder()
.baseUrl(RetrofitService.ZHIHU_DAILY_BASE)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClientBuilder.build())
.build()
retrofit.create(RetrofitService.ZhihuDailyService::class.java)
}
companion object {
private var INSTANCE: ZhihuDailyContentRemoteDataSource? = null
@JvmStatic
fun getInstance(appExecutors: AppExecutors): ZhihuDailyContentRemoteDataSource {
if (INSTANCE == null) {
synchronized(ZhihuDailyContentRemoteDataSource::javaClass) {
INSTANCE = ZhihuDailyContentRemoteDataSource(appExecutors)
}
}
return INSTANCE!!
}
@VisibleForTesting
fun clearInstance() {
INSTANCE = null
}
}
override suspend fun getZhihuDailyContent(id: Int): Result<ZhihuDailyContent> = withContext(mAppExecutors.ioContext) {
try {
val response = mZhihuDailyService.getZhihuContent(id).execute()
if (response.isSuccessful) {
response.body()?.let {
Result.Success(it)
} ?: run {
Result.Error(RemoteDataNotFoundException())
}
} else {
Result.Error(RemoteDataNotFoundException())
}
} catch (e: Exception) {
Result.Error(RemoteDataNotFoundException())
}
}
override suspend fun saveContent(content: ZhihuDailyContent) {
// Not required because the [com.marktony.zhihudaily.data.source.repository.ZhihuDailyNewsRepository] handles the logic of refreshing the
// news from all the available data sources.
}
}
| apache-2.0 | 71c9a6c8a822297bd02bafe6282121fe | 34.783019 | 145 | 0.691801 | 5.33474 | false | false | false | false |
dscoppelletti/spaceship | lib/src/main/kotlin/it/scoppelletti/spaceship/app/AppExt.kt | 1 | 3535 | /*
* Copyright (C) 2013-2021 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier",
"unused")
package it.scoppelletti.spaceship.app
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.annotation.UiThread
import it.scoppelletti.spaceship.inject.AppComponent
import it.scoppelletti.spaceship.inject.AppComponentProvider
import it.scoppelletti.spaceship.inject.StdlibComponent
import it.scoppelletti.spaceship.inject.StdlibComponentProvider
/**
* Application model extensions.
*
* @since 1.0.0
*/
public object AppExt {
/**
* Tag of `AlertDialogFragment` fragment.
*
* @see it.scoppelletti.spaceship.app.AlertDialogFragment
*/
public const val TAG_ALERTDIALOG = "it.scoppelletti.spaceship.1"
/**
* Tag of `ExceptionDialogFragment` fragment.
*
* @see it.scoppelletti.spaceship.app.ExceptionDialogFragment
*/
public const val TAG_EXCEPTIONDIALOG = "it.scoppelletti.spaceship.2"
/**
* Tag of `BottomSheetDialogFragmentEx` fragment.
*
* @see it.scoppelletti.spaceship.app.BottomSheetDialogFragmentEx
*/
public const val TAG_BOTTOMSHEETDIALOG = "it.scoppelletti.spaceship.3"
/**
* Property containing an item.
*/
public const val PROP_ITEM = "it.scoppelletti.spaceship.1"
/**
* Property containing a message.
*/
public const val PROP_MESSAGE = "it.scoppelletti.spaceship.2"
/**
* Property containing a result.
*/
public const val PROP_RESULT = "it.scoppelletti.spaceship.3"
}
/**
* Returns the `UIComponent` component.
*
* @receiver Activity.
* @return The object.
* @since 1.0.0
*/
public fun Activity.appComponent(): AppComponent =
(this.application as AppComponentProvider).appComponent()
/**
* Returns the `StdlibComponent` component.
*
* @receiver Activity.
* @return The object.
* @since 1.0.0
*/
public fun Activity.stdlibComponent(): StdlibComponent =
(this.application as StdlibComponentProvider).stdlibComponent()
/**
* Tries to finish an activity.
*
* @receiver Activity.
* @return Returns `true` if the finish process has been started, `false` if
* this activity was already finishing.
* @since 1.0.0
*/
@UiThread
public fun Activity.tryFinish(): Boolean {
if (this.isFinishing) {
return false
}
this.finish()
return true
}
/**
* Hides the soft keyboard.
*
* @receiver Activity.
* @since 1.0.0
*/
@UiThread
public fun Activity.hideSoftKeyboard() {
val view: View?
val inputMgr: InputMethodManager
view = this.currentFocus
if (view != null) {
inputMgr = this.getSystemService(Context.INPUT_METHOD_SERVICE) as
InputMethodManager
inputMgr.hideSoftInputFromWindow(view.windowToken, 0)
}
}
| apache-2.0 | d0a11b0105dda0e6e0205cff1742f8a1 | 25.984733 | 78 | 0.698727 | 4.139344 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/test/java/jp/hazuki/yuzubrowser/legacy/action/item/VibrationSingleActionTest.kt | 1 | 1604 | /*
* 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.legacy.action.item
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import okio.buffer
import okio.sink
import okio.source
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class VibrationSingleActionTest {
@Test
fun testDecodeEncode() {
val json = """{"0":500}"""
val reader = JsonReader.of(ByteArrayInputStream(json.toByteArray()).source().buffer())
val action = VibrationSingleAction(0, reader)
assertThat(action.time).isEqualTo(500)
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT)
val os = ByteArrayOutputStream()
val writer = JsonWriter.of(os.sink().buffer())
writer.beginArray()
action.writeIdAndData(writer)
writer.endArray()
writer.flush()
assertThat(os.toString()).isEqualTo("""[0,{"0":500}]""")
}
} | apache-2.0 | 3add8ed3be44232375942a02d11090d0 | 30.470588 | 94 | 0.714464 | 4.32345 | false | true | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/service/BootReceiver.kt | 1 | 2254 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.text.format.DateUtils
import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.android.AndroidEntryPoint
import net.jami.services.PreferencesService
import javax.inject.Inject
@AndroidEntryPoint
class BootReceiver : BroadcastReceiver() {
@Inject
lateinit var mPreferencesService: PreferencesService
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action ?: return
if (Intent.ACTION_BOOT_COMPLETED == action || Intent.ACTION_REBOOT == action || Intent.ACTION_MY_PACKAGE_REPLACED == action) {
try {
if (mPreferencesService.settings.runOnStartup) {
try {
ContextCompat.startForegroundService(context, Intent(SyncService.ACTION_START)
.setClass(context, SyncService::class.java)
.putExtra(SyncService.EXTRA_TIMEOUT, 5 * DateUtils.SECOND_IN_MILLIS))
} catch (e: IllegalStateException) {
Log.e(TAG, "Error starting service", e)
}
}
} catch (e: Exception) {
Log.e(TAG, "Can't start on boot", e)
}
}
}
companion object {
private val TAG = BootReceiver::class.simpleName!!
}
} | gpl-3.0 | dbeefb6251c27122a412d01d7e0858a5 | 38.561404 | 134 | 0.661047 | 4.572008 | false | false | false | false |
tmarsteel/kotlin-prolog | core/src/main/kotlin/com/github/prologdb/runtime/RandomVariableScope.kt | 1 | 3316 | package com.github.prologdb.runtime
import com.github.prologdb.runtime.term.CompoundTerm
import com.github.prologdb.runtime.term.RandomVariable
import com.github.prologdb.runtime.term.Term
import com.github.prologdb.runtime.term.Variable
import java.lang.ref.WeakReference
import kotlin.math.max
import kotlin.math.min
/**
* Handles the remapping of user-specified variables to random variables (that avoids name collisions).
*/
class RandomVariableScope {
/**
* This is essentially the most simple PRNG possible: this int will just be incremented until it hits Long.MAX_VALUE
* and will then throw an exception. That number is then used to generate variable names.
*/
private var counter: Long = 0
/**
* Replaces all the variables in the given term with random instances; the mapping gets stored
* in the given map.
*/
fun withRandomVariables(term: Term, mapping: VariableMapping): Term {
return term.substituteVariables { originalVariable ->
if (originalVariable == Variable.ANONYMOUS) {
createNewRandomVariable()
}
else {
if (!mapping.hasOriginal(originalVariable)) {
val randomVariable = createNewRandomVariable()
mapping.storeSubstitution(originalVariable, randomVariable)
}
mapping.getSubstitution(originalVariable)!!
}
}
}
fun withRandomVariables(term: CompoundTerm, mapping: VariableMapping) = withRandomVariables(term as Term, mapping) as CompoundTerm
fun withRandomVariables(terms: Array<out Term>, mapping: VariableMapping): Array<out Term> = Array(terms.size) { index ->
this.withRandomVariables(terms[index], mapping)
}
fun createNewRandomVariable(): Variable {
val localCounter = ++counter
if (localCounter == Long.MAX_VALUE) {
throw PrologInternalError("Out of random variables (reached $localCounter random variables in one proof search).")
}
if (localCounter >= Integer.MAX_VALUE.toLong()) {
return RandomVariable(localCounter)
}
val localCounterInt = localCounter.toInt()
val localPool = pool
if (localCounterInt < localPool.size) {
var variable = localPool[localCounterInt]?.get()
if (variable == null) {
variable = RandomVariable(localCounter)
localPool[localCounterInt] = WeakReference(variable)
}
return variable
}
val newPool = localPool.copyOf(
newSize = min(
max(
localCounter + 1L, localPool.size.toLong() * 2L
),
Integer.MAX_VALUE.toLong()
).toInt()
)
val variable = RandomVariable(localCounter)
newPool[localCounterInt] = WeakReference(variable)
pool = newPool
return variable
}
companion object {
/**
* Shared cache for random variables. The index corresponds to [RandomVariableScope.counter]
*/
@JvmStatic
@Volatile
private var pool: Array<WeakReference<RandomVariable>?> = Array(100) { counter -> WeakReference(RandomVariable(counter.toLong())) }
}
}
| mit | 23389e311ae2011ebdbd0df327fbed0b | 35.43956 | 139 | 0.636309 | 5.054878 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/games/views/GameFooterView.kt | 1 | 6060 | package ca.josephroque.bowlingcompanion.games.views
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.matchplay.MatchPlayResult
import kotlinx.android.synthetic.main.view_game_footer.view.pins_divider as pinsDivider
import kotlinx.android.synthetic.main.view_game_footer.view.iv_clear_pins as clearPinsIcon
import kotlinx.android.synthetic.main.view_game_footer.view.iv_foul as foulIcon
import kotlinx.android.synthetic.main.view_game_footer.view.iv_lock as lockIcon
import kotlinx.android.synthetic.main.view_game_footer.view.iv_match_play as matchPlayIcon
import kotlinx.android.synthetic.main.view_game_footer.view.iv_fullscreen as fullscreenIcon
/**
* Copyright (C) 2018 Joseph Roque
*
* Footer view to display game and frame controls at the foot of the game details.
*/
class GameFooterView : ConstraintLayout {
companion object {
@Suppress("unused")
private const val TAG = "GameFooterView"
private const val SUPER_STATE = "${TAG}_super_state"
private const val STATE_CURRENT_BALL = "${TAG}_current_ball"
private const val STATE_MATCH_PLAY_RESULT = "${TAG}_match_play_result"
private const val STATE_LOCK = "${TAG}_lock"
private const val STATE_FOUL = "${TAG}_foul"
private const val STATE_MANUAL_SCORE = "${TAG}_manual"
private const val STATE_FULLSCREEN = "${TAG}_fullscreen"
enum class Clear {
Strike, Spare, Fifteen;
val image: Int
get() = when (this) {
Strike -> R.drawable.ic_clear_pins_strike
Spare -> R.drawable.ic_clear_pins_spare
Fifteen -> R.drawable.ic_clear_pins_fifteen
}
companion object {
private val map = Clear.values().associateBy(Clear::ordinal)
fun fromInt(type: Int) = map[type]
}
}
}
var delegate: GameFooterInteractionDelegate? = null
var isFullscreen: Boolean = false
set(value) {
field = value
fullscreenIcon.setImageResource(if (value) R.drawable.ic_fullscreen_exit else R.drawable.ic_fullscreen)
}
var clear: Clear = Clear.Strike
set(value) {
field = value
clearPinsIcon.setImageResource(value.image)
}
var matchPlayResult: MatchPlayResult = MatchPlayResult.NONE
set(value) {
field = value
matchPlayIcon.setImageResource(value.getIcon())
}
var isGameLocked: Boolean = false
set(value) {
field = value
lockIcon.setImageResource(if (value) R.drawable.ic_lock else R.drawable.ic_lock_open)
}
var isFoulActive: Boolean = false
set(value) {
field = value
foulIcon.setImageResource(if (value) R.drawable.ic_foul_active else R.drawable.ic_foul_inactive)
}
var isManualScoreSet: Boolean = false
set(value) {
field = value
val visible = if (value) View.GONE else View.VISIBLE
clearPinsIcon.visibility = visible
foulIcon.visibility = visible
pinsDivider.visibility = visible
}
private val onClickListener = View.OnClickListener {
when (it.id) {
R.id.iv_fullscreen -> delegate?.onFullscreenToggle()
R.id.iv_clear_pins -> delegate?.onClearPins()
R.id.iv_foul -> delegate?.onFoulToggle()
R.id.iv_lock -> delegate?.onLockToggle()
R.id.iv_match_play -> delegate?.onMatchPlaySettings()
}
}
// MARK: Constructors
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
LayoutInflater.from(context).inflate(R.layout.view_game_footer, this, true)
fullscreenIcon.setOnClickListener(onClickListener)
clearPinsIcon.setOnClickListener(onClickListener)
foulIcon.setOnClickListener(onClickListener)
lockIcon.setOnClickListener(onClickListener)
matchPlayIcon.setOnClickListener(onClickListener)
}
// MARK: Lifecycle functions
override fun onSaveInstanceState(): Parcelable {
return Bundle().apply {
putParcelable(SUPER_STATE, super.onSaveInstanceState())
putInt(STATE_CURRENT_BALL, clear.ordinal)
putInt(STATE_MATCH_PLAY_RESULT, matchPlayResult.ordinal)
putBoolean(STATE_LOCK, isGameLocked)
putBoolean(STATE_FOUL, isFoulActive)
putBoolean(STATE_MANUAL_SCORE, isManualScoreSet)
putBoolean(STATE_FULLSCREEN, isFullscreen)
}
}
override fun onRestoreInstanceState(state: Parcelable?) {
var superState: Parcelable? = null
if (state is Bundle) {
clear = Clear.fromInt(state.getInt(STATE_CURRENT_BALL))!!
matchPlayResult = MatchPlayResult.fromInt(state.getInt(STATE_MATCH_PLAY_RESULT))!!
isGameLocked = state.getBoolean(STATE_LOCK)
isFoulActive = state.getBoolean(STATE_FOUL)
isManualScoreSet = state.getBoolean(STATE_MANUAL_SCORE)
isFullscreen = state.getBoolean(STATE_FULLSCREEN)
superState = state.getParcelable(SUPER_STATE)
}
super.onRestoreInstanceState(superState)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
delegate = null
}
// MARK: GameFooterInteractionDelegate
interface GameFooterInteractionDelegate {
fun onLockToggle()
fun onClearPins()
fun onFoulToggle()
fun onMatchPlaySettings()
fun onFullscreenToggle()
}
}
| mit | f84e7bac1602668edf8354d57d022fb0 | 36.177914 | 115 | 0.657426 | 4.505576 | false | false | false | false |
industrial-data-space/trusted-connector | camel-multipart-processor/src/main/kotlin/de/fhg/aisec/ids/camel/multipart/MultiPartStringParser.kt | 1 | 3338 | /*-
* ========================LICENSE_START=================================
* camel-multipart-processor
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.camel.multipart
import org.apache.commons.fileupload.FileUpload
import org.apache.commons.fileupload.UploadContext
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
class MultiPartStringParser internal constructor(private val multipartInput: InputStream) :
UploadContext {
private var boundary: String? = null
var header: String? = null
var payload: InputStream? = null
var payloadContentType: String? = null
override fun getCharacterEncoding(): String = StandardCharsets.UTF_8.name()
override fun getContentLength() = -1
override fun getContentType() = "multipart/form-data, boundary=$boundary"
override fun getInputStream() = multipartInput
override fun contentLength() = -1L
companion object {
private val LOG = LoggerFactory.getLogger(MultiPartStringParser::class.java)
}
init {
multipartInput.mark(10240)
BufferedReader(InputStreamReader(multipartInput, StandardCharsets.UTF_8)).use { reader ->
val boundaryLine =
reader.readLine()
?: throw IOException(
"Message body appears to be empty, expected multipart boundary."
)
boundary = boundaryLine.substring(2).trim { it <= ' ' }
multipartInput.reset()
for (i in FileUpload(DiskFileItemFactory()).parseRequest(this)) {
val fieldName = i.fieldName
if (LOG.isTraceEnabled) {
LOG.trace("Found multipart field with name \"{}\"", fieldName)
}
if (MultiPartConstants.MULTIPART_HEADER == fieldName) {
header = i.string
if (LOG.isDebugEnabled) {
LOG.debug("Found header:\n{}", header)
}
} else if (MultiPartConstants.MULTIPART_PAYLOAD == fieldName) {
payload = i.inputStream
payloadContentType = i.contentType
if (LOG.isDebugEnabled) {
LOG.debug("Found body with Content-Type \"{}\"", payloadContentType)
}
} else {
throw IOException("Unknown multipart field name detected: $fieldName")
}
}
}
}
}
| apache-2.0 | 089fb842263a2e176e9a4e6128ef055d | 38.270588 | 97 | 0.610545 | 5.06525 | false | false | false | false |
roamingthings/dev-workbench | dev-workbench-backend/src/main/kotlin/de/roamingthings/devworkbench/persistence/UpdateField.kt | 1 | 444 | package de.roamingthings.devworkbench.persistence
open class UpdateField<T>(val value: T? = null, val ignored: Boolean = false) {
fun get(): T = value ?: throw IllegalStateException("value cannot be null.")
fun getOrDefault(defaultValue: T): T = if (ignored) defaultValue else get()
companion object {
fun <T> ignore() = UpdateField<T>(ignored = true)
fun <T> of(value: T) = UpdateField<T>(value = value)
}
} | apache-2.0 | 7c0baa90b5ab7728e91ff4dc0c892aa8 | 33.230769 | 80 | 0.664414 | 3.894737 | false | false | false | false |
shchurov/gitter-kotlin-client | app/src/main/kotlin/com/github/shchurov/gitterclient/data/database/implementation/DatabaseImpl.kt | 1 | 2136 | package com.github.shchurov.gitterclient.data.database.implementation
import com.github.shchurov.gitterclient.data.database.Database
import com.github.shchurov.gitterclient.data.database.implementation.realm_models.RoomRealm
import com.github.shchurov.gitterclient.domain.models.Room
import io.realm.Realm
class DatabaseImpl(initializer: RealmInitializer) : Database {
private val converter = DatabaseConverter()
init {
initializer.initRealm()
}
override fun getRooms(): MutableList<Room> {
val realm = getRealmInstance()
val realmRooms = realm.allObjects(RoomRealm::class.java)
val rooms: MutableList<Room> = mutableListOf()
realmRooms.mapTo(rooms) { converter.convertRealmToRoom(it) }
realm.close()
return rooms
}
override fun insertRooms(rooms: List<Room>) {
val realmRooms = rooms.map { converter.convertRoomToRealm(it) }
executeTransaction { realm -> realm.copyToRealm(realmRooms) }
}
override fun updateRoomLastAccessTime(roomId: String, timestamp: Long) {
executeTransaction { realm ->
getRoom(roomId, realm).lastAccessTimestamp = timestamp
}
}
private fun getRoom(roomId: String, realm: Realm) =
realm.where(RoomRealm::class.java)
.equalTo(RoomRealm.FIELD_ID, roomId)
.findFirst()
override fun decrementRoomUnreadItems(roomId: String) {
executeTransaction { realm ->
val realmRoom = getRoom(roomId, realm)
realmRoom.unreadItems--
}
}
override fun clearRooms() {
executeTransaction { realm -> realm.clear(RoomRealm::class.java) }
}
private fun executeTransaction(transaction: (Realm) -> Unit) {
val realm = getRealmInstance()
realm.beginTransaction()
try {
transaction(realm)
realm.commitTransaction()
} catch (e: Exception) {
e.printStackTrace()
realm.cancelTransaction()
}
realm.close()
}
private fun getRealmInstance() = Realm.getDefaultInstance()
} | apache-2.0 | 1d47d8bc492487ebfd2025fa28241f6e | 30.895522 | 91 | 0.65309 | 4.757238 | false | false | false | false |
FWDekker/intellij-randomness | src/test/kotlin/com/fwdekker/randomness/template/TemplateListEditorTest.kt | 1 | 9776 | package com.fwdekker.randomness.template
import com.fwdekker.randomness.DummyScheme
import com.fwdekker.randomness.Scheme
import com.fwdekker.randomness.SettingsState
import com.fwdekker.randomness.clickActionButton
import com.fwdekker.randomness.datetime.DateTimeScheme
import com.fwdekker.randomness.decimal.DecimalScheme
import com.fwdekker.randomness.integer.IntegerScheme
import com.fwdekker.randomness.string.StringScheme
import com.fwdekker.randomness.uuid.UuidScheme
import com.fwdekker.randomness.word.WordScheme
import com.intellij.testFramework.fixtures.IdeaTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import com.intellij.ui.JBSplitter
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.assertj.swing.edt.FailOnThreadViolationRepaintManager
import org.assertj.swing.edt.GuiActionRunner
import org.assertj.swing.fixture.AbstractComponentFixture
import org.assertj.swing.fixture.Containers
import org.assertj.swing.fixture.FrameFixture
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
/**
* GUI tests for [TemplateListEditor].
*/
object TemplateListEditorTest : Spek({
lateinit var ideaFixture: IdeaTestFixture
lateinit var frame: FrameFixture
lateinit var state: SettingsState
lateinit var editor: TemplateListEditor
beforeGroup {
FailOnThreadViolationRepaintManager.install()
TemplateListEditor.CREATE_SPLITTER =
{ vertical, proportionKey, defaultProportion -> JBSplitter(vertical, proportionKey, defaultProportion) }
}
beforeEachTest {
ideaFixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture()
ideaFixture.setUp()
state = SettingsState(
TemplateList(
listOf(
Template("Whip", listOf(IntegerScheme(), StringScheme())),
Template("Ability", listOf(DecimalScheme(), WordScheme()))
)
)
)
state.templateList.applySettingsState(state)
editor = GuiActionRunner.execute<TemplateListEditor> { TemplateListEditor(state) }
frame = Containers.showInFrame(editor.rootComponent)
}
afterEachTest {
frame.cleanUp()
GuiActionRunner.execute { editor.dispose() }
ideaFixture.tearDown()
}
describe("loadState") {
it("loads the list's schemes") {
assertThat(GuiActionRunner.execute<Int> { frame.tree().target().rowCount }).isEqualTo(6)
}
}
describe("readState") {
it("returns the original state if no editor changes are made") {
assertThat(editor.readState()).isEqualTo(editor.originalState)
}
it("returns the editor's state") {
GuiActionRunner.execute {
frame.tree().target().selectionRows = intArrayOf(0)
frame.clickActionButton("Remove")
}
val readScheme = editor.readState()
assertThat(readScheme.templateList.templates).hasSize(1)
}
it("returns the loaded state if no editor changes are made") {
GuiActionRunner.execute {
frame.tree().target().selectionRows = intArrayOf(0)
frame.clickActionButton("Remove")
}
assertThat(editor.isModified()).isTrue()
GuiActionRunner.execute { editor.loadState(editor.readState()) }
assertThat(editor.isModified()).isFalse()
assertThat(editor.readState()).isEqualTo(editor.originalState)
}
it("returns different instances of the settings") {
val readState = editor.readState()
assertThat(readState).isNotSameAs(state)
assertThat(readState.templateList).isNotSameAs(state.templateList)
}
it("retains the list's UUIDs") {
val readState = editor.readState()
assertThat(readState.uuid).isEqualTo(state.uuid)
assertThat(readState.templateList.uuid).isEqualTo(state.templateList.uuid)
assertThat(readState.templateList.templates.map { it.uuid })
.containsExactlyElementsOf(state.templateList.templates.map { it.uuid })
}
}
describe("reset") {
it("undoes changes to the initial selection") {
GuiActionRunner.execute {
frame.tree().target().setSelectionRow(1)
frame.spinner("minValue").target().value = 7
}
GuiActionRunner.execute { editor.reset() }
assertThat(frame.spinner("minValue").target().value).isEqualTo(0L)
}
it("retains the selection if `queueSelection` is null") {
editor.queueSelection = null
GuiActionRunner.execute { editor.reset() }
assertThat(frame.tree().target().selectionRows).containsExactly(0)
}
it("selects the indicated template after reset") {
editor.queueSelection = state.templateList.templates[1].uuid
GuiActionRunner.execute { editor.reset() }
assertThat(frame.tree().target().selectionRows).containsExactly(3)
}
it("does nothing if the indicated template could not be found") {
editor.queueSelection = "231ee9da-8f72-4535-b770-0119fdf68f70"
GuiActionRunner.execute { editor.reset() }
assertThat(frame.tree().target().selectionRows).containsExactly(0)
}
}
describe("addChangeListener") {
it("invokes the listener if the model is changed") {
GuiActionRunner.execute { frame.tree().target().setSelectionRow(1) }
var invoked = 0
GuiActionRunner.execute { editor.addChangeListener { invoked++ } }
GuiActionRunner.execute { frame.spinner("minValue").target().value = 321 }
assertThat(invoked).isNotZero()
}
it("invokes the listener if a scheme is removed") {
GuiActionRunner.execute { frame.tree().target().selectionRows = intArrayOf(0) }
var invoked = 0
GuiActionRunner.execute { editor.addChangeListener { invoked++ } }
GuiActionRunner.execute { frame.clickActionButton("Remove") }
assertThat(invoked).isNotZero()
}
it("invokes the listener if the selection is changed") {
GuiActionRunner.execute { frame.tree().target().clearSelection() }
var invoked = 0
GuiActionRunner.execute { editor.addChangeListener { invoked++ } }
GuiActionRunner.execute { frame.tree().target().setSelectionRow(2) }
assertThat(invoked).isNotZero()
}
}
describe("scheme editor") {
it("loads the selected scheme's editor") {
GuiActionRunner.execute { frame.tree().target().setSelectionRow(2) }
frame.textBox("pattern").requireVisible()
}
it("retains changes made in a scheme editor") {
GuiActionRunner.execute {
frame.tree().target().setSelectionRow(2)
frame.textBox("pattern").target().text = "strange"
}
GuiActionRunner.execute {
frame.tree().target().setSelectionRow(1)
frame.tree().target().setSelectionRow(2)
}
frame.textBox("pattern").requireText("strange")
}
describe("editor creation") {
data class Param(
val name: String,
val scheme: Scheme,
val matcher: (FrameFixture) -> AbstractComponentFixture<*, *, *>
)
listOf(
Param("integer", IntegerScheme()) { it.spinner("minValue") },
Param("decimal", DecimalScheme()) { it.spinner("minValue") },
Param("string", StringScheme()) { it.textBox("pattern") },
Param("UUID", UuidScheme()) { it.radioButton("type1") },
Param("word", WordScheme()) { it.radioButton("capitalizationRetain") },
Param("date-time", DateTimeScheme()) { it.textBox("minDateTime") },
Param("template reference", TemplateReference()) { it.list() }
).forEach { (name, scheme, matcher) ->
it("loads an editor for ${name}s") {
state.templateList.templates = listOf(Template(schemes = listOf(scheme)))
state.templateList.applySettingsState(state)
GuiActionRunner.execute {
editor.reset()
frame.tree().target().setSelectionRow(1)
}
matcher(frame).requireVisible()
}
}
it("loads an editor for templates") {
state.templateList.templates = listOf(Template(schemes = emptyList()))
state.templateList.applySettingsState(state)
GuiActionRunner.execute { editor.reset() }
frame.textBox("templateName").requireVisible()
}
it("throws an error for unknown scheme types") {
state.templateList.templates = listOf(Template(schemes = listOf(DummyScheme.from("grain"))))
state.templateList.applySettingsState(state)
assertThatThrownBy {
GuiActionRunner.execute {
editor.reset()
frame.tree().target().setSelectionRow(1)
}
}
.isInstanceOf(IllegalStateException::class.java)
.hasMessage("Unknown scheme type 'com.fwdekker.randomness.DummyScheme'.")
}
}
}
})
| mit | 9c3f89de61693d33c0b4974088ebef62 | 35.614232 | 116 | 0.614669 | 5.25309 | false | false | false | false |
FWDekker/intellij-randomness | src/test/kotlin/com/fwdekker/randomness/integer/IntegerSchemeEditorTest.kt | 1 | 8436 | package com.fwdekker.randomness.integer
import com.fwdekker.randomness.CapitalizationMode
import com.fwdekker.randomness.array.ArrayDecorator
import org.assertj.core.api.Assertions.assertThat
import org.assertj.swing.edt.FailOnThreadViolationRepaintManager
import org.assertj.swing.edt.GuiActionRunner
import org.assertj.swing.fixture.Containers.showInFrame
import org.assertj.swing.fixture.FrameFixture
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
/**
* GUI tests for [IntegerSchemeEditor].
*/
object IntegerSchemeEditorTest : Spek({
lateinit var scheme: IntegerScheme
lateinit var editor: IntegerSchemeEditor
lateinit var frame: FrameFixture
beforeGroup {
FailOnThreadViolationRepaintManager.install()
}
beforeEachTest {
scheme = IntegerScheme()
editor = GuiActionRunner.execute<IntegerSchemeEditor> { IntegerSchemeEditor(scheme) }
frame = showInFrame(editor.rootComponent)
}
afterEachTest {
frame.cleanUp()
}
describe("input handling") {
describe("base") {
it("truncates decimals in the base") {
GuiActionRunner.execute { frame.spinner("base").target().value = 22.62f }
frame.spinner("base").requireValue(22)
}
}
describe("minimum value") {
it("truncates decimals in the minimum value") {
GuiActionRunner.execute { frame.spinner("minValue").target().value = 285.21f }
frame.spinner("minValue").requireValue(285L)
}
}
describe("maximum value") {
it("truncates decimals in the maximum value") {
GuiActionRunner.execute { frame.spinner("maxValue").target().value = 490.34f }
frame.spinner("maxValue").requireValue(490L)
}
}
}
describe("loadState") {
it("loads the scheme's minimum value") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(minValue = 145L, maxValue = 341L)) }
frame.spinner("minValue").requireValue(145L)
}
it("loads the scheme's maximum value") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(minValue = 337L, maxValue = 614L)) }
frame.spinner("maxValue").requireValue(614L)
}
it("loads the scheme's base value") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(base = 25)) }
frame.spinner("base").requireValue(25)
}
it("loads the scheme's grouping separator") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(groupingSeparator = "_")) }
frame.radioButton("groupingSeparatorNone").requireSelected(false)
frame.radioButton("groupingSeparatorPeriod").requireSelected(false)
frame.radioButton("groupingSeparatorComma").requireSelected(false)
frame.radioButton("groupingSeparatorUnderscore").requireSelected(true)
frame.panel("groupingSeparatorCustom").radioButton().requireSelected(false)
}
it("loads the scheme's custom grouping separator") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(customGroupingSeparator = "r")) }
frame.panel("groupingSeparatorCustom").textBox().requireText("r")
}
it("selects the scheme's custom grouping separator") {
GuiActionRunner.execute {
editor.loadState(IntegerScheme(groupingSeparator = "a", customGroupingSeparator = "a"))
}
frame.panel("groupingSeparatorCustom").radioButton().requireSelected()
}
it("loads the scheme's capitalization mode") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(capitalization = CapitalizationMode.LOWER)) }
frame.radioButton("capitalizationLower").requireSelected(true)
frame.radioButton("capitalizationUpper").requireSelected(false)
}
it("loads the scheme's prefix") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(prefix = "wage")) }
frame.textBox("prefix").requireText("wage")
}
it("loads the scheme's suffix") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(suffix = "fat")) }
frame.textBox("suffix").requireText("fat")
}
}
describe("readState") {
describe("defaults") {
it("returns default brackets if no brackets are selected") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(groupingSeparator = "unsupported")) }
assertThat(editor.readState().groupingSeparator).isEqualTo(IntegerScheme.DEFAULT_GROUPING_SEPARATOR)
}
it("returns default brackets if no brackets are selected") {
GuiActionRunner.execute { editor.loadState(IntegerScheme(capitalization = CapitalizationMode.DUMMY)) }
assertThat(editor.readState().capitalization).isEqualTo(IntegerScheme.DEFAULT_CAPITALIZATION)
}
}
it("returns the original state if no editor changes are made") {
assertThat(editor.readState()).isEqualTo(editor.originalState)
}
it("returns the editor's state") {
GuiActionRunner.execute {
frame.spinner("minValue").target().value = 2_147_483_648L
frame.spinner("maxValue").target().value = 2_147_483_649L
frame.spinner("base").target().value = 14
frame.radioButton("groupingSeparatorPeriod").target().isSelected = true
frame.panel("groupingSeparatorCustom").textBox().target().text = "s"
frame.radioButton("capitalizationUpper").target().isSelected = true
frame.textBox("prefix").target().text = "silent"
frame.textBox("suffix").target().text = "pain"
}
val readScheme = editor.readState()
assertThat(readScheme.minValue).isEqualTo(2_147_483_648L)
assertThat(readScheme.maxValue).isEqualTo(2_147_483_649L)
assertThat(readScheme.base).isEqualTo(14)
assertThat(readScheme.groupingSeparator).isEqualTo(".")
assertThat(readScheme.customGroupingSeparator).isEqualTo("s")
assertThat(readScheme.capitalization).isEqualTo(CapitalizationMode.UPPER)
assertThat(readScheme.prefix).isEqualTo("silent")
assertThat(readScheme.suffix).isEqualTo("pain")
}
it("returns the loaded state if no editor changes are made") {
GuiActionRunner.execute { frame.spinner("minValue").target().value = 242L }
assertThat(editor.isModified()).isTrue()
GuiActionRunner.execute { editor.loadState(editor.readState()) }
assertThat(editor.isModified()).isFalse()
assertThat(editor.readState()).isEqualTo(editor.originalState)
}
it("returns a different instance from the loaded scheme") {
val readState = editor.readState()
assertThat(readState)
.isEqualTo(editor.originalState)
.isNotSameAs(editor.originalState)
assertThat(readState.arrayDecorator)
.isEqualTo(editor.originalState.arrayDecorator)
.isNotSameAs(editor.originalState.arrayDecorator)
}
it("retains the scheme's UUID") {
assertThat(editor.readState().uuid).isEqualTo(editor.originalState.uuid)
}
}
describe("addChangeListener") {
it("invokes the listener if a field changes") {
var listenerInvoked = false
editor.addChangeListener { listenerInvoked = true }
GuiActionRunner.execute { frame.spinner("minValue").target().value = 76L }
assertThat(listenerInvoked).isTrue()
}
it("invokes the listener if the array decorator changes") {
GuiActionRunner.execute {
editor.loadState(IntegerScheme(arrayDecorator = ArrayDecorator(enabled = true)))
}
var listenerInvoked = false
editor.addChangeListener { listenerInvoked = true }
GuiActionRunner.execute { frame.spinner("arrayMinCount").target().value = 528 }
assertThat(listenerInvoked).isTrue()
}
}
})
| mit | 23ffcb6287ef496b29af90987553f007 | 37.171946 | 118 | 0.637624 | 5.282405 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/request/json/v5/model/SyncTokenRequestBody.kt | 1 | 961 | package com.jeremiahzucker.pandroid.request.json.v5.model
import com.jeremiahzucker.pandroid.PandroidApplication.Companion.Preferences
/**
* Created by Jeremiah Zucker on 8/20/2017.
*/
open class SyncTokenRequestBody(tokenType: TokenType = TokenType.USER) {
enum class TokenType(val getToken: () -> String?) {
USER({ Preferences.userAuthToken }),
PARTNER({ Preferences.partnerAuthToken }),
NONE({ null })
}
val syncTime: Long = (Preferences.syncTimeOffset ?: 0L) + (System.currentTimeMillis() / 1000L)
// Use nullable types to allow GSON to only serialize populated members
var userAuthToken: String? = null
var partnerAuthToken: String? = null
init {
when (tokenType) {
TokenType.USER -> {
userAuthToken = tokenType.getToken()
}
TokenType.PARTNER -> {
partnerAuthToken = tokenType.getToken()
}
}
}
}
| mit | 057a6574043fd23d95bb64be42d01b2d | 29.03125 | 98 | 0.633715 | 4.665049 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/persist/Preferences.kt | 1 | 4004 | package com.jeremiahzucker.pandroid.persist
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
// class NullableDatastoreDelegate<V>(private val dataStore: DataStore<Preferences>, private val key: Preferences.Key<V>) {
//
// companion object {
// private const val LONG_NULL = Long.MAX_VALUE
// }
//
// operator fun getValue(thisRef: Any?, prop: KProperty<*>): V? = runBlocking {
// dataStore.data.map { it[key] }.map { if (it == LONG_NULL) null else it }.single()
// }
//
// operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: V?) = dataStore.editBlocking {
// it[key] = when (value) {
// is Long -> value
// else -> value
// } ?: LONG_NULL as V
// }
//
// private fun DataStore<Preferences>.editBlocking(transform: suspend (MutablePreferences) -> Unit): Preferences = runBlocking {
// edit(transform)
// }
// }
//
// inline fun <reified V : Any> DataStore<Preferences>.bindToPreferenceFieldNullable(prop: KProperty<*>) = NullableDatastoreDelegate<V>(this, preferencesKey(prop.name))
class NullableSharedPreferencesDelegate<V : Any>(private val sharedPreferences: SharedPreferences, private val dataClass: KClass<V>) {
companion object {
private const val LONG_NULL = Long.MAX_VALUE
private const val STRING_NULL = "I'm a null string baby"
}
operator fun getValue(thisRef: Any?, prop: KProperty<*>): V? = when (dataClass) {
Long::class -> when (val value = sharedPreferences.getLong(prop.name, LONG_NULL)) {
LONG_NULL -> null
else -> value
}
String::class -> when (val value = sharedPreferences.getString(prop.name, STRING_NULL)) {
STRING_NULL -> null
else -> value
}
else -> throw IllegalArgumentException("unsupported type $dataClass")
} as? V
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: V?) = sharedPreferences.edit {
when (dataClass) {
Long::class -> putLong(prop.name, value as? Long ?: LONG_NULL)
String::class -> putString(prop.name, value as? String ?: STRING_NULL)
else -> throw IllegalArgumentException("unsupported type $dataClass")
} as? V
}
}
inline fun <reified V : Any> SharedPreferences.bindToPreferenceFieldNullable() = NullableSharedPreferencesDelegate(this, V::class)
/**
* Created by jzucker on 7/7/17.
* SharedPreferences
*/
class Preferences(application: Application) {
// fun init(context: Context) {
// this.context = context
// }
//
// private lateinit var context: Context
private val context: Context = application
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
// private val dataStore: DataStore<Preferences> = context.createDataStore("settings")
// init {
// GlobalScope.launch {
// dataStore.data.first()
// }
// }
var syncTimeOffset: Long? by sharedPreferences.bindToPreferenceFieldNullable()
var partnerId: String? by sharedPreferences.bindToPreferenceFieldNullable()
var partnerAuthToken: String? by sharedPreferences.bindToPreferenceFieldNullable()
var userAuthToken: String? by sharedPreferences.bindToPreferenceFieldNullable()
var userId: String? by sharedPreferences.bindToPreferenceFieldNullable()
var stationListChecksum: String? by sharedPreferences.bindToPreferenceFieldNullable()
var username: String? by sharedPreferences.bindToPreferenceFieldNullable()
var password: String? by sharedPreferences.bindToPreferenceFieldNullable()
fun reset() {
syncTimeOffset = null
partnerId = null
partnerAuthToken = null
userAuthToken = null
userId = null
stationListChecksum = null
}
}
| mit | 8ec96c6c50448ebb0a8d023f76f4780e | 37.5 | 168 | 0.682318 | 4.612903 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/views/dashboard/Stuff.kt | 1 | 2060 | package net.perfectdreams.spicymorenitta.views.dashboard
import kotlinx.html.*
import kotlinx.html.dom.create
import net.perfectdreams.spicymorenitta.utils.loriUrl
import net.perfectdreams.spicymorenitta.utils.TingleModal
import net.perfectdreams.spicymorenitta.utils.TingleOptions
import kotlinx.browser.document
import kotlinx.browser.window
object Stuff {
fun showPremiumFeatureModal(description: (DIV.() -> (Unit))? = null) {
val modal = TingleModal(
TingleOptions(
footer = true,
cssClass = arrayOf("tingle-modal--overflow")
)
)
modal.setContent(
document.create.div {
div(classes = "category-name") {
+ "Você encontrou uma função premium!"
}
div {
style = "text-align: center;"
img(src = "https://i.imgur.com/wEUDTZG.png") {
width = "250"
}
if (description != null) {
description.invoke(this)
} else {
p {
+"Você encontrou uma função premium minha! Legal, né?"
}
p {
+"Para ter esta função e muito mais, veja a minha lista de vantagens que você pode ganhar doando!"
}
}
}
}
)
modal.addFooterBtn("<i class=\"fas fa-gift\"></i> Vamos lá!", "button-discord button-discord-info pure-button button-discord-modal") {
window.open("${loriUrl}donate", "_blank")
}
modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") {
modal.close()
}
modal.open()
}
} | agpl-3.0 | 0970f607d2dcef434f2d075ac652db02 | 34.964912 | 158 | 0.488531 | 4.776224 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/util/extension/ProxerLibExtensions.kt | 1 | 21384 | @file:Suppress("MethodOverloading")
package me.proxer.app.util.extension
import android.content.Context
import android.content.res.Resources
import androidx.appcompat.content.res.AppCompatResources
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorInt
import me.proxer.app.R
import me.proxer.app.R.id.description
import me.proxer.app.R.id.post
import me.proxer.app.anime.AnimeStream
import me.proxer.app.anime.resolver.StreamResolutionResult
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.LocalMessage
import me.proxer.app.chat.pub.message.ParsedChatMessage
import me.proxer.app.comment.LocalComment
import me.proxer.app.forum.ParsedPost
import me.proxer.app.forum.TopicMetaData
import me.proxer.app.media.LocalTag
import me.proxer.app.media.comments.ParsedComment
import me.proxer.app.profile.comment.ParsedUserComment
import me.proxer.app.profile.history.LocalUserHistoryEntry
import me.proxer.app.profile.media.LocalUserMediaListEntry
import me.proxer.app.profile.settings.LocalProfileSettings
import me.proxer.app.profile.topten.LocalTopTenEntry
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.toBBTree
import me.proxer.app.ui.view.bbcode.toSimpleBBTree
import me.proxer.library.entity.anime.Stream
import me.proxer.library.entity.chat.ChatMessage
import me.proxer.library.entity.forum.Post
import me.proxer.library.entity.forum.Topic
import me.proxer.library.entity.info.Comment
import me.proxer.library.entity.info.Entry
import me.proxer.library.entity.info.EntryCore
import me.proxer.library.entity.info.EntrySeasonInfo
import me.proxer.library.entity.info.Synonym
import me.proxer.library.entity.list.Tag
import me.proxer.library.entity.manga.Chapter
import me.proxer.library.entity.manga.Page
import me.proxer.library.entity.messenger.Conference
import me.proxer.library.entity.messenger.Message
import me.proxer.library.entity.ucp.UcpHistoryEntry
import me.proxer.library.entity.ucp.UcpSettings
import me.proxer.library.entity.ucp.UcpTopTenEntry
import me.proxer.library.entity.user.TopTenEntry
import me.proxer.library.entity.user.UserComment
import me.proxer.library.entity.user.UserHistoryEntry
import me.proxer.library.entity.user.UserMediaListEntry
import me.proxer.library.enums.AnimeLanguage
import me.proxer.library.enums.CalendarDay
import me.proxer.library.enums.Category
import me.proxer.library.enums.Country
import me.proxer.library.enums.FskConstraint
import me.proxer.library.enums.Gender
import me.proxer.library.enums.IndustryType
import me.proxer.library.enums.Language
import me.proxer.library.enums.License
import me.proxer.library.enums.MediaLanguage
import me.proxer.library.enums.MediaState
import me.proxer.library.enums.MediaType
import me.proxer.library.enums.Medium
import me.proxer.library.enums.MessageAction
import me.proxer.library.enums.RelationshipStatus
import me.proxer.library.enums.Season
import me.proxer.library.enums.SynonymType
import me.proxer.library.enums.UserMediaProgress
import me.proxer.library.util.ProxerUrls
import me.proxer.library.util.ProxerUrls.hasProxerHost
import okhttp3.HttpUrl
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
object ProxerLibExtensions {
fun fskConstraintFromAppString(context: Context, string: String) = when (string) {
context.getString(R.string.fsk_0) -> FskConstraint.FSK_0
context.getString(R.string.fsk_6) -> FskConstraint.FSK_6
context.getString(R.string.fsk_12) -> FskConstraint.FSK_12
context.getString(R.string.fsk_16) -> FskConstraint.FSK_16
context.getString(R.string.fsk_18) -> FskConstraint.FSK_18
context.getString(R.string.fsk_bad_language) -> FskConstraint.BAD_LANGUAGE
context.getString(R.string.fsk_fear) -> FskConstraint.FEAR
context.getString(R.string.fsk_violence) -> FskConstraint.VIOLENCE
context.getString(R.string.fsk_sex) -> FskConstraint.SEX
else -> error("Could not find fsk constraint for description: $description")
}
}
fun Medium.toAppString(context: Context): String = context.getString(
when (this) {
Medium.ANIMESERIES -> R.string.medium_anime_series
Medium.HENTAI -> R.string.medium_hentai
Medium.MOVIE -> R.string.medium_movie
Medium.OVA -> R.string.medium_ova
Medium.MANGASERIES -> R.string.medium_manga_series
Medium.LIGHTNOVEL -> R.string.medium_lightnovel
Medium.WEBNOVEL -> R.string.medium_webnovel
Medium.VISUALNOVEL -> R.string.medium_visualnovel
Medium.DOUJIN -> R.string.medium_doujin
Medium.HMANGA -> R.string.medium_h_manga
Medium.ONESHOT -> R.string.medium_oneshot
Medium.OTHER -> R.string.medium_other
}
)
fun MediaLanguage.toGeneralLanguage() = when (this) {
MediaLanguage.GERMAN, MediaLanguage.GERMAN_SUB, MediaLanguage.GERMAN_DUB -> Language.GERMAN
MediaLanguage.ENGLISH, MediaLanguage.ENGLISH_SUB, MediaLanguage.ENGLISH_DUB -> Language.ENGLISH
MediaLanguage.OTHER -> Language.OTHER
}
fun MediaLanguage.toAnimeLanguage() = when (this) {
MediaLanguage.GERMAN, MediaLanguage.GERMAN_SUB -> AnimeLanguage.GERMAN_SUB
MediaLanguage.ENGLISH, MediaLanguage.ENGLISH_SUB -> AnimeLanguage.ENGLISH_SUB
MediaLanguage.GERMAN_DUB -> AnimeLanguage.GERMAN_DUB
MediaLanguage.ENGLISH_DUB -> AnimeLanguage.ENGLISH_DUB
MediaLanguage.OTHER -> AnimeLanguage.OTHER
}
fun Language.toMediaLanguage() = when (this) {
Language.GERMAN -> MediaLanguage.GERMAN
Language.ENGLISH -> MediaLanguage.ENGLISH
Language.OTHER -> MediaLanguage.OTHER
}
fun AnimeLanguage.toMediaLanguage() = when (this) {
AnimeLanguage.GERMAN_SUB -> MediaLanguage.GERMAN_SUB
AnimeLanguage.GERMAN_DUB -> MediaLanguage.GERMAN_DUB
AnimeLanguage.ENGLISH_SUB -> MediaLanguage.ENGLISH_SUB
AnimeLanguage.ENGLISH_DUB -> MediaLanguage.ENGLISH_DUB
AnimeLanguage.OTHER -> MediaLanguage.OTHER
}
fun Language.toAppDrawable(context: Context) = AppCompatResources.getDrawable(
context,
when (this) {
Language.GERMAN -> R.drawable.ic_germany
Language.ENGLISH -> R.drawable.ic_united_states
Language.OTHER -> R.drawable.ic_united_nations
}
) ?: error("Could not resolve Drawable for language: $this")
fun MediaLanguage.toAppString(context: Context): String = context.getString(
when (this) {
MediaLanguage.GERMAN -> R.string.language_german
MediaLanguage.ENGLISH -> R.string.language_english
MediaLanguage.GERMAN_SUB -> R.string.language_german_sub
MediaLanguage.GERMAN_DUB -> R.string.language_german_dub
MediaLanguage.ENGLISH_SUB -> R.string.language_english_sub
MediaLanguage.ENGLISH_DUB -> R.string.language_english_dub
MediaLanguage.OTHER -> R.string.language_other
}
)
fun Country.toAppDrawable(context: Context) = AppCompatResources.getDrawable(
context,
when (this) {
Country.GERMANY -> R.drawable.ic_germany
Country.ENGLAND -> R.drawable.ic_united_states
Country.UNITED_STATES -> R.drawable.ic_united_states
Country.JAPAN -> R.drawable.ic_japan
Country.KOREA -> R.drawable.ic_korea
Country.CHINA -> R.drawable.ic_china
Country.INTERNATIONAL, Country.OTHER, Country.NONE -> R.drawable.ic_united_nations
}
) ?: error("Could not resolve Drawable for country: $this")
fun Medium.toCategory() = when (this) {
Medium.ANIMESERIES, Medium.MOVIE, Medium.OVA, Medium.HENTAI -> Category.ANIME
Medium.MANGASERIES, Medium.ONESHOT, Medium.DOUJIN, Medium.HMANGA -> Category.MANGA
Medium.LIGHTNOVEL, Medium.WEBNOVEL, Medium.VISUALNOVEL -> Category.NOVEL
Medium.OTHER -> error("Invalid medium: OTHER")
}
fun Category.toEpisodeAppString(context: Context, number: Int? = null): String = when (number) {
null -> context.getString(
when (this) {
Category.ANIME -> R.string.category_anime_episodes_title
Category.MANGA, Category.NOVEL -> R.string.category_manga_episodes_title
}
)
else -> context.getString(
when (this) {
Category.ANIME -> R.string.category_anime_episode_number
Category.MANGA, Category.NOVEL -> R.string.category_manga_episode_number
},
number
)
}
fun MediaState.toAppDrawable(context: Context): IconicsDrawable = IconicsDrawable(context).apply {
icon = when (this@toAppDrawable) {
MediaState.PRE_AIRING -> CommunityMaterial.Icon3.cmd_radio_tower
MediaState.FINISHED -> CommunityMaterial.Icon.cmd_book
MediaState.AIRING -> CommunityMaterial.Icon.cmd_book_open_variant
MediaState.CANCELLED -> CommunityMaterial.Icon.cmd_close
MediaState.CANCELLED_SUB -> CommunityMaterial.Icon.cmd_close
}
colorInt = context.resolveColor(R.attr.colorIcon)
}
fun UserMediaProgress.toEpisodeAppString(
context: Context,
episode: Int = 1,
category: Category = Category.ANIME
): String = when (this) {
UserMediaProgress.WATCHED -> context.getString(
when (category) {
Category.ANIME -> R.string.user_media_progress_watched
Category.MANGA, Category.NOVEL -> R.string.user_media_progress_read
}
)
UserMediaProgress.WATCHING -> context.getString(
when (category) {
Category.ANIME -> R.string.user_media_progress_watching
Category.MANGA, Category.NOVEL -> R.string.user_media_progress_reading
},
episode
)
UserMediaProgress.WILL_WATCH -> context.getString(
when (category) {
Category.ANIME -> R.string.user_media_progress_will_watch
Category.MANGA, Category.NOVEL -> R.string.user_media_progress_will_read
}
)
UserMediaProgress.CANCELLED -> context.getString(R.string.user_media_progress_cancelled, episode)
}
fun Synonym.toTypeAppString(context: Context): String = context.getString(
when (this.type) {
SynonymType.ORIGINAL -> R.string.synonym_original_type
SynonymType.ENGLISH -> R.string.synonym_english_type
SynonymType.GERMAN -> R.string.synonym_german_type
SynonymType.JAPANESE -> R.string.synonym_japanese_type
SynonymType.KOREAN -> R.string.synonym_korean_type
SynonymType.CHINESE -> R.string.synonym_chinese_type
SynonymType.ORIGINAL_ALTERNATIVE -> R.string.synonym_alternative_type
SynonymType.OTHER -> R.string.synonym_alternative_type
}
)
fun EntrySeasonInfo.toStartAppString(context: Context): String = when (season) {
Season.WINTER -> context.getString(R.string.season_winter_start, year)
Season.SPRING -> context.getString(R.string.season_spring_start, year)
Season.SUMMER -> context.getString(R.string.season_summer_start, year)
Season.AUTUMN -> context.getString(R.string.season_autumn_start, year)
Season.UNSPECIFIED -> year.toString()
}
fun EntrySeasonInfo.toEndAppString(context: Context): String = when (season) {
Season.WINTER -> context.getString(R.string.season_winter_end, year)
Season.SPRING -> context.getString(R.string.season_spring_end, year)
Season.SUMMER -> context.getString(R.string.season_summer_end, year)
Season.AUTUMN -> context.getString(R.string.season_autumn_end, year)
Season.UNSPECIFIED -> year.toString()
}
fun MediaState.toAppString(context: Context): String = context.getString(
when (this) {
MediaState.PRE_AIRING -> R.string.media_state_pre_airing
MediaState.AIRING -> R.string.media_state_airing
MediaState.CANCELLED -> R.string.media_state_cancelled
MediaState.CANCELLED_SUB -> R.string.media_state_cancelled_sub
MediaState.FINISHED -> R.string.media_state_finished
}
)
fun License.toAppString(context: Context): String = context.getString(
when (this) {
License.LICENSED -> R.string.license_licensed
License.NOT_LICENSED -> R.string.license_not_licensed
License.UNKNOWN -> R.string.license_unknown
}
)
fun FskConstraint.toAppString(context: Context): String = context.getString(
when (this) {
FskConstraint.FSK_0 -> R.string.fsk_0
FskConstraint.FSK_6 -> R.string.fsk_6
FskConstraint.FSK_12 -> R.string.fsk_12
FskConstraint.FSK_16 -> R.string.fsk_16
FskConstraint.FSK_18 -> R.string.fsk_18
FskConstraint.BAD_LANGUAGE -> R.string.fsk_bad_language
FskConstraint.FEAR -> R.string.fsk_fear
FskConstraint.VIOLENCE -> R.string.fsk_violence
FskConstraint.SEX -> R.string.fsk_sex
}
)
fun FskConstraint.toAppStringDescription(context: Context): String = context.getString(
when (this) {
FskConstraint.FSK_0 -> R.string.fsk_0_description
FskConstraint.FSK_6 -> R.string.fsk_6_description
FskConstraint.FSK_12 -> R.string.fsk_12_description
FskConstraint.FSK_16 -> R.string.fsk_16_description
FskConstraint.FSK_18 -> R.string.fsk_18_description
FskConstraint.BAD_LANGUAGE -> R.string.fsk_bad_language_description
FskConstraint.FEAR -> R.string.fsk_fear_description
FskConstraint.VIOLENCE -> R.string.fsk_violence_description
FskConstraint.SEX -> R.string.fsk_sex_description
}
)
fun FskConstraint.toAppDrawable(context: Context) = AppCompatResources.getDrawable(
context,
when (this) {
FskConstraint.FSK_0 -> R.drawable.ic_fsk_0
FskConstraint.FSK_6 -> R.drawable.ic_fsk_6
FskConstraint.FSK_12 -> R.drawable.ic_fsk_12
FskConstraint.FSK_16 -> R.drawable.ic_fsk_16
FskConstraint.FSK_18 -> R.drawable.ic_fsk_18
FskConstraint.BAD_LANGUAGE -> R.drawable.ic_fsk_bad_language
FskConstraint.FEAR -> R.drawable.ic_fsk_fear
FskConstraint.SEX -> R.drawable.ic_fsk_sex
FskConstraint.VIOLENCE -> R.drawable.ic_fsk_violence
}
) ?: error("Could not resolve Drawable for fsk constraint: $this")
fun IndustryType.toAppString(context: Context): String = context.getString(
when (this) {
IndustryType.PUBLISHER -> R.string.industry_publisher
IndustryType.STUDIO -> R.string.industry_studio
IndustryType.STUDIO_SECONDARY -> R.string.industry_studio_secondary
IndustryType.PRODUCER -> R.string.industry_producer
IndustryType.RECORD_LABEL -> R.string.industry_record_label
IndustryType.TALENT_AGENT -> R.string.industry_talent_agent
IndustryType.STREAMING -> R.string.industry_streaming
IndustryType.DEVELOPER -> R.string.industry_developer
IndustryType.TV -> R.string.industry_tv
IndustryType.SOUND_STUDIO -> R.string.industry_sound_studio
IndustryType.UNKNOWN -> R.string.industry_unknown
}
)
fun CalendarDay.toAppString(context: Context): String = context.getString(
when (this) {
CalendarDay.MONDAY -> R.string.day_monday
CalendarDay.TUESDAY -> R.string.day_tuesday
CalendarDay.WEDNESDAY -> R.string.day_wednesday
CalendarDay.THURSDAY -> R.string.day_thursday
CalendarDay.FRIDAY -> R.string.day_friday
CalendarDay.SATURDAY -> R.string.day_saturday
CalendarDay.SUNDAY -> R.string.day_sunday
}
)
fun Gender.toAppString(context: Context): String = context.getString(
when (this) {
Gender.MALE -> R.string.gender_male
Gender.FEMALE -> R.string.gender_female
Gender.OTHER -> R.string.gender_other
Gender.UNKNOWN -> R.string.gender_unknown
}
)
fun RelationshipStatus.toAppString(context: Context): String = context.getString(
when (this) {
RelationshipStatus.SINGLE -> R.string.relationship_status_single
RelationshipStatus.IN_RELATION -> R.string.relationship_status_in_relation
RelationshipStatus.ENGAGED -> R.string.relationship_status_engaged
RelationshipStatus.COMPLICATED -> R.string.relationship_status_complicated
RelationshipStatus.MARRIED -> R.string.relationship_status_married
RelationshipStatus.SEARCHING -> R.string.relationship_status_searching
RelationshipStatus.NOT_SEARCHING -> R.string.relationship_status_not_searching
RelationshipStatus.UNKNOWN -> R.string.relationship_status_unknown
}
)
fun MessageAction.toAppString(context: Context, username: String, message: String): String = when (this) {
MessageAction.ADD_USER -> context.getString(R.string.action_conference_add_user, "@$username", "@$message")
MessageAction.REMOVE_USER -> context.getString(R.string.action_conference_delete_user, "@$username", "@$message")
MessageAction.SET_LEADER -> context.getString(R.string.action_conference_set_leader, "@$username", "@$message")
MessageAction.SET_TOPIC -> context.getString(R.string.action_conference_set_topic, "@$username", message)
MessageAction.EXIT -> context.getString(R.string.action_conference_exit, "@$message")
MessageAction.NONE -> message
}
fun MediaType.isAgeRestricted(): Boolean {
return this == MediaType.ALL_WITH_HENTAI || this == MediaType.HENTAI || this == MediaType.HMANGA
}
inline val Chapter.isOfficial: Boolean
get() = if (pages == null) {
val serverUrl = server.toPrefixedUrlOrNull()
serverUrl != null && serverUrl.host in arrayOf("www.webtoons.com", "www.lezhin.com")
} else {
false
}
inline val Entry.isTrulyAgeRestricted: Boolean
get() = isAgeRestricted || medium == Medium.HMANGA || medium == Medium.HENTAI ||
fskConstraints.contains(FskConstraint.FSK_18)
inline val EntryCore.isAgeRestricted: Boolean
get() = medium == Medium.HMANGA || medium == Medium.HENTAI || fskConstraints.contains(FskConstraint.FSK_18)
inline val Page.decodedName: String
get() = try {
URLDecoder.decode(name, "UTF-8")
} catch (error: UnsupportedEncodingException) {
""
}
fun Stream.toAnimeStream(
isSupported: Boolean,
resolutionResult: StreamResolutionResult? = null
) = AnimeStream(
id, hoster, hosterName, image, uploaderId, uploaderName, date.toInstantBP(), translatorGroupId, translatorGroupName,
isOfficial, isPublic, isSupported, resolutionResult
)
fun Conference.toLocalConference(isFullyLoaded: Boolean) = LocalConference(
id.toLong(), topic, customTopic, participantAmount, image, imageType, isGroup, isRead, isRead, date.toInstantBP(),
unreadMessageAmount, lastReadMessageId, isFullyLoaded
)
fun UcpSettings.toLocalSettings() = LocalProfileSettings(
profileVisibility, topTenVisibility, animeVisibility, mangaVisibility, commentVisibility, forumVisibility,
friendVisibility, friendRequestConstraint, aboutVisibility, historyVisibility, guestBookVisibility,
guestBookEntryConstraint, galleryVisibility, articleVisibility, isHideTags, isShowAds, adInterval
)
fun Message.toLocalMessage() = LocalMessage(
id.toLong(),
conferenceId.toLong(),
userId,
username,
message,
action,
date.toInstantBP(),
device
)
fun Comment.toParsedComment() = ParsedComment(
id, entryId, authorId, mediaProgress, ratingDetails,
content.toSimpleBBTree(), overallRating, episode, helpfulVotes, date.toInstantBP(), author, image
)
fun Comment.toLocalComment() = LocalComment(
id,
entryId,
mediaProgress,
ratingDetails,
content,
overallRating,
episode
)
fun UserComment.toParsedUserComment() = ParsedUserComment(
id, entryId, entryName, medium, category, authorId, mediaProgress, ratingDetails,
content.toSimpleBBTree(), overallRating, episode, helpfulVotes, date.toInstantBP(), author, image
)
fun Topic.toTopicMetaData() = TopicMetaData(
categoryId,
categoryName,
firstPostDate,
lastPostDate,
hits,
isLocked,
post,
subject
)
fun Post.toParsedPost(resources: Resources): ParsedPost {
val parsedMessage = message.toBBTree(BBArgs(resources = resources, userId = userId))
val parsedSignature = signature?.let {
if (it.isNotBlank()) it.toBBTree(BBArgs(resources = resources, userId = userId)) else null
}
return ParsedPost(
id, parentId, userId, username, image, date.toInstantBP(), parsedSignature,
modifiedById, modifiedByName, modifiedReason, parsedMessage, thankYouAmount
)
}
fun Tag.toParcelableTag() = LocalTag(id, type, name, description, subType, isSpoiler)
fun ChatMessage.toParsedMessage() = ParsedChatMessage(id, userId, username, image, message, action, date.toInstantBP())
fun UserMediaListEntry.toLocalEntry() = LocalUserMediaListEntry(
id, name, episodeAmount, medium, state, commentId, commentContent, mediaProgress, episode, rating
)
fun UserMediaListEntry.toLocalEntryUcp() = LocalUserMediaListEntry.Ucp(
id, name, episodeAmount, medium, state, commentId, commentContent, mediaProgress, episode, rating
)
fun UserHistoryEntry.toLocalEntry() = LocalUserHistoryEntry(id, entryId, name, language, medium, category, episode)
fun UcpHistoryEntry.toLocalEntryUcp() = LocalUserHistoryEntry.Ucp(
id,
entryId,
name,
language,
medium,
category,
episode,
date
)
fun TopTenEntry.toLocalEntry() = LocalTopTenEntry(id, name, category, medium)
fun UcpTopTenEntry.toLocalEntryUcp() = LocalTopTenEntry.Ucp(id, name, category, medium, entryId)
fun HttpUrl.proxyIfRequired() = when (this.hasProxerHost) {
true -> this
false -> ProxerUrls.proxyImage(this)
}
| gpl-3.0 | aa0d92deacf5b9ff78b2a2b6906b2a94 | 40.603113 | 120 | 0.731294 | 4.052302 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/main/tools/apps/AppDetailsActivity.kt | 1 | 13002 | package com.androidvip.hebf.ui.main.tools.apps
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.*
import androidx.lifecycle.lifecycleScope
import com.androidvip.hebf.R
import com.androidvip.hebf.applyAnim
import com.androidvip.hebf.getThemedVectorDrawable
import com.androidvip.hebf.models.App
import com.androidvip.hebf.ui.base.BaseActivity
import com.androidvip.hebf.utils.*
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_app_details.*
import kotlinx.coroutines.launch
import java.io.File
// Todo: check target sdk 29
class AppDetailsActivity : BaseActivity() {
private lateinit var appPackageName: TextView
private lateinit var appVersion: TextView
private lateinit var storageDetails: TextView
private lateinit var pathDetails: TextView
private lateinit var storage: LinearLayout
private lateinit var path: LinearLayout
private lateinit var appOps: FrameLayout
private lateinit var appIcon: ImageView
private lateinit var packagesManager: PackagesManager
private var sdSize: Long = 0
private var internalSize: Long = 0
private var appSize: Long = 0
private lateinit var apkFile: File
private var aPackageName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_app_details)
setUpToolbar(toolbar)
bindViews()
packagesManager = PackagesManager(this)
// Check the data from intent
val app = intent.getSerializableExtra(K.EXTRA_APP) as App?
if (app != null) {
aPackageName = app.packageName
// Update Toolbar title with app name
supportActionBar?.title = app.label
// Show info according to the given package name
appIcon.setImageDrawable(packagesManager.getAppIcon(app.packageName))
appPackageName.text = app.packageName
appVersion.text = "v${app.versionName}"
// Get disabled state of the package and set button text accordingly
if (!app.isEnabled) appDetailsDisable.setText(R.string.enable)
appOps.setOnClickListener {
val i = Intent(this@AppDetailsActivity, AppOpsActivity::class.java)
i.putExtra(K.EXTRA_APP, intent.getSerializableExtra(K.EXTRA_APP))
startActivity(i)
}
lifecycleScope.launch(workerContext) {
// Check if the system has the appops binary
val supportsAppOps = RootUtils.executeSync("which appops").isNotEmpty()
// Get the package installation path from the PackageManager
val pathString = Utils.runCommand(
"pm path ${aPackageName!!}",
getString(android.R.string.unknownName)
).replace("package:", "")
apkFile = File(pathString)
if (apkFile.exists()) {
appSize = runCatching {
// Get root installation folder size
RootUtils.executeWithOutput(
"du -s ${apkFile.parentFile.absolutePath} | awk '{print $1}'",
"0"
).toLong()
}.getOrElse {
runCatching {
RootUtils.executeWithOutput(
"du -s ${apkFile.parentFile.absolutePath} | awk '{print $1}'",
"0"
).toLong()
}.getOrDefault(0)
}
}
try {
// Get external folder size
sdSize = FileUtils.getFileSize(File("${Environment.getExternalStorageDirectory()}/Android/data/$aPackageName")) / 1024
// Get root data folder size
internalSize = RootUtils.executeWithOutput("du -s /data/data/$aPackageName | awk '{print $1}'", "0").toLong()
} catch (e: Exception) {
try { //again
sdSize = FileUtils.getFileSize(File("${Environment.getExternalStorageDirectory()}/Android/data/$aPackageName")) / 1024
internalSize = RootUtils.executeWithOutput("du -s /data/data/$aPackageName | awk '{print $1}'", "0").toLong()
} catch (ex: Exception) {
sdSize = 0
internalSize = 0
}
}
runSafeOnUiThread {
/*
* Compute and show total storage size on the UI Thread.
* Set pathDetails text to the package path obtained from PackageManager,
* this path is used to share .apk file of the app.
*/
val finalSize = (sdSize + internalSize + appSize) / 1024
pathDetails.text = pathString
storageDetails.text = "$finalSize MB"
findViewById<View>(R.id.app_details_progress).visibility = View.GONE
findViewById<View>(R.id.app_details_detail_layout).visibility = View.VISIBLE
if (!supportsAppOps) {
appOps.visibility = View.GONE
Logger.logWarning("Appops is not supported", this@AppDetailsActivity)
}
}
}
// Show storage usage details
storage.setOnClickListener {
MaterialAlertDialogBuilder(this@AppDetailsActivity)
.setTitle(R.string.storage)
.setMessage("SD: ${if (sdSize >= 1024) "${(sdSize / 1024)}MB\n" else "${sdSize}KB\n"}Internal: ${if (internalSize >= 1024) "${(internalSize / 1024)}MB\n" else "${internalSize}KB\n"}App: ${appSize / 1024}MB")
.setPositiveButton(R.string.clear_data) { _, _ ->
// Clear data associated with the package using the PackageManager
runCommand("pm clear ${aPackageName!!}")
Logger.logInfo("Cleared data of the package: ${aPackageName!!}", this)
}
.setNegativeButton(R.string.close) { _, _ -> }
.applyAnim().also {
it.show()
}
}
path.setOnClickListener {
if (apkFile.isFile) {
// Share .apk file
val uri = Uri.parse(apkFile.toString())
val share = Intent(Intent.ACTION_SEND)
share.type = "application/octet-stream"
share.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(share, "Share APK File"))
}
}
// Disable or enable package
appDetailsDisable.setOnClickListener {
if (app.isEnabled) {
MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.warning))
.setIcon(getThemedVectorDrawable(R.drawable.ic_warning))
.setMessage(getString(R.string.confirmation_message))
.setNegativeButton(R.string.cancelar) { _, _ -> }
.setPositiveButton(R.string.disable) { _, _ ->
runCommand("pm disable ${aPackageName!!}")
Logger.logInfo("Disabled package: ${aPackageName!!}", this)
Snackbar.make(appDetailsDisable, R.string.package_disabled, Snackbar.LENGTH_LONG).show()
// Update button text
appDetailsDisable.setText(R.string.enable)
}.applyAnim().also {
it.show()
}
} else {
// Enable package using the PackageManager and update button text
runCommand("pm enable ${aPackageName!!}")
Logger.logInfo("Enabled package: ${aPackageName!!}", this)
appDetailsDisable.setText(R.string.disable)
}
}
appDetailsUninstall.setOnClickListener {
Logger.logWarning("Attempting to uninstall package: ${aPackageName!!}", this)
if (app.isSystemApp) {
MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.warning))
.setIcon(getThemedVectorDrawable(R.drawable.ic_warning))
.setMessage(getString(R.string.confirmation_message))
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.setPositiveButton(R.string.uninstall) { _, _ ->
lifecycleScope.launch(workerContext) {
// Get package path
val packagePathString = RootUtils.executeWithOutput("pm path ${aPackageName!!}", "", this@AppDetailsActivity).substring(8)
val packagePath = File(packagePathString)
if (packagePath.isFile) {
RootUtils.deleteFileOrDir(packagePathString)
RootUtils.deleteFileOrDir("${Environment.getDataDirectory()}/data/$aPackageName")
Logger.logInfo("Deleted package: ${aPackageName!!}", this@AppDetailsActivity)
runSafeOnUiThread {
MaterialAlertDialogBuilder(this@AppDetailsActivity)
.setTitle(R.string.package_uninstalled)
.setMessage("Reboot your device")
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setNeutralButton(R.string.reboot) { _, _ -> runCommand("reboot") }
.applyAnim().also {
it.show()
}
}
} else {
runSafeOnUiThread {
Snackbar.make(appDetailsUninstall, "${getString(R.string.error)}: $packagePath does not exist", Snackbar.LENGTH_LONG).show()
}
}
}
}
.applyAnim().also {
it.show()
}
} else {
// User app, invoke Android uninstall dialog and let it deal with the package
try {
val packageURI = Uri.parse("package:${aPackageName!!}")
val uninstallIntent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI)
startActivity(uninstallIntent)
} catch (e: Exception) {
Toast.makeText(this@AppDetailsActivity, "Could not launch uninstall dialog for package: $aPackageName. Reason: ${e.message}", Toast.LENGTH_LONG).show()
Logger.logError("Could not launch uninstall dialog for package: $aPackageName. Reason: ${e.message}", this@AppDetailsActivity)
}
}
}
} else {
// Something went wrong, return back to the previous screen
Logger.logWTF("Failed to show app details because no app was provided to begin with", this)
Toast.makeText(this, R.string.failed, Toast.LENGTH_SHORT).show()
finish()
}
}
private fun bindViews() {
appPackageName = findViewById(R.id.app_details_package_name)
appVersion = findViewById(R.id.app_details_version)
appIcon = findViewById(R.id.app_details_icon)
appOps = findViewById(R.id.app_details_app_ops)
storage = findViewById(R.id.app_details_storage)
storageDetails = findViewById(R.id.app_details_storage_sum)
path = findViewById(R.id.app_details_path)
pathDetails = findViewById(R.id.app_details_path_sum)
}
}
| apache-2.0 | 0cbf1a4ea3f48f4c20c6d582269e16f6 | 50.188976 | 231 | 0.516997 | 5.869977 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/App.kt | 1 | 3999 | /**
* 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
import android.app.Application
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.res.ResourcesCompat
import fr.cph.chicago.R
import fr.cph.chicago.core.activity.ErrorActivity
import fr.cph.chicago.core.model.Theme
import fr.cph.chicago.service.PreferenceService
import io.reactivex.rxjava3.plugins.RxJavaPlugins
import timber.log.Timber
import timber.log.Timber.DebugTree
/**
* Main class that extends Application. Mainly used to get the context from anywhere in the app.
*
* @author Carl-Philipp Harmant
* @version 1
*/
class App : Application() {
companion object {
lateinit var instance: App
private val preferenceService = PreferenceService
fun startErrorActivity() {
val context = instance.applicationContext
val intent = Intent(context, ErrorActivity::class.java)
intent.putExtra(context.getString(R.string.bundle_error), "Something went wrong")
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
var refresh: Boolean = false
val lineWidthGoogleMap: Float by lazy {
if (screenWidth > 1080) 7f else if (screenWidth > 480) 4f else 2f
}
val lineWidthMapBox: Float by lazy {
if (screenWidth > 1080) 2f else if (screenWidth > 480) 1f else 2f
}
val streetViewPlaceHolder: Drawable by lazy {
ResourcesCompat.getDrawable(resources, R.drawable.placeholder_street_view, this.theme)!!
}
override fun onCreate() {
instance = this
Timber.plant(DebugTree())
RxJavaPlugins.setErrorHandler { throwable ->
Timber.e(throwable, "RxError not handled")
startErrorActivity()
}
themeSetup()
super.onCreate()
}
fun themeSetup() {
when (preferenceService.getTheme()) {
Theme.AUTO -> {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
}
}
Theme.LIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
Theme.DARK -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
}
val screenWidth: Int by lazy {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
val windowManager: WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val rect: Rect = windowManager.currentWindowMetrics.bounds
rect.width()
}
else -> {
val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val point = Point()
display.getSize(point)
point.x
}
}
}
}
| apache-2.0 | d0120d9ff0956f599b1d508a1ab45e0d | 32.605042 | 151 | 0.671918 | 4.655413 | false | false | false | false |
jsargent7089/android | src/main/java/com/nextcloud/client/etm/pages/EtmMigrations.kt | 1 | 2253 | package com.nextcloud.client.etm.pages
import android.os.Bundle
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 com.nextcloud.client.etm.EtmBaseFragment
import com.owncloud.android.R
import kotlinx.android.synthetic.main.fragment_etm_migrations.*
import java.util.Locale
class EtmMigrations : EtmBaseFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_etm_migrations, container, false)
}
override fun onResume() {
super.onResume()
showStatus()
}
fun showStatus() {
val builder = StringBuilder()
val status = vm.migrationsStatus.toString().toLowerCase(Locale.US)
builder.append("Migration status: $status\n")
val lastMigratedVersion = if (vm.lastMigratedVersion >= 0) {
vm.lastMigratedVersion.toString()
} else {
"never"
}
builder.append("Last migrated version: $lastMigratedVersion\n")
builder.append("Migrations:\n")
vm.migrationsInfo.forEach {
val migrationStatus = if (it.applied) {
"applied"
} else {
"pending"
}
builder.append(" - ${it.id} ${it.description} - $migrationStatus\n")
}
etm_migrations_text.text = builder.toString()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_migrations, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_migrations_delete -> {
onDeleteMigrationsClicked(); true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onDeleteMigrationsClicked() {
vm.clearMigrations()
showStatus()
}
}
| gpl-2.0 | 0b445064fc74f2f5c0ec95c7b4676b2e | 30.732394 | 116 | 0.650688 | 4.674274 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/domain/SeasonData.kt | 1 | 827 | package cz.vhromada.catalog.web.domain
import cz.vhromada.catalog.entity.Season
import cz.vhromada.common.entity.Time
import java.io.Serializable
import java.util.Objects
/**
* A class represents season data.
*
* @author Vladimir Hromada
*/
data class SeasonData(
/**
* Season
*/
val season: Season,
/**
* Count of episodes
*/
val episodesCount: Int,
/**
* Total length
*/
val totalLength: Time) : Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return if (other !is SeasonData) {
false
} else season == other.season
}
override fun hashCode(): Int {
return Objects.hashCode(season)
}
}
| mit | ab3bd2720ab2d0e57ec16d89c240768d | 18.232558 | 47 | 0.556227 | 4.398936 | false | false | false | false |
moxi/weather-app-demo | weather-library/src/main/java/org/rcgonzalezf/weather/openweather/model/OpenWeatherCurrentData.kt | 1 | 348 | package org.rcgonzalezf.weather.openweather.model
import org.rcgonzalezf.weather.common.models.converter.Data
class OpenWeatherCurrentData : Data {
val name: String? = null
val cod: String? = null
val wind: Wind? = null
val weather: List<Weather>? = null
val sys: Sys? = null
val dt: Long = 0
val main: Main? = null
}
| mit | 4a2eaf58878d499c4fdce108d5c5878b | 25.769231 | 59 | 0.683908 | 3.663158 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/event/WarrenEventDispatcher.kt | 1 | 2104 | package chat.willow.warren.event
import kotlin.reflect.KClass
interface IEventListener<in T> {
fun on(event: T)
}
interface IEventListenersWrapper<T> {
fun add(listener: (T) -> Unit)
fun fireToAll(event: T)
operator fun plusAssign(listener: (T) -> Unit) = add(listener)
}
class EventListenersWrapper<T> : IEventListenersWrapper<T> {
private var listeners: Set<IEventListener<T>> = setOf()
override fun fireToAll(event: T) {
listeners.forEach { it.on(event) }
}
override fun add(listener: (T) -> Unit) {
listeners += object : IEventListener<T> {
override fun on(event: T) = listener(event)
}
}
}
interface IWarrenEventDispatcher {
fun <T : IWarrenEvent> fire(event: T)
fun <T : IWarrenEvent> on(eventClass: KClass<T>, listener: (T) -> Unit)
fun onAny(listener: (Any) -> Unit)
}
class WarrenEventDispatcher : IWarrenEventDispatcher {
private val onAnythingListeners: IEventListenersWrapper<Any> = EventListenersWrapper<Any>()
private var eventToListenersMap = mutableMapOf<Class<*>, IEventListenersWrapper<*>>()
override fun <T : IWarrenEvent> fire(event: T) {
onAnythingListeners.fireToAll(event)
@Suppress("UNCHECKED_CAST")
val listenersWrapper = eventToListenersMap[event::class.java] as? IEventListenersWrapper<T>
listenersWrapper?.fireToAll(event)
}
override fun <T : IWarrenEvent> on(eventClass: KClass<T>, listener: (T) -> Unit) {
val wrapper = eventToListenersMap[eventClass.java] ?: constructAndAddWrapperForEvent(eventClass)
@Suppress("UNCHECKED_CAST")
val typedWrapper = wrapper as? IEventListenersWrapper<T> ?: return
typedWrapper += listener
}
override fun onAny(listener: (Any) -> Unit) {
onAnythingListeners += listener
}
private fun <T : IWarrenEvent> constructAndAddWrapperForEvent(eventClass: KClass<T>): IEventListenersWrapper<T> {
val newWrapper = EventListenersWrapper<T>()
eventToListenersMap[eventClass.java] = newWrapper
return newWrapper
}
} | isc | 428a07eb96ea3f8969cfea1f922900c5 | 29.071429 | 117 | 0.680133 | 4.216433 | false | false | false | false |
google/horologist | media-sample/src/main/java/com/google/android/horologist/mediasample/ui/browse/UampStreamingBrowseScreen.kt | 1 | 2097 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.mediasample.ui.browse
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlaylistPlay
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.wear.compose.material.ScalingLazyListState
import com.google.android.horologist.media.ui.screens.browse.BrowseScreen
import com.google.android.horologist.media.ui.screens.browse.BrowseScreenPlaylistsSectionButton
import com.google.android.horologist.mediasample.R
@Composable
fun UampStreamingBrowseScreen(
onPlaylistsClick: () -> Unit,
onSettingsClick: () -> Unit,
scalingLazyListState: ScalingLazyListState,
modifier: Modifier = Modifier
) {
BrowseScreen(
scalingLazyListState = scalingLazyListState,
modifier = modifier
) {
this.playlistsSection(
buttons = listOf(
BrowseScreenPlaylistsSectionButton(
textId = R.string.horologist_browse_library_playlists_button,
icon = Icons.Default.PlaylistPlay,
onClick = onPlaylistsClick
),
BrowseScreenPlaylistsSectionButton(
textId = R.string.horologist_browse_library_settings_button,
icon = Icons.Default.Settings,
onClick = onSettingsClick
)
)
)
}
}
| apache-2.0 | 1daafcb744419113dcbc3e0b2cb0d4d5 | 37.127273 | 95 | 0.701955 | 4.755102 | false | false | false | false |
Jonatino/Xena | src/main/java/org/xena/offsets/offsets/EngineOffsets.kt | 1 | 4098 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.xena.offsets.offsets
import com.github.jonatino.misc.Strings
import org.xena.offsets.OffsetManager.engineModule
import org.xena.offsets.misc.PatternScanner
import org.xena.offsets.misc.PatternScanner.byPattern
import java.io.IOException
import java.lang.reflect.Field
import java.nio.file.Files
import java.nio.file.Paths
/**
* Created by Jonathan on 11/13/2015.
*/
object EngineOffsets {
/**
* Engine.dll offsets
*/
@JvmField var dwClientState: Int = 0
@JvmField var dwInGame: Int = 0
@JvmField var dwMaxPlayer: Int = 0
@JvmField var dwMapDirectory: Int = 0
@JvmField var dwMapname: Int = 0
@JvmField var dwPlayerInfo: Int = 0
@JvmField var dwViewAngles: Int = 0
@JvmField var dwEnginePosition: Int = 0
@JvmField var m_bCanReload: Int = 0
@JvmField var bSendPacket: Int = 0
@JvmField var dwLocalPlayerIndex: Int = 0
@JvmField var dwGlobalVars: Int = 0
@JvmField var dwSignOnState: Int = 0
@JvmStatic
fun load() {
dwGlobalVars = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0x68, 0x0, 0x0, 0x0, 0x0, 0x68, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x50, 0x08, 0x85, 0xC0)
dwClientState = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x33, 0xD2, 0x6A, 0x0, 0x6A, 0x0, 0x33, 0xC9, 0x89, 0xB0)
dwInGame = byPattern(engineModule(), 0x2, 0x0, PatternScanner.READ, 0x83, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x94, 0xC0, 0xC3)
dwMaxPlayer = byPattern(engineModule(), 0x7, 0x0, PatternScanner.READ, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x80, 0x00, 0x00, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0x55, 0x8B, 0xEC, 0x8A, 0x45, 0x08)
dwMapDirectory = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ, 0x05, 0x00, 0x00, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x80, 0x3D)
dwMapname = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ, 0x05, 0x00, 0x00, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xA1, 0x00, 0x00, 0x00, 0x00)
dwPlayerInfo = byPattern(engineModule(), 0x2, 0x0, PatternScanner.READ, 0x8B, 0x89, 0x00, 0x00, 0x00, 0x00, 0x85, 0xC9, 0x0F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x01)
dwViewAngles = byPattern(engineModule(), 0x4, 0x0, PatternScanner.READ, 0xF3, 0x0F, 0x11, 0x80, 0x00, 0x00, 0x00, 0x00, 0xD9, 0x46, 0x04, 0xD9, 0x05, 0x00, 0x00, 0x00, 0x00)
dwEnginePosition = byPattern(engineModule(), 0x4, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xF3, 0x0F, 0x11, 0x15, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x0D, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x05, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x3D, 0x00, 0x00, 0x00, 0x00)
dwLocalPlayerIndex = byPattern(engineModule(), 0x2, 0x0, PatternScanner.READ, 0x8B, 0x80, 0x00, 0x00, 0x00, 0x00, 0x40, 0xC3)
bSendPacket = byPattern(engineModule(), 0, 0, PatternScanner.SUBTRACT, 0x01, 0x8B, 0x01, 0x8B, 0x40, 0x10)
dwSignOnState = byPattern(engineModule(), 2, 0, PatternScanner.READ, 0x83, 0xB8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0F, 0x94, 0xC0, 0xC3)
}
@JvmStatic
fun dump() {
val text = EngineOffsets::class.java.fields.map { it.name + " -> " + Strings.hex(getValue(it)) }
try {
Files.write(Paths.get("EngineOffsets.txt"), text)
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun getValue(field: Field): Int {
try {
return field.get(EngineOffsets::class.java) as? Int ?: -1
} catch (t: Throwable) {
t.printStackTrace()
}
return -1
}
}
| apache-2.0 | a6537f9d17f656280ba59c0e11c7114e | 46.103448 | 296 | 0.711811 | 2.542184 | false | false | false | false |
JavaEden/OrchidCore | plugins/OrchidJavadoc/src/main/kotlin/com/eden/orchid/javadoc/pages/BaseJavadocPage.kt | 1 | 1217 | package com.eden.orchid.javadoc.pages
import com.copperleaf.javadoc.json.models.JavaDocElement
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.javadoc.JavadocGenerator
import com.eden.orchid.javadoc.resources.BaseJavadocResource
@Archetype(value = ConfigArchetype::class, key = "${JavadocGenerator.GENERATOR_KEY}.pages")
abstract class BaseJavadocPage(
resource: BaseJavadocResource,
key: String,
title: String
) : OrchidPage(resource, key, title) {
fun renderCommentText(el: JavaDocElement) : String {
val builder = StringBuilder()
for(commentComponent in el.comment) {
if(commentComponent.kind in listOf("see", "link")) {
val linkedPage = context.findPage(null, null, commentComponent.className)
if(linkedPage != null) {
builder.append(""" <a href="${linkedPage.link}">${linkedPage.title}</a> """)
}
}
else {
builder.append(commentComponent.text)
}
}
return builder.toString()
}
}
| mit | 392c4fb5375fe4f230c991d90ef6df05 | 33.771429 | 96 | 0.664749 | 4.330961 | false | true | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/main/java/org/wordpress/android/fluxc/example/ui/customer/WooCustomersFragment.kt | 2 | 2936 | package org.wordpress.android.fluxc.example.ui.customer
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_woo_customer.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.wordpress.android.fluxc.example.R
import org.wordpress.android.fluxc.example.prependToLog
import org.wordpress.android.fluxc.example.replaceFragment
import org.wordpress.android.fluxc.example.ui.customer.creation.WooCustomerCreationFragment
import org.wordpress.android.fluxc.example.ui.customer.search.WooCustomersSearchBuilderFragment
import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment
import org.wordpress.android.fluxc.example.utils.showSingleLineDialog
import org.wordpress.android.fluxc.store.WCCustomerStore
import javax.inject.Inject
class WooCustomersFragment : StoreSelectingFragment() {
@Inject internal lateinit var wcCustomerStore: WCCustomerStore
private val coroutineScope = CoroutineScope(Dispatchers.Main)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_woo_customer, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnPrintCutomer.setOnClickListener { printCustomerById() }
btnFetchCustomerList.setOnClickListener {
replaceFragment(WooCustomersSearchBuilderFragment.newInstance(selectedSite!!.id))
}
btnCreateCustomer.setOnClickListener {
replaceFragment(WooCustomerCreationFragment.newInstance(selectedSite!!.id))
}
}
private fun printCustomerById() {
val site = selectedSite!!
showSingleLineDialog(
activity, "Enter the remote customer Id:", isNumeric = true
) { remoteIdEditText ->
if (remoteIdEditText.text.isEmpty()) {
prependToLog("Remote Id is null so doing nothing")
return@showSingleLineDialog
}
val remoteId = remoteIdEditText.text.toString().toLong()
prependToLog("Submitting request to print customer with id: $remoteId")
coroutineScope.launch {
withContext(Dispatchers.Default) {
wcCustomerStore.fetchSingleCustomer(site, remoteId)
}.run {
error?.let { prependToLog("${it.type}: ${it.message}") }
if (model != null) {
prependToLog("Customer data: ${this.model}")
} else {
prependToLog("Customer with id $remoteId is missing")
}
}
}
}
}
}
| gpl-2.0 | 37257e166489da994f784831da7201e5 | 41.550725 | 116 | 0.696526 | 5.150877 | false | false | false | false |
andresmr/UpcomingMovies | app/src/main/java/upcomingmovies/andresmr/com/upcomingmovies/ui/FuntionUtils.kt | 1 | 729 | package upcomingmovies.andresmr.com.upcomingmovies.ui
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.widget.TextView
import org.jetbrains.anko.textColor
import upcomingmovies.andresmr.com.upcomingmovies.data.entities.Result
inline fun <reified T : Activity> Activity.navigate(movie: Result? = null) {
val intent = Intent(this, T::class.java)
intent.putExtra("movie", movie)
startActivity(intent)
}
fun TextView.showMovieHeader(movie: Result?) {
textColor = Color.BLACK
textSize = 20f
val headerTitle = movie?.title + " - " + movie?.popularity
text = headerTitle
}
fun TextView.showMovieContent(movie: Result?) {
text = movie?.overview
} | mit | 513300b8c23a74904c3706e0535a8f57 | 27.076923 | 76 | 0.753086 | 3.816754 | false | false | false | false |
sephiroth74/Material-BottomNavigation | bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BadgeDrawable.kt | 1 | 2271 | package it.sephiroth.android.library.bottomnavigation
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.os.SystemClock
/**
* Created by crugnola on 4/12/16.
*
* The MIT License
*/
class BadgeDrawable(color: Int, private val size: Int) : Drawable() {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var startTimeMillis: Long = 0
var animating: Boolean = true
init {
this.paint.color = color
}
override fun draw(canvas: Canvas) {
if (!animating) {
paint.alpha = ALPHA_MAX.toInt()
drawInternal(canvas)
} else {
if (startTimeMillis == 0L) {
startTimeMillis = SystemClock.uptimeMillis()
}
val normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION
if (normalized >= 1f) {
animating = false
paint.alpha = ALPHA_MAX.toInt()
drawInternal(canvas)
} else {
val partialAlpha = (ALPHA_MAX * normalized).toInt()
alpha = partialAlpha
drawInternal(canvas)
}
}
}
private fun drawInternal(canvas: Canvas) {
val bounds = bounds
val w = bounds.width()
val h = bounds.height()
canvas.drawCircle((bounds.centerX() + w / 2).toFloat(), (bounds.centerY() - h / 2).toFloat(), (w / 2).toFloat(), paint)
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
invalidateSelf()
}
override fun getAlpha(): Int {
return paint.alpha
}
override fun isStateful(): Boolean {
return false
}
override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
invalidateSelf()
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun getIntrinsicHeight(): Int {
return size
}
override fun getIntrinsicWidth(): Int {
return size
}
companion object {
const val FADE_DURATION = 100f
const val ALPHA_MAX = 255f
}
}
| mit | 421eddf9a8e77253de72f4571306fe93 | 24.806818 | 127 | 0.593571 | 4.653689 | false | false | false | false |
spinnaker/keiko | keiko-test-common/src/main/kotlin/com/netflix/spinnaker/mockito/mockito_extensions.kt | 5 | 1456 | package com.netflix.spinnaker.mockito
import org.mockito.stubbing.OngoingStubbing
infix fun <P1, R> OngoingStubbing<R>.doStub(stub: (P1) -> R): OngoingStubbing<R> =
thenAnswer {
it.arguments.run {
@Suppress("UNCHECKED_CAST")
stub.invoke(component1() as P1)
}
}
infix fun <P1, P2, R> OngoingStubbing<R>.doStub(stub: (P1, P2) -> R): OngoingStubbing<R> =
thenAnswer {
it.arguments.run {
@Suppress("UNCHECKED_CAST")
stub.invoke(component1() as P1, component2() as P2)
}
}
infix fun <P1, P2, P3, R> OngoingStubbing<R>.doStub(stub: (P1, P2, P3) -> R): OngoingStubbing<R> =
thenAnswer {
it.arguments.run {
@Suppress("UNCHECKED_CAST")
stub.invoke(component1() as P1, component2() as P2, component3() as P3)
}
}
/* ktlint-disable max-line-length */
infix fun <P1, P2, P3, P4, R> OngoingStubbing<R>.doStub(stub: (P1, P2, P3, P4) -> R): OngoingStubbing<R> =
thenAnswer {
it.arguments.run {
@Suppress("UNCHECKED_CAST")
stub.invoke(component1() as P1, component2() as P2, component3() as P3, component4() as P4)
}
}
infix fun <P1, P2, P3, P4, P5, R> OngoingStubbing<R>.doStub(stub: (P1, P2, P3, P4, P5) -> R): OngoingStubbing<R> =
thenAnswer {
it.arguments.run {
@Suppress("UNCHECKED_CAST")
stub.invoke(component1() as P1, component2() as P2, component3() as P3, component4() as P4, component5() as P5)
}
}
/* ktlint-enable max-line-length */
| apache-2.0 | 798ba25b8696eff569754f348321770d | 31.355556 | 117 | 0.637363 | 2.965377 | false | false | false | false |
enchf/kotlin-koans | src/ii_collections/n22Fold.kt | 1 | 609 | package ii_collections
fun example9() {
val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult })
result == 24
}
// The same as
fun whatFoldDoes(): Int {
var result = 1
listOf(1, 2, 3, 4).forEach { element -> result = element * result}
return result
}
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
// Return the set of products ordered by every customer
return customers.fold(allOrderedProducts, { orderedByAll,
customer -> orderedByAll.intersect(customer.orderedProducts) })
}
| mit | c9c41a2b34f53b6bdb682ef03b80b6bf | 29.45 | 111 | 0.638752 | 4.2 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/assembler/AssemblerQueryService.kt | 1 | 11377 | /*
* Copyright (C) 2019. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.assembler
import com.openlattice.analysis.requests.*
import com.openlattice.datastore.services.EdmManager
import com.openlattice.postgres.DataTables
import com.openlattice.postgres.PostgresColumn
import com.openlattice.postgres.PostgresTable
import com.openlattice.postgres.streams.BasePostgresIterable
import com.openlattice.postgres.streams.StatementHolderSupplier
import com.zaxxer.hikari.HikariDataSource
import org.slf4j.LoggerFactory
@Deprecated("Unused, needs rewrite")
class AssemblerQueryService(
private val edmService: EdmManager
) {
companion object {
private val logger = LoggerFactory.getLogger(AssemblerQueryService::class.java)
private const val SRC_TABLE_ALIAS = "SRC_TABLE"
private const val EDGE_TABLE_ALIAS = "EDGE_TABLE"
private const val DST_TABLE_ALIAS = "DST_TABLE"
}
fun simpleAggregation(
hds: HikariDataSource,
srcEntitySetName: String, edgeEntitySetName: String, dstEntitySetName: String,
srcGroupColumns: List<String>, edgeGroupColumns: List<String>, dstGroupColumns: List<String>,
srcAggregates: Map<String, List<AggregationType>>, edgeAggregates: Map<String, List<AggregationType>>, dstAggregates: Map<String, List<AggregationType>>,
calculations: Set<Calculation>,
srcFilters: Map<String, List<Filter>>, edgeFilters: Map<String, List<Filter>>, dstFilters: Map<String, List<Filter>>
): Iterable<Map<String, Any?>> {
// Groupings
val srcGroupColAliases = mutableListOf<String>()
val edgeGroupColAliases = mutableListOf<String>()
val dstGroupColAliases = mutableListOf<String>()
val srcGroupCols = srcGroupColumns.map {
val alias = "${SRC_TABLE_ALIAS}_$it"
srcGroupColAliases.add(alias)
"$SRC_TABLE_ALIAS.${DataTables.quote(it)} AS ${DataTables.quote(alias)}"
}
val edgeGroupCols = edgeGroupColumns.map {
val alias = "${EDGE_TABLE_ALIAS}_$it"
edgeGroupColAliases.add(alias)
"$EDGE_TABLE_ALIAS.${DataTables.quote(it)} AS ${DataTables.quote(alias)}"
}
val dstGroupCols = dstGroupColumns.map {
val alias = "${DST_TABLE_ALIAS}_$it"
edgeGroupColAliases.add(alias)
"$DST_TABLE_ALIAS.${DataTables.quote(it)} AS ${DataTables.quote(alias)}"
}
val cols = (srcGroupCols + edgeGroupCols + dstGroupCols).joinToString(", ")
// Aggregations
val srcAggregateAliases = mutableListOf<String>()
val srcAggregateCols = srcAggregates.flatMap { aggregate ->
val quotedColumn = DataTables.quote(aggregate.key)
val aggregateColumn = "$SRC_TABLE_ALIAS.$quotedColumn"
aggregate.value.map { aggregateFun ->
val aggregateAlias = "${SRC_TABLE_ALIAS}_${aggregate.key}_$aggregateFun"
srcAggregateAliases.add(aggregateAlias)
"$aggregateFun( $aggregateColumn ) AS ${DataTables.quote(aggregateAlias)}"
}
}
val edgeAggregateAliases = mutableListOf<String>()
val edgeAggregateCols = edgeAggregates.flatMap { aggregate ->
val quotedColumn = DataTables.quote(aggregate.key)
val aggregateColumn = "$EDGE_TABLE_ALIAS.$quotedColumn"
aggregate.value.map { aggregateFun ->
val aggregateAlias = "${EDGE_TABLE_ALIAS}_${aggregate.key}_$aggregateFun"
edgeAggregateAliases.add(aggregateAlias)
"$aggregateFun( $aggregateColumn ) AS ${DataTables.quote(aggregateAlias)}"
}
}
val dstAggregateAliases = mutableListOf<String>()
val dstAggregateCols = dstAggregates.flatMap { aggregate ->
val quotedColumn = DataTables.quote(aggregate.key)
val aggregateColumn = "$DST_TABLE_ALIAS.$quotedColumn"
aggregate.value.map { aggregateFun ->
val aggregateAlias = "${DST_TABLE_ALIAS}_${aggregate.key}_$aggregateFun"
dstAggregateAliases.add(aggregateAlias)
"$aggregateFun( $aggregateColumn ) AS ${DataTables.quote(aggregateAlias)}"
}
}
// Calculations
val calculationAliases = mutableListOf<String>()
val calculationGroupCols = mutableListOf<String>()
val calculationSqls = calculations
.filter { it.calculationType.basseType == BaseCalculationTypes.DURATION }
.map {
val firstPropertyType = edmService.getPropertyTypeFqn(it.firstPropertyId.propertyTypeId).fullQualifiedNameAsString
val firstPropertyCol = mapOrientationToTableAlias(it.firstPropertyId.orientation) + "." + DataTables.quote(firstPropertyType)
val secondPropertyType = edmService.getPropertyTypeFqn(it.secondPropertyId.propertyTypeId).fullQualifiedNameAsString
val secondPropertyCol = mapOrientationToTableAlias(it.secondPropertyId.orientation) + "." + DataTables.quote(secondPropertyType)
calculationGroupCols.add(firstPropertyCol)
calculationGroupCols.add(secondPropertyCol)
val calculator = DurationCalculator(firstPropertyCol, secondPropertyCol)
val alias = "${it.calculationType}_${firstPropertyType}_$secondPropertyType"
calculationAliases.add(alias)
mapDurationCalcualtionsToSql(calculator, it.calculationType) + " AS ${DataTables.quote(alias)}"
}
// The query
val groupingColAliases = (srcGroupColAliases + edgeGroupColAliases + dstGroupColAliases)
.joinToString(", ") { DataTables.quote(it) } + if (calculationGroupCols.isNotEmpty()) {
calculationGroupCols.joinToString(", ", ", ", "")
} else {
""
}
// Filters
val srcFilterSqls = srcFilters.map {
val colName = " $SRC_TABLE_ALIAS.${DataTables.quote(it.key)} "
it.value.map {
it.asSql(colName)
}.joinToString(" AND ")
}
val edgeFilterSqls = edgeFilters.map {
val colName = " $EDGE_TABLE_ALIAS.${DataTables.quote(it.key)} "
it.value.map {
it.asSql(colName)
}.joinToString(" AND ")
}
val dstFilterSqls = dstFilters.map {
val colName = " $DST_TABLE_ALIAS.${DataTables.quote(it.key)} "
it.value.map {
it.asSql(colName)
}.joinToString(" AND ")
}
val allFilters = (srcFilterSqls + edgeFilterSqls + dstFilterSqls)
val filtersSql = if (allFilters.isNotEmpty()) allFilters.joinToString(" AND ", " AND ", " ") else ""
val aggregateCols = (srcAggregateCols + edgeAggregateCols + dstAggregateCols).joinToString(", ")
val calculationCols = if (calculationSqls.isNotEmpty()) ", " + calculationSqls.joinToString(", ") else ""
val simpleSql = simpleAggregationJoinSql(srcEntitySetName, edgeEntitySetName, dstEntitySetName,
cols, groupingColAliases, aggregateCols, calculationCols,
filtersSql)
logger.info("Simple assembly aggregate query:\n$simpleSql")
return BasePostgresIterable(StatementHolderSupplier(hds, simpleSql)) { rs ->
((srcGroupColAliases + edgeGroupColAliases + dstGroupColAliases).map { col ->
val arrayVal = rs.getArray(col)
col to if (arrayVal == null) {
null
} else {
(rs.getArray(col).array as Array<Any>)[0]
}
} + (srcAggregateAliases + edgeAggregateAliases + dstAggregateAliases).map { col ->
col to rs.getObject(col)
} + (calculationAliases).map { col ->
col to rs.getObject(col)
}).toMap()
}
}
private fun simpleAggregationJoinSql(srcEntitySetName: String, edgeEntitySetName: String, dstEntitySetName: String,
cols: String, groupingColAliases: String, aggregateCols: String, calculationCols: String,
filtersSql: String): String {
return "SELECT $cols, $aggregateCols $calculationCols FROM ${AssemblerConnectionManager.OPENLATTICE_SCHEMA}.${PostgresTable.E.name} " +
"INNER JOIN ${AssemblerConnectionManager.entitySetNameTableName(srcEntitySetName)} AS $SRC_TABLE_ALIAS USING( ${PostgresColumn.ID.name} ) " +
"INNER JOIN ${AssemblerConnectionManager.entitySetNameTableName(edgeEntitySetName)} AS $EDGE_TABLE_ALIAS ON( $EDGE_TABLE_ALIAS.${PostgresColumn.ID.name} = ${PostgresColumn.EDGE_COMP_2.name} ) " +
"INNER JOIN ${AssemblerConnectionManager.entitySetNameTableName(dstEntitySetName)} AS $DST_TABLE_ALIAS ON( $DST_TABLE_ALIAS.${PostgresColumn.ID.name} = ${PostgresColumn.EDGE_COMP_1.name} ) " +
"WHERE ${PostgresColumn.COMPONENT_TYPES.name} = 0 $filtersSql " +
"GROUP BY ($groupingColAliases)"
}
private fun mapOrientationToTableAlias(orientation: Orientation): String {
return when (orientation) {
Orientation.SRC -> SRC_TABLE_ALIAS
Orientation.EDGE -> EDGE_TABLE_ALIAS
Orientation.DST -> DST_TABLE_ALIAS
}
}
private fun mapDurationCalcualtionsToSql(durationCalculation: DurationCalculator, calculationType: CalculationType): String {
return when (calculationType) {
CalculationType.DURATION_YEAR -> durationCalculation.numberOfYears()
CalculationType.DURATION_DAY -> durationCalculation.numberOfDays()
CalculationType.DURATION_HOUR -> durationCalculation.numberOfHours()
}
}
private class DurationCalculator(private val endColumn: String, private val startColumn: String) {
fun firstStart(): String {
return "(SELECT unnest($startColumn) ORDER BY 1 LIMIT 1)"
}
fun lastEnd(): String {
return "(SELECT unnest($endColumn) ORDER BY 1 DESC LIMIT 1)"
}
fun numberOfYears(): String {
return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600/24/365)"
}
fun numberOfDays(): String {
return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600/24)"
}
fun numberOfHours(): String {
return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600)"
}
}
}
| gpl-3.0 | 75a9950d018b344c71751eb7c2e1cdf7 | 46.207469 | 211 | 0.641206 | 4.963787 | false | false | false | false |
googlearchive/android-AutofillFramework | kotlinApp/Application/src/main/java/com/example/android/autofillframework/app/CreditCardActivity.kt | 4 | 3382 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.autofillframework.app
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ArrayAdapter
import com.example.android.autofillframework.R
import kotlinx.android.synthetic.main.credit_card_activity.clear
import kotlinx.android.synthetic.main.credit_card_activity.creditCardNumberField
import kotlinx.android.synthetic.main.credit_card_activity.expirationDay
import kotlinx.android.synthetic.main.credit_card_activity.expirationMonth
import kotlinx.android.synthetic.main.credit_card_activity.expirationYear
import kotlinx.android.synthetic.main.credit_card_activity.submit
import java.util.Calendar
class CreditCardActivity : AppCompatActivity() {
private val CC_EXP_YEARS_COUNT = 5
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.credit_card_activity)
// Create an ArrayAdapter using the string array and a default spinner layout
expirationDay.adapter = ArrayAdapter.createFromResource(this, R.array.day_array,
android.R.layout.simple_spinner_item).apply {
// Specify the layout to use when the list of choices appears
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
expirationMonth.adapter = ArrayAdapter.createFromResource(this, R.array.month_array,
android.R.layout.simple_spinner_item).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
val year = Calendar.getInstance().get(Calendar.YEAR)
val years = (0 until CC_EXP_YEARS_COUNT)
.map { Integer.toString(year + it) }
.toTypedArray<CharSequence>()
expirationYear.adapter = object : ArrayAdapter<CharSequence?>(this,
android.R.layout.simple_spinner_item, years) {
override fun getAutofillOptions() = years
}
submit.setOnClickListener { submitCcInfo() }
clear.setOnClickListener { resetFields() }
}
private fun resetFields() {
creditCardNumberField.setText("")
expirationDay.setSelection(0)
expirationMonth.setSelection(0)
expirationYear.setSelection(0)
}
/**
* Launches new Activity and finishes, triggering an autofill save request if the user entered
* any new data.
*/
private fun submitCcInfo() {
startActivity(WelcomeActivity.getStartActivityIntent(this))
finish()
}
companion object {
fun getStartActivityIntent(context: Context) =
Intent(context, CreditCardActivity::class.java)
}
}
| apache-2.0 | f7543678f0a4025a0f769e0d8c10de1a | 37.873563 | 98 | 0.71644 | 4.557951 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/loanrepayment/LoanRepaymentFragment.kt | 1 | 15872 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.loanrepayment
import android.content.DialogInterface
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.fragment.app.DialogFragment
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.google.gson.Gson
import com.jakewharton.fliptables.FlipTable
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MaterialDialog
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener
import com.mifos.objects.accounts.loan.LoanRepaymentRequest
import com.mifos.objects.accounts.loan.LoanRepaymentResponse
import com.mifos.objects.accounts.loan.LoanWithAssociations
import com.mifos.objects.templates.loans.LoanRepaymentTemplate
import com.mifos.utils.Constants
import com.mifos.utils.FragmentConstants
import com.mifos.utils.Utils
import javax.inject.Inject
class LoanRepaymentFragment : MifosBaseFragment(), OnDatePickListener, LoanRepaymentMvpView, DialogInterface.OnClickListener {
val LOG_TAG = javaClass.simpleName
@kotlin.jvm.JvmField
@BindView(R.id.rl_loan_repayment)
var rl_loan_repayment: RelativeLayout? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_clientName)
var tv_clientName: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_product_short_name)
var tv_loanProductShortName: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loanAccountNumber)
var tv_loanAccountNumber: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_in_arrears)
var tv_inArrears: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_amount_due)
var tv_amountDue: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_repayment_date)
var tv_repaymentDate: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_amount)
var et_amount: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_additional_payment)
var et_additionalPayment: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_fees)
var et_fees: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_total)
var tv_total: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_payment_type)
var sp_paymentType: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.bt_paynow)
var bt_paynow: Button? = null
@kotlin.jvm.JvmField
@Inject
var mLoanRepaymentPresenter: LoanRepaymentPresenter? = null
private lateinit var rootView: View
// Arguments Passed From the Loan Account Summary Fragment
private var clientName: String? = null
private var loanId: String? = null
private var loanAccountNumber: String? = null
private var loanProductName: String? = null
private var amountInArrears: Double? = null
private var paymentTypeOptionId = 0
private var mfDatePicker: DialogFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
arguments?.getParcelable<LoanWithAssociations>(Constants.LOAN_SUMMARY)?.let { loanWithAssociations ->
clientName = loanWithAssociations.clientName
loanAccountNumber = loanWithAssociations.accountNo
loanId = loanWithAssociations.id.toString()
loanProductName = loanWithAssociations.loanProductName
amountInArrears = loanWithAssociations.summary.totalOverdue
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_loan_repayment, container, false)
setToolbarTitle("Loan Repayment")
ButterKnife.bind(this, rootView)
mLoanRepaymentPresenter!!.attachView(this)
//This Method Checking LoanRepayment made before in Offline mode or not.
//If yes then User have to sync this first then he can able to make transaction.
//If not then User able to make LoanRepayment in Online or Offline.
checkLoanRepaymentStatusInDatabase()
return rootView
}
override fun checkLoanRepaymentStatusInDatabase() {
// Checking LoanRepayment Already made in Offline mode or Not.
mLoanRepaymentPresenter!!.checkDatabaseLoanRepaymentByLoanId(loanId!!.toInt())
}
override fun showLoanRepaymentExistInDatabase() {
//Visibility of ParentLayout GONE, If Repayment Already made in Offline Mode
rl_loan_repayment!!.visibility = View.GONE
MaterialDialog.Builder().init(activity)
.setTitle(R.string.sync_previous_transaction)
.setMessage(R.string.dialog_message_sync_transaction)
.setPositiveButton(R.string.dialog_action_ok, this)
.setCancelable(false)
.createMaterialDialog()
.show()
}
override fun onClick(dialog: DialogInterface, which: Int) {
if (DialogInterface.BUTTON_POSITIVE == which) {
requireActivity().supportFragmentManager.popBackStackImmediate()
}
}
override fun showLoanRepaymentDoesNotExistInDatabase() {
// This Method Inflating UI and Initializing the Loading LoadRepayment
// Template for transaction
inflateUI()
// Loading PaymentOptions.
mLoanRepaymentPresenter!!.loanLoanRepaymentTemplate(loanId!!.toInt())
}
/**
* This Method Setting UI and Initializing the Object, TextView or EditText.
*/
fun inflateUI() {
tv_clientName!!.text = clientName
tv_loanProductShortName!!.text = loanProductName
tv_loanAccountNumber!!.text = loanId
tv_inArrears!!.text = amountInArrears.toString()
//Setup Form with Default Values
et_amount!!.setText("0.0")
et_amount!!.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
try {
tv_total!!.text = calculateTotal().toString()
} catch (nfe: NumberFormatException) {
et_amount!!.setText("0")
} finally {
tv_total!!.text = calculateTotal().toString()
}
}
override fun afterTextChanged(editable: Editable) {}
})
et_additionalPayment!!.setText("0.0")
et_additionalPayment!!.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
try {
tv_total!!.text = calculateTotal().toString()
} catch (nfe: NumberFormatException) {
et_additionalPayment!!.setText("0")
} finally {
tv_total!!.text = calculateTotal().toString()
}
}
override fun afterTextChanged(editable: Editable) {}
})
et_fees!!.setText("0.0")
et_fees!!.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
try {
tv_total!!.text = calculateTotal().toString()
} catch (nfe: NumberFormatException) {
et_fees!!.setText("0")
} finally {
tv_total!!.text = calculateTotal().toString()
}
}
override fun afterTextChanged(editable: Editable) {}
})
inflateRepaymentDate()
tv_total!!.text = calculateTotal().toString()
}
/**
* Calculating the Total of the Amount, Additional Payment and Fee
*
* @return Total of the Amount + Additional Payment + Fee Amount
*/
fun calculateTotal(): Double {
return et_amount!!.text.toString().toDouble() + et_additionalPayment!!.text.toString().toDouble() + et_fees!!.text.toString().toDouble()
}
/**
* Setting the Repayment Date
*/
fun inflateRepaymentDate() {
mfDatePicker = MFDatePicker.newInsance(this)
tv_repaymentDate!!.text = MFDatePicker.getDatePickedAsString()
/*
TODO Add Validation to make sure :
1. Date Is in Correct Format
2. Date Entered is not greater than Date Today i.e Date is not in future
*/tv_repaymentDate!!.setOnClickListener { (mfDatePicker as MFDatePicker?)!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER) }
}
/**
* Whenever user click on Date Picker and in Result, setting Date in TextView.
*
* @param date Selected Date by Date picker
*/
override fun onDatePicked(date: String) {
tv_repaymentDate!!.text = date
}
/**
* Submitting the LoanRepayment after setting all arguments and Displaying the Dialog
* First, So that user make sure. He/She wanna make LoanRepayment
*/
@OnClick(R.id.bt_paynow)
fun onPayNowButtonClicked() {
try {
val headers = arrayOf("Field", "Value")
val data = arrayOf(arrayOf("Account Number", loanAccountNumber), arrayOf<String?>("Repayment Date", tv_repaymentDate!!.text.toString()), arrayOf<String?>("Payment Type", sp_paymentType!!.selectedItem.toString()), arrayOf<String?>("Amount", et_amount!!.text.toString()), arrayOf<String?>("Addition Payment", et_additionalPayment!!.text.toString()), arrayOf<String?>("Fees", et_fees!!.text.toString()), arrayOf<String?>("Total", calculateTotal().toString()))
Log.d(LOG_TAG, FlipTable.of(headers, data))
val formReviewString = StringBuilder().append(data[0][0].toString() + " : " + data[0][1])
.append("\n")
.append(data[1][0].toString() + " : " + data[1][1])
.append("\n")
.append(data[2][0].toString() + " : " + data[2][1])
.append("\n")
.append(data[3][0].toString() + " : " + data[3][1])
.append("\n")
.append(data[4][0].toString() + " : " + data[4][1])
.append("\n")
.append(data[5][0].toString() + " : " + data[5][1])
.append("\n")
.append(data[6][0].toString() + " : " + data[6][1]).toString()
MaterialDialog.Builder().init(activity)
.setTitle(R.string.review_payment)
.setMessage(formReviewString)
.setPositiveButton(R.string.dialog_action_pay_now
) { dialog, which -> submitPayment() }
.setNegativeButton(R.string.dialog_action_back
) { dialog, which -> dialog.dismiss() }
.createMaterialDialog()
.show()
} catch (npe: NullPointerException) {
Toaster.show(rootView, "Please make sure every field has a value, before submitting " +
"repayment!")
}
}
/**
* Cancel button on Home UI
*/
@OnClick(R.id.bt_cancelPayment)
fun onCancelPaymentButtonClicked() {
requireActivity().supportFragmentManager.popBackStackImmediate()
}
/**
* Submit the Final LoanRepayment
*/
fun submitPayment() {
//TODO Implement a proper builder method here
val dateString = tv_repaymentDate!!.text.toString().replace("-", " ")
val request = LoanRepaymentRequest()
request.accountNumber = loanAccountNumber
request.paymentTypeId = paymentTypeOptionId.toString()
request.locale = "en"
request.transactionAmount = calculateTotal().toString()
request.dateFormat = "dd MM yyyy"
request.transactionDate = dateString
val builtRequest = Gson().toJson(request)
Log.i("LOG_TAG", builtRequest)
mLoanRepaymentPresenter!!.submitPayment(loanId!!.toInt(), request)
}
override fun showLoanRepayTemplate(loanRepaymentTemplate: LoanRepaymentTemplate?) {
/* Activity is null - Fragment has been detached; no need to do anything. */
if (activity == null) return
if (loanRepaymentTemplate != null) {
tv_amountDue!!.text = loanRepaymentTemplate.amount.toString()
inflateRepaymentDate()
val listOfPaymentTypes = Utils.getPaymentTypeOptions(loanRepaymentTemplate.paymentTypeOptions)
val paymentTypeAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, listOfPaymentTypes)
paymentTypeAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
sp_paymentType!!.adapter = paymentTypeAdapter
sp_paymentType!!.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
paymentTypeOptionId = loanRepaymentTemplate
.paymentTypeOptions[position].id
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
et_amount!!.setText((loanRepaymentTemplate
.principalPortion
+ loanRepaymentTemplate.interestPortion).toString())
et_additionalPayment!!.setText("0.0")
et_fees!!.setText(loanRepaymentTemplate
.feeChargesPortion.toString())
}
}
override fun showPaymentSubmittedSuccessfully(loanRepaymentResponse: LoanRepaymentResponse?) {
if (loanRepaymentResponse != null) {
Toaster.show(rootView, "Payment Successful, Transaction ID = " +
loanRepaymentResponse.resourceId)
}
requireActivity().supportFragmentManager.popBackStackImmediate()
}
override fun showError(errorMessage: Int) {
Toaster.show(rootView, errorMessage)
}
override fun showProgressbar(b: Boolean) {
if (b) {
rl_loan_repayment!!.visibility = View.GONE
showMifosProgressBar()
} else {
rl_loan_repayment!!.visibility = View.VISIBLE
hideMifosProgressBar()
}
}
override fun onDestroyView() {
super.onDestroyView()
mLoanRepaymentPresenter!!.detachView()
}
interface OnFragmentInteractionListener
companion object {
@kotlin.jvm.JvmStatic
fun newInstance(loanWithAssociations: LoanWithAssociations?): LoanRepaymentFragment {
val fragment = LoanRepaymentFragment()
val args = Bundle()
if (loanWithAssociations != null) {
args.putParcelable(Constants.LOAN_SUMMARY, loanWithAssociations)
fragment.arguments = args
}
return fragment
}
}
} | mpl-2.0 | 4520765b649465cbe9abaf930aa07883 | 40.015504 | 468 | 0.639491 | 4.877689 | false | false | false | false |
kotlin-es/kotlin-JFrame-standalone | 09-start-async-radiobutton-application/src/main/kotlin/components/textArea/TextAreaImpl.kt | 6 | 1711 | package components.progressBar
import utils.ThreadMain
import java.awt.Dimension
import java.util.concurrent.CompletableFuture
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTextArea
/**
* Created by vicboma on 05/12/16.
*/
class TextAreaImpl internal constructor(val _text: String) : JTextArea() , TextArea {
companion object {
var scrollPane : JScrollPane? = null
fun create(text: String): TextArea {
return TextAreaImpl(text)
}
}
init{
scrollPane = JScrollPane(this)
scrollPane?.setPreferredSize(Dimension(380, 100))
scrollPane?.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
this.lineWrap = true
this.wrapStyleWord = true
this.isEditable = false
this.alignmentX = JPanel.CENTER_ALIGNMENT
this.autoscrolls = true
for ( i in 0.._text.length-1) {
i.text()
}
}
override fun asyncUI() {
ThreadMain.asyncUI {
CompletableFuture.runAsync {
Thread.sleep(1500)
text = ""
for ( i in 0.._text.length-1) {
Thread.sleep(50)
i.text()
}
}.thenAcceptAsync {
asyncUI()
}
}
}
private fun isMod(a : Int, b :Int) = (a % b) == 0
public fun Int.text() = when {
//isMod(this,TextArea.MOD) -> caretPosition = getDocument().getLength()
else -> {
append(_text[this].toString())
caretPosition = getDocument().getLength()
}
}
override fun component() : JScrollPane? = scrollPane
}
| mit | 17c39b957ca83892ebf78f5ff6bcb7a7 | 24.537313 | 85 | 0.571011 | 4.538462 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/rac1/java/cat/xojan/random1/data/RemotePodcastRepository.kt | 2 | 1370 | package cat.xojan.random1.data
import cat.xojan.random1.domain.model.Podcast
import cat.xojan.random1.domain.model.PodcastData
import cat.xojan.random1.domain.repository.PodcastRepository
import io.reactivex.Single
class RemotePodcastRepository(private val service: ApiService): PodcastRepository {
private var hourPodcasts: Single<PodcastData>? = null
private var sectionPodcasts: Single<PodcastData>? = null
private var programId: String? = null
private var sectionId: String? = null
override fun getPodcasts(programId: String, sectionId: String?, refresh: Boolean)
: Single<List<Podcast>> {
val podcastData: Single<PodcastData>
if (sectionId != null) {
if (sectionPodcasts == null || refresh || programId != this.programId ||
sectionId != this.sectionId) {
sectionPodcasts = service.getPodcastData(programId, sectionId).cache()
}
podcastData = sectionPodcasts!!
} else {
if (hourPodcasts == null || refresh || programId != this.programId) {
hourPodcasts = service.getPodcastData(programId).cache()
}
podcastData = hourPodcasts!!
}
this.programId = programId
this.sectionId = sectionId
return podcastData.map { pd -> pd.toPodcasts(programId) }
}
} | mit | 010ddca5410a22ae0b4ce7eedaf1a25a | 38.171429 | 86 | 0.655474 | 4.724138 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/oneway/AddOnewayForm.kt | 1 | 4447 | package de.westnordost.streetcomplete.quests.oneway
import android.content.Context
import android.os.Bundle
import androidx.annotation.AnyThread
import android.view.View
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.databinding.QuestStreetSidePuzzleBinding
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.StreetSideRotater
import de.westnordost.streetcomplete.quests.oneway.OnewayAnswer.*
import de.westnordost.streetcomplete.util.getOrientationAtCenterLineInDegrees
import de.westnordost.streetcomplete.view.DrawableImage
import de.westnordost.streetcomplete.view.ResImage
import de.westnordost.streetcomplete.view.ResText
import de.westnordost.streetcomplete.view.RotatedCircleDrawable
import de.westnordost.streetcomplete.view.image_select.*
import kotlin.math.PI
class AddOnewayForm : AbstractQuestFormAnswerFragment<OnewayAnswer>() {
override val contentLayoutResId = R.layout.quest_street_side_puzzle
private val binding by contentViewBinding(QuestStreetSidePuzzleBinding::bind)
override val contentPadding = false
private var streetSideRotater: StreetSideRotater? = null
private var selection: OnewayAnswer? = null
private var mapRotation: Float = 0f
private var wayRotation: Float = 0f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState?.getString(SELECTION)?.let { selection = valueOf(it) }
wayRotation = (elementGeometry as ElementPolylinesGeometry).getOrientationAtCenterLineInDegrees()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.puzzleView.showOnlyRightSide()
binding.puzzleView.onClickSideListener = { showDirectionSelectionDialog() }
val defaultResId = R.drawable.ic_oneway_unknown
binding.puzzleView.setRightSideImage(ResImage(selection?.iconResId ?: defaultResId))
binding.puzzleView.setRightSideText(selection?.titleResId?.let { resources.getString(it) })
if (selection == null && !HAS_SHOWN_TAP_HINT) {
binding.puzzleView.showRightSideTapHint()
HAS_SHOWN_TAP_HINT = true
}
streetSideRotater = StreetSideRotater(
binding.puzzleView,
binding.littleCompass.root,
elementGeometry as ElementPolylinesGeometry
)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
selection?.let { outState.putString(SELECTION, it.name) }
}
override fun isFormComplete() = selection != null
override fun onClickOk() {
applyAnswer(selection!!)
}
@AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) {
streetSideRotater?.onMapOrientation(rotation, tilt)
mapRotation = (rotation * 180 / PI).toFloat()
}
private fun showDirectionSelectionDialog() {
val ctx = context ?: return
val items = OnewayAnswer.values().map { it.toItem(ctx, wayRotation + mapRotation) }
ImageListPickerDialog(ctx, items, R.layout.labeled_icon_button_cell, 3) { selected ->
val oneway = selected.value!!
binding.puzzleView.replaceRightSideImage(ResImage(oneway.iconResId))
binding.puzzleView.setRightSideText(resources.getString(oneway.titleResId))
selection = oneway
checkIsFormComplete()
}.show()
}
companion object {
private const val SELECTION = "selection"
private var HAS_SHOWN_TAP_HINT = false
}
}
private fun OnewayAnswer.toItem(context: Context, rotation: Float): DisplayItem<OnewayAnswer> {
val drawable = RotatedCircleDrawable(context.getDrawable(iconResId)!!)
drawable.rotation = rotation
return Item2(this, DrawableImage(drawable), ResText(titleResId))
}
private val OnewayAnswer.titleResId: Int get() = when(this) {
FORWARD -> R.string.quest_oneway2_dir
BACKWARD -> R.string.quest_oneway2_dir
NO_ONEWAY -> R.string.quest_oneway2_no_oneway
}
private val OnewayAnswer.iconResId: Int get() = when(this) {
FORWARD -> R.drawable.ic_oneway_lane
BACKWARD -> R.drawable.ic_oneway_lane_reverse
NO_ONEWAY -> R.drawable.ic_oneway_lane_no
}
| gpl-3.0 | 8a7fc0be4e0028c0bc89cc0099daaaa8 | 37.008547 | 105 | 0.736901 | 4.751068 | false | false | false | false |
Kotlin/kotlinx.serialization | core/commonTest/src/kotlinx/serialization/PolymorphismTestData.kt | 1 | 900 | /*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization
import kotlinx.serialization.modules.*
import kotlin.native.concurrent.*
@Serializable
open class PolyBase(val id: Int) {
override fun hashCode(): Int {
return id
}
override fun toString(): String {
return "PolyBase(id=$id)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as PolyBase
if (id != other.id) return false
return true
}
}
@Serializable
data class PolyDerived(val s: String) : PolyBase(1)
@SharedImmutable
val BaseAndDerivedModule = SerializersModule {
polymorphic(PolyBase::class, PolyBase.serializer()) {
subclass(PolyDerived.serializer())
}
}
| apache-2.0 | b10ad4897aaa1ceac996eaaeebada1ba | 22.684211 | 102 | 0.66 | 4.035874 | false | false | false | false |
FHannes/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUAnnotation.kt | 8 | 2349 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUNamedExpression
class JavaUAnnotation(
override val psi: PsiAnnotation,
override val uastParent: UElement?
) : UAnnotation {
override val qualifiedName: String?
get() = psi.qualifiedName
override val attributeValues: List<UNamedExpression> by lz {
val context = getUastContext()
val attributes = psi.parameterList.attributes
attributes.map { attribute -> JavaUNamedExpression(attribute, this) }
}
override fun resolve(): PsiClass? = psi.nameReferenceElement?.resolve() as? PsiClass
override fun findAttributeValue(name: String?): UExpression? {
val context = getUastContext()
val attributeValue = psi.findAttributeValue(name) ?: return null
return context.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression
}
override fun findDeclaredAttributeValue(name: String?): UExpression? {
val context = getUastContext()
val attributeValue = psi.findDeclaredAttributeValue(name) ?: return null
return context.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression
}
companion object {
@JvmStatic
fun wrap(annotation: PsiAnnotation): UAnnotation = JavaUAnnotation(annotation, null)
@JvmStatic
fun wrap(annotations: List<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) }
@JvmStatic
fun wrap(annotations: Array<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) }
}
} | apache-2.0 | d50d8b16e01f6220f0d296787038db91 | 37.52459 | 118 | 0.721584 | 4.843299 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/connection/RealConnectionPool.kt | 3 | 8407 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeUnit
import okhttp3.Address
import okhttp3.ConnectionPool
import okhttp3.Route
import okhttp3.internal.assertThreadHoldsLock
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.Task
import okhttp3.internal.concurrent.TaskQueue
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.connection.RealCall.CallReference
import okhttp3.internal.okHttpName
import okhttp3.internal.platform.Platform
class RealConnectionPool(
taskRunner: TaskRunner,
/** The maximum number of idle connections for each address. */
private val maxIdleConnections: Int,
keepAliveDuration: Long,
timeUnit: TimeUnit
) {
private val keepAliveDurationNs: Long = timeUnit.toNanos(keepAliveDuration)
private val cleanupQueue: TaskQueue = taskRunner.newQueue()
private val cleanupTask = object : Task("$okHttpName ConnectionPool") {
override fun runOnce() = cleanup(System.nanoTime())
}
/**
* Holding the lock of the connection being added or removed when mutating this, and check its
* [RealConnection.noNewExchanges] property. This defends against races where a connection is
* simultaneously adopted and removed.
*/
private val connections = ConcurrentLinkedQueue<RealConnection>()
init {
// Put a floor on the keep alive duration, otherwise cleanup will spin loop.
require(keepAliveDuration > 0L) { "keepAliveDuration <= 0: $keepAliveDuration" }
}
fun idleConnectionCount(): Int {
return connections.count {
synchronized(it) { it.calls.isEmpty() }
}
}
fun connectionCount(): Int {
return connections.size
}
/**
* Attempts to acquire a recycled connection to [address] for [call]. Returns true if a connection
* was acquired.
*
* If [routes] is non-null these are the resolved routes (ie. IP addresses) for the connection.
* This is used to coalesce related domains to the same HTTP/2 connection, such as `square.com`
* and `square.ca`.
*/
fun callAcquirePooledConnection(
address: Address,
call: RealCall,
routes: List<Route>?,
requireMultiplexed: Boolean
): Boolean {
for (connection in connections) {
synchronized(connection) {
if (requireMultiplexed && !connection.isMultiplexed) return@synchronized
if (!connection.isEligible(address, routes)) return@synchronized
call.acquireConnectionNoEvents(connection)
return true
}
}
return false
}
fun put(connection: RealConnection) {
connection.assertThreadHoldsLock()
connections.add(connection)
cleanupQueue.schedule(cleanupTask)
}
/**
* Notify this pool that [connection] has become idle. Returns true if the connection has been
* removed from the pool and should be closed.
*/
fun connectionBecameIdle(connection: RealConnection): Boolean {
connection.assertThreadHoldsLock()
return if (connection.noNewExchanges || maxIdleConnections == 0) {
connection.noNewExchanges = true
connections.remove(connection)
if (connections.isEmpty()) cleanupQueue.cancelAll()
true
} else {
cleanupQueue.schedule(cleanupTask)
false
}
}
fun evictAll() {
val i = connections.iterator()
while (i.hasNext()) {
val connection = i.next()
val socketToClose = synchronized(connection) {
if (connection.calls.isEmpty()) {
i.remove()
connection.noNewExchanges = true
return@synchronized connection.socket()
} else {
return@synchronized null
}
}
socketToClose?.closeQuietly()
}
if (connections.isEmpty()) cleanupQueue.cancelAll()
}
/**
* Performs maintenance on this pool, evicting the connection that has been idle the longest if
* either it has exceeded the keep alive limit or the idle connections limit.
*
* Returns the duration in nanoseconds to sleep until the next scheduled call to this method.
* Returns -1 if no further cleanups are required.
*/
fun cleanup(now: Long): Long {
var inUseConnectionCount = 0
var idleConnectionCount = 0
var longestIdleConnection: RealConnection? = null
var longestIdleDurationNs = Long.MIN_VALUE
// Find either a connection to evict, or the time that the next eviction is due.
for (connection in connections) {
synchronized(connection) {
// If the connection is in use, keep searching.
if (pruneAndGetAllocationCount(connection, now) > 0) {
inUseConnectionCount++
} else {
idleConnectionCount++
// If the connection is ready to be evicted, we're done.
val idleDurationNs = now - connection.idleAtNs
if (idleDurationNs > longestIdleDurationNs) {
longestIdleDurationNs = idleDurationNs
longestIdleConnection = connection
} else {
Unit
}
}
}
}
when {
longestIdleDurationNs >= this.keepAliveDurationNs
|| idleConnectionCount > this.maxIdleConnections -> {
// We've chosen a connection to evict. Confirm it's still okay to be evict, then close it.
val connection = longestIdleConnection!!
synchronized(connection) {
if (connection.calls.isNotEmpty()) return 0L // No longer idle.
if (connection.idleAtNs + longestIdleDurationNs != now) return 0L // No longer oldest.
connection.noNewExchanges = true
connections.remove(longestIdleConnection)
}
connection.socket().closeQuietly()
if (connections.isEmpty()) cleanupQueue.cancelAll()
// Clean up again immediately.
return 0L
}
idleConnectionCount > 0 -> {
// A connection will be ready to evict soon.
return keepAliveDurationNs - longestIdleDurationNs
}
inUseConnectionCount > 0 -> {
// All connections are in use. It'll be at least the keep alive duration 'til we run
// again.
return keepAliveDurationNs
}
else -> {
// No connections, idle or in use.
return -1
}
}
}
/**
* Prunes any leaked calls and then returns the number of remaining live calls on [connection].
* Calls are leaked if the connection is tracking them but the application code has abandoned
* them. Leak detection is imprecise and relies on garbage collection.
*/
private fun pruneAndGetAllocationCount(connection: RealConnection, now: Long): Int {
connection.assertThreadHoldsLock()
val references = connection.calls
var i = 0
while (i < references.size) {
val reference = references[i]
if (reference.get() != null) {
i++
continue
}
// We've discovered a leaked call. This is an application bug.
val callReference = reference as CallReference
val message = "A connection to ${connection.route().address.url} was leaked. " +
"Did you forget to close a response body?"
Platform.get().logCloseableLeak(message, callReference.callStackTrace)
references.removeAt(i)
connection.noNewExchanges = true
// If this was the last allocation, the connection is eligible for immediate eviction.
if (references.isEmpty()) {
connection.idleAtNs = now - keepAliveDurationNs
return 0
}
}
return references.size
}
companion object {
fun get(connectionPool: ConnectionPool): RealConnectionPool = connectionPool.delegate
}
}
| apache-2.0 | a7d427beab346539233511eb4feb1dcd | 32.763052 | 100 | 0.688474 | 4.793044 | false | false | false | false |
misaochan/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/upload/structure/depictions/DepictedItemTest.kt | 2 | 5661 | package fr.free.nrw.commons.upload.structure.depictions
import com.nhaarman.mockitokotlin2.mock
import depictedItem
import entity
import entityId
import fr.free.nrw.commons.wikidata.WikidataProperties
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.not
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.nullValue
import org.junit.Test
import place
import snak
import statement
import valueString
import wikiBaseEntityValue
class DepictedItemTest {
@Test
fun `name and description get user language label`() {
val depictedItem =
DepictedItem(entity(mapOf("en" to "label"), mapOf("en" to "description")))
assertThat(depictedItem.name, `is`("label"))
assertThat(depictedItem.description, `is`("description"))
}
@Test
fun `name and descriptions get first language label if user language not present`() {
val depictedItem = DepictedItem(entity(mapOf("" to "label"), mapOf("" to "description")))
assertThat(depictedItem.name, `is`("label"))
assertThat(depictedItem.description, `is`("description"))
}
@Test
fun `name and descriptions get empty if nothing present`() {
val depictedItem = DepictedItem(entity())
assertThat(depictedItem.name, `is`(""))
assertThat(depictedItem.description, `is`(""))
}
@Test
fun `image is empty with null statements`() {
assertThat(DepictedItem(entity(statements = null)).imageUrl, nullValue())
}
@Test
fun `image is empty with no image statement`() {
assertThat(DepictedItem(entity()).imageUrl, nullValue())
}
@Test
fun `image is empty with dataValue not of ValueString type`() {
assertThat(
DepictedItem(
entity(
statements = mapOf(
WikidataProperties.IMAGE.propertyName to listOf(statement(snak(dataValue = mock())))
)
)
).imageUrl,
nullValue()
)
}
@Test
fun `image is not empty with dataValue of ValueString type`() {
assertThat(
DepictedItem(
entity(
statements = mapOf(
WikidataProperties.IMAGE.propertyName to listOf(
statement(snak(dataValue = valueString("prefix: example_")))
)
)
)
).imageUrl,
`is`("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/_example_/70px-_example_")
)
}
@Test
fun `instancesOf maps EntityIds to ids`() {
assertThat(
DepictedItem(
entity(
statements = mapOf(
WikidataProperties.INSTANCE_OF.propertyName to listOf(
statement(snak(dataValue = valueString("prefix: example_"))),
statement(snak(dataValue = entityId(wikiBaseEntityValue(id = "1")))),
statement(snak(dataValue = entityId(wikiBaseEntityValue(id = "2"))))
)
)
)
).instanceOfs,
`is`(listOf("1", "2")))
}
@Test
fun `instancesOf is empty with no values`() {
assertThat(DepictedItem(entity()).instanceOfs, `is`(emptyList()))
}
@Test
fun `commonsCategory maps ValueString to strings`() {
assertThat(
DepictedItem(
entity(
statements = mapOf(
WikidataProperties.COMMONS_CATEGORY.propertyName to listOf(
statement(snak(dataValue = valueString("1"))),
statement(snak(dataValue = valueString("2")))
)
)
)
).commonsCategories,
`is`(listOf("1", "2")))
}
@Test
fun `commonsCategory is empty with no values`() {
assertThat(DepictedItem(entity()).commonsCategories, `is`(emptyList()))
}
@Test
fun `isSelected is false at creation`() {
assertThat(DepictedItem(entity()).isSelected, `is`(false))
}
@Test
fun `id is entityId`() {
assertThat(DepictedItem(entity(id = "1")).id, `is`("1"))
}
@Test
fun `place constructor uses place name and longDescription`() {
val depictedItem = DepictedItem(entity(), place(name = "1", longDescription = "2"))
assertThat(depictedItem.name, `is`("1"))
assertThat(depictedItem.description, `is`("2"))
}
@Test
fun `same object is Equal`() {
val depictedItem = depictedItem()
assertThat(depictedItem == depictedItem, `is`(true))
}
@Test
fun `different type is not Equal`() {
assertThat(depictedItem().equals(Unit), `is`(false))
}
@Test
fun `if names are equal is Equal`() {
assertThat(
depictedItem(name="a", id = "0") == depictedItem(name="a", id = "1"),
`is`(true))
}
@Test
fun `if names are not equal is not Equal`() {
assertThat(
depictedItem(name="a") == depictedItem(name="b"),
`is`(false))
}
@Test
fun `hashCode returns same values for objects with same name`() {
assertThat(depictedItem(name="a").hashCode(), `is`(depictedItem(name="a").hashCode()))
}
@Test
fun `hashCode returns different values for objects with different name`() {
assertThat(depictedItem(name="a").hashCode(), not(depictedItem(name="b").hashCode()))
}
}
| apache-2.0 | f19baae194f9bcc24aa84d9a221d6a3f | 30.803371 | 108 | 0.565978 | 5.009735 | false | true | false | false |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/common/v2/stream/AbstractFlowControlStrategy.kt | 1 | 3914 | package com.fireflysource.net.http.common.v2.stream
import com.fireflysource.common.sys.SystemLogger
import com.fireflysource.net.http.common.HttpConfig.DEFAULT_WINDOW_SIZE
import com.fireflysource.net.http.common.v2.frame.WindowUpdateFrame
abstract class AbstractFlowControlStrategy(
protected var initialStreamRecvWindow: Int = DEFAULT_WINDOW_SIZE
) : FlowControl {
companion object {
private val log = SystemLogger.create(AbstractFlowControlStrategy::class.java)
}
private var initialStreamSendWindow: Int = DEFAULT_WINDOW_SIZE
override fun onStreamCreated(stream: Stream) {
val http2Stream = stream as AsyncHttp2Stream
http2Stream.updateSendWindow(initialStreamSendWindow)
http2Stream.updateRecvWindow(initialStreamRecvWindow)
}
override fun onStreamDestroyed(stream: Stream) {
}
override fun updateInitialStreamWindow(
http2Connection: Http2Connection,
initialStreamWindow: Int,
local: Boolean
) {
val previousInitialStreamWindow: Int
if (local) {
previousInitialStreamWindow = initialStreamRecvWindow
initialStreamRecvWindow = initialStreamWindow
} else {
previousInitialStreamWindow = initialStreamSendWindow
initialStreamSendWindow = initialStreamWindow
}
val delta = initialStreamWindow - previousInitialStreamWindow
if (delta == 0) return
http2Connection.streams.forEach { stream ->
if (local) {
val http2Stream = stream as AsyncHttp2Stream
http2Stream.updateRecvWindow(delta)
log.debug { "Updated initial stream recv window $previousInitialStreamWindow -> $initialStreamWindow for $http2Stream" }
} else {
(http2Connection as AsyncHttp2Connection).onWindowUpdate(stream, WindowUpdateFrame(stream.id, delta))
}
}
}
override fun onWindowUpdate(http2Connection: Http2Connection, stream: Stream?, frame: WindowUpdateFrame) {
if (frame.isStreamWindowUpdate) {
// The stream may have been removed concurrently.
if (stream != null && stream is AsyncHttp2Stream) {
stream.updateSendWindow(frame.windowDelta)
}
} else {
(http2Connection as AsyncHttp2Connection).updateSendWindow(frame.windowDelta)
}
}
override fun onDataReceived(http2Connection: Http2Connection, stream: Stream?, length: Int) {
val connection = http2Connection as AsyncHttp2Connection
var oldSize: Int = connection.updateRecvWindow(-length)
log.debug { "Data received, $length bytes, updated session recv window $oldSize -> ${oldSize - length} for $connection" }
if (stream != null && stream is AsyncHttp2Stream) {
oldSize = stream.updateRecvWindow(-length)
log.debug { "Data received, $length bytes, updated stream recv window $oldSize -> ${oldSize - length} for $stream" }
}
}
override fun onDataSending(stream: Stream, length: Int) {
if (length == 0) return
val http2Stream = stream as AsyncHttp2Stream
val connection = http2Stream.http2Connection as AsyncHttp2Connection
val oldSessionWindow = connection.updateSendWindow(-length)
val newSessionWindow = oldSessionWindow - length
log.debug { "Sending, session send window $oldSessionWindow -> $newSessionWindow for $connection" }
val oldStreamWindow = http2Stream.updateSendWindow(-length)
val newStreamWindow = oldStreamWindow - length
log.debug { "Sending, stream send window $oldStreamWindow -> $newStreamWindow for $stream" }
}
override fun onDataSent(stream: Stream, length: Int) {
}
override fun windowUpdate(http2Connection: Http2Connection, stream: Stream?, frame: WindowUpdateFrame) {
}
} | apache-2.0 | 2a5a0ba2f61fec4c335b9a1b9586edf1 | 40.210526 | 136 | 0.688298 | 4.948167 | false | false | false | false |
aglne/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/AppBootstrapListener.kt | 3 | 3517 | /**
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin
import com.mycollab.configuration.IDeploymentMode
import com.mycollab.core.Version
import com.mycollab.module.file.StorageUtils
import com.mycollab.module.user.service.BillingAccountService
import com.mycollab.spring.AppContextUtil
import com.mycollab.vaadin.TooltipHelper.TOOLTIP_ID
import com.mycollab.vaadin.ui.UIUtils
import com.vaadin.server.BootstrapFragmentResponse
import com.vaadin.server.BootstrapListener
import com.vaadin.server.BootstrapPageResponse
/**
* @author MyCollab Ltd.
* @since 3.0
*/
class AppBootstrapListener : BootstrapListener {
override fun modifyBootstrapFragment(response: BootstrapFragmentResponse) {}
override fun modifyBootstrapPage(response: BootstrapPageResponse) {
val request = response.request
val domain = UIUtils.getSubDomain(request)
val billingService = AppContextUtil.getSpringBean(BillingAccountService::class.java)
val account = billingService.getAccountByDomain(domain)
if (account != null) {
val favIconPath = StorageUtils.getFavIconPath(account.id!!, account.faviconpath)
response.document.head().getElementsByAttributeValue("rel", "shortcut icon").attr("href", favIconPath)
response.document.head().getElementsByAttributeValue("rel", "icon").attr("href", favIconPath)
}
response.document.head().append("<meta name=\"robots\" content=\"nofollow\" />")
val deploymentMode = AppContextUtil.getSpringBean(IDeploymentMode::class.java)
response.document.head()
.append("<script type=\"text/javascript\" src=\"${deploymentMode.getCdnUrl()}js/jquery-2.1.4.min.js\"></script>")
response.document.head()
.append("<script type=\"text/javascript\" src=\"${deploymentMode.getCdnUrl()}js/stickytooltip-1.0.2.js?v=${Version.getVersion()}\"></script>")
response.document.head()
.append("<script type=\"text/javascript\" src=\"${deploymentMode.getCdnUrl()}js/common-1.0.0.js?v=${Version.getVersion()}\"></script>")
val div1 = response.document.body().appendElement("div")
div1.attr("id", "div1$TOOLTIP_ID")
div1.attr("class", "stickytooltip")
val div12 = div1.appendElement("div")
div12.attr("style", "padding:5px")
val div13 = div12.appendElement("div")
div13.attr("id", "div13$TOOLTIP_ID")
div13.attr("class", "atip")
div13.attr("style", "width:550px")
val div14 = div13.appendElement("div")
div14.attr("id", "div14$TOOLTIP_ID")
val linkToTop = response.document.body().appendElement("a")
linkToTop.attr("href", "#")
linkToTop.attr("id", "linkToTop")
linkToTop.append("<iron-icon icon=\"vaadin:vaadin-h\"></iron-icon>")
}
} | agpl-3.0 | a902e2b29eb9e943f9bf8e5060d999f2 | 42.419753 | 158 | 0.695961 | 4.170819 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutorManager.kt | 1 | 3786 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.EventDispatcher
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException
import java.awt.Component
import java.util.*
/**
* Allows to acquire API executor without exposing the auth token to external code
*/
class GithubApiRequestExecutorManager(private val authenticationManager: GithubAuthenticationManager,
private val requestExecutorFactory: GithubApiRequestExecutor.Factory) {
@CalledInAwt
fun getExecutor(account: GithubAccount, project: Project): GithubApiRequestExecutor? {
return authenticationManager.getOrRequestTokenForAccount(account, project)
?.let(requestExecutorFactory::create)
}
@CalledInAwt
fun getManagedHolder(account: GithubAccount, project: Project): ManagedHolder? {
val requestExecutor = getExecutor(account, project) ?: return null
val holder = ManagedHolder(account, requestExecutor)
ApplicationManager.getApplication().messageBus.connect(holder).subscribe(GithubAccountManager.ACCOUNT_TOKEN_CHANGED_TOPIC, holder)
return holder
}
@CalledInAwt
fun getExecutor(account: GithubAccount, parentComponent: Component): GithubApiRequestExecutor? {
return authenticationManager.getOrRequestTokenForAccount(account, null, parentComponent)
?.let(requestExecutorFactory::create)
}
@CalledInAwt
@Throws(GithubMissingTokenException::class)
fun getExecutor(account: GithubAccount): GithubApiRequestExecutor {
return authenticationManager.getTokenForAccount(account)?.let(requestExecutorFactory::create)
?: throw GithubMissingTokenException(account)
}
inner class ManagedHolder internal constructor(private val account: GithubAccount, initialExecutor: GithubApiRequestExecutor)
: Disposable, AccountTokenChangedListener {
private var isDisposed = false
var executor: GithubApiRequestExecutor = initialExecutor
@CalledInAny
get() {
if (isDisposed) throw IllegalStateException("Already disposed")
return field
}
@CalledInAwt
internal set(value) {
field = value
eventDispatcher.multicaster.executorChanged()
}
private val eventDispatcher = EventDispatcher.create(ExecutorChangeListener::class.java)
override fun tokenChanged(account: GithubAccount) {
if (account == this.account) runInEdt {
try {
executor = getExecutor(account)
}
catch (e: GithubMissingTokenException) {
//token is missing, so content will be closed anyway
}
}
}
fun addListener(listener: ExecutorChangeListener, disposable: Disposable) = eventDispatcher.addListener(listener, disposable)
override fun dispose() {
isDisposed = true
}
}
interface ExecutorChangeListener : EventListener {
fun executorChanged()
}
companion object {
@JvmStatic
fun getInstance(): GithubApiRequestExecutorManager = service()
}
} | apache-2.0 | a6eb32a98de40653cc9db26de6d252e7 | 38.447917 | 140 | 0.768621 | 5.486957 | false | false | false | false |
vindkaldr/libreplicator | libreplicator-core/src/test/kotlin/org/libreplicator/core/journal/file/DefaultFileHandlerTest.kt | 2 | 5132 | /*
* Copyright (C) 2016 Mihály Szabó
*
* 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 org.libreplicator.core.journal.file
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.isEmptyString
import org.junit.After
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
class DefaultFileHandlerTest {
private val FIRST_LINE = "first-line"
private val SECOND_LINE = "second-line"
private val NEW_LINE = "new-line"
private val NEW_DIRECTORY = "new-directory"
private lateinit var testDirectory: Path
private lateinit var file: Path
private lateinit var emptyFile: Path
private lateinit var notExistingFile: Path
private lateinit var notExistingDirectory: Path
private lateinit var fileHandler: FileHandler
@Before
fun setUp() {
testDirectory = createTestDirectory()
file = createFile()
emptyFile = createEmptyFile()
notExistingFile = initializeNotExistingFile()
notExistingDirectory = initializeNotExistingDirectory()
fileHandler = DefaultFileHandler()
}
@After
fun tearDown() {
removeTestDirectory()
}
@Test
fun createDirectory_createsDirectories_whenParentDirectoryNotExists() {
fileHandler.createDirectory(notExistingDirectory, NEW_DIRECTORY)
val newParentDirectory = notExistingDirectory.toFile()
assertThat(newParentDirectory.exists(), equalTo(true))
assertThat(newParentDirectory.isDirectory, equalTo(true))
val newDirectory = notExistingDirectory.resolve(NEW_DIRECTORY).toFile()
assertThat(newDirectory.exists(), equalTo(true))
assertThat(newDirectory.isDirectory, equalTo(true))
}
@Test
fun createDirectory_createsDirectory() {
fileHandler.createDirectory(testDirectory, NEW_DIRECTORY)
val newDirectory = testDirectory.resolve(NEW_DIRECTORY).toFile()
assertThat(newDirectory.exists(), equalTo(true))
assertThat(newDirectory.isDirectory, equalTo(true))
}
@Test(expected = NoSuchFileException::class)
fun readFirstLine_throwsException_whenFileNotExists() {
fileHandler.readFirstLine(notExistingFile)
}
@Test
fun readFistLine_returnsEmptyString_whenFileIsEmpty() {
assertThat(fileHandler.readFirstLine(emptyFile), isEmptyString())
}
@Test
fun readFirstLine_returnsFirstLine() {
assertThat(fileHandler.readFirstLine(file), equalTo(FIRST_LINE))
}
@Test
fun write_createsFileAndWritesLine_whenFileNotExists() {
fileHandler.write(notExistingFile, FIRST_LINE)
assertThat(Files.readAllLines(notExistingFile).first(), equalTo(FIRST_LINE))
}
@Test
fun write_writesLineIntoEmptyFile() {
fileHandler.write(emptyFile, FIRST_LINE)
val lines = Files.readAllLines(emptyFile)
assertThat(lines.size, equalTo(1))
assertThat(lines.first(), equalTo(FIRST_LINE))
}
@Test
fun write_truncatesExistingFileAndWritesLine() {
fileHandler.write(file, NEW_LINE)
val lines = Files.readAllLines(file)
assertThat(lines.size, equalTo(1))
assertThat(lines.first(), equalTo(NEW_LINE))
}
@Test(expected = NoSuchFileException::class)
fun move_throwsException_whenSourceNotExists() {
fileHandler.move(notExistingFile, emptyFile)
}
@Test
fun move_movesFile() {
fileHandler.move(file, emptyFile)
assertThat(Files.readAllLines(emptyFile), equalTo(listOf(FIRST_LINE, SECOND_LINE)))
}
private fun createTestDirectory(): Path {
return Files.createTempDirectory("libreplicator-test-file-handler-")
}
private fun createFile(): Path {
val file = testDirectory.resolve("file")
Files.write(file, listOf(FIRST_LINE, SECOND_LINE))
return file
}
private fun createEmptyFile(): Path {
val file = testDirectory.resolve("empty-file")
file.toFile().createNewFile()
return file
}
private fun initializeNotExistingFile(): Path {
return testDirectory.resolve("not-existing-file")
}
private fun initializeNotExistingDirectory(): Path {
return testDirectory.resolve("not-existing-directory")
}
private fun removeTestDirectory() {
testDirectory.toFile().deleteRecursively()
}
}
| gpl-3.0 | a9a36d2f7e20e7fd1c6bc84346ba3604 | 29.535714 | 91 | 0.697661 | 4.672131 | false | true | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/SpriteAnimation.kt | 1 | 2295 | package com.soywiz.korge.view
import com.soywiz.kds.*
import com.soywiz.klock.*
import com.soywiz.kmem.umod
import com.soywiz.korim.atlas.*
import com.soywiz.korim.bitmap.Bitmap
import com.soywiz.korim.bitmap.BmpSlice
import com.soywiz.korim.bitmap.sliceWithSize
class SpriteAnimation constructor(
val sprites: List<BmpSlice>,
val defaultTimePerFrame: TimeSpan = TimeSpan.NIL
) {
companion object {
operator fun invoke(
spriteMap: Bitmap,
spriteWidth: Int = 16,
spriteHeight: Int = 16,
marginTop: Int = 0,
marginLeft: Int = 0,
columns: Int = 1,
rows: Int = 1,
offsetBetweenColumns: Int = 0,
offsetBetweenRows: Int = 0
): SpriteAnimation {
return SpriteAnimation(
FastArrayList<BmpSlice>().apply {
for (row in 0 until rows){
for (col in 0 until columns){
add(
spriteMap.sliceWithSize(
marginLeft + (spriteWidth + offsetBetweenColumns) * col,
marginTop + (spriteHeight + offsetBetweenRows) * row,
spriteWidth,
spriteHeight,
name = "slice$size"
)
)
}
}
}
)
}
}
val spriteStackSize: Int get() = sprites.size
val size: Int get() = sprites.size
val firstSprite: BmpSlice get() = sprites[0]
fun getSprite(index: Int): BmpSlice = sprites[index umod sprites.size]
operator fun get(index: Int) = getSprite(index)
}
fun Atlas.getSpriteAnimation(prefix: String = "", defaultTimePerFrame: TimeSpan = TimeSpan.NIL): SpriteAnimation =
SpriteAnimation(this.entries.filter { it.filename.startsWith(prefix) }.map { it.slice }.toFastList(), defaultTimePerFrame)
fun Atlas.getSpriteAnimation(regex: Regex, defaultTimePerFrame: TimeSpan = TimeSpan.NIL): SpriteAnimation =
SpriteAnimation(this.entries.filter { regex.matches(it.filename) }.map { it.slice }.toFastList(), defaultTimePerFrame)
| apache-2.0 | a54a72578f5b5ea60872a471956b1891 | 38.568966 | 126 | 0.55817 | 4.872611 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/component/list/GridViewList.kt | 1 | 1330 | package com.soywiz.korge.component.list
import com.soywiz.kds.iterators.*
import com.soywiz.korge.view.*
/*
Deprecated("")
class GridViewList(
val row0: View,
val row1: View,
val cellSelector: (View) -> Pair<View, View>,
val initialRows: Int,
val initialColumns: Int,
val container: Container = row0.parent!!
) {
private val rowsData = arrayListOf<ViewList>()
var columns: Int = initialColumns
set(value) {
field = value
update()
}
var rows: Int = initialRows
set(value) {
field = value
update()
}
private fun addItem() {
val n = container.numChildren
val item = row0.clone()
container += item
item.setMatrixInterpolated(n.toDouble(), row0.localMatrix, row1.localMatrix)
val select = cellSelector(item)
rowsData += ViewList(select.first, select.second, columns)
}
private fun removeLastItem() {
container.lastChild?.removeFromParent()
rowsData.removeAt(rowsData.size - 1)
}
fun update() {
while (rowsData.size < rows) addItem()
while (rowsData.size > rows) removeLastItem()
rowsData.fastForEach { rowData ->
rowData.length = columns
}
}
init {
container.removeChildren()
update()
}
val length: Int get() = columns * rows
operator fun get(row: Int): ViewList = this.rowsData[row]
operator fun get(row: Int, column: Int): View? = this[row][column]
}
*/
| apache-2.0 | a18d08bd6626df6d0eeb802dd1204271 | 21.166667 | 78 | 0.694737 | 3.189448 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/Card.kt | 1 | 19647 | /*
* Copyright (c) 2009 Daniel Svärd [email protected]>
* Copyright (c) 2011 Norbert Nagold [email protected]>
* Copyright (c) 2014 Houssam Salem <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki
import android.content.ContentValues
import android.text.TextUtils
import androidx.annotation.VisibleForTesting
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.CollectionHelper
import com.ichi2.anki.R
import com.ichi2.async.CancelListener
import com.ichi2.libanki.Consts.CARD_QUEUE
import com.ichi2.libanki.Consts.CARD_TYPE
import com.ichi2.libanki.TemplateManager.TemplateRenderContext.TemplateRenderOutput
import com.ichi2.libanki.stats.Stats
import com.ichi2.libanki.template.TemplateError
import com.ichi2.utils.Assert
import com.ichi2.utils.JSONObject
import com.ichi2.utils.LanguageUtil
import net.ankiweb.rsdroid.RustCleanup
import timber.log.Timber
import java.util.*
import java.util.concurrent.CancellationException
/**
* A Card is the ultimate entity subject to review; it encapsulates the scheduling parameters (from which to derive
* the next interval), the note it is derived from (from which field data is retrieved), its own ownership (which deck it
* currently belongs to), and the retrieval of presentation elements (filled-in templates).
*
* Card presentation has two components: the question (front) side and the answer (back) side. The presentation of the
* card is derived from the template of the card's Card Type. The Card Type is a component of the Note Type (see Models)
* that this card is derived from.
*
* This class is responsible for:
* - Storing and retrieving database entries that map to Cards in the Collection
* - Providing the HTML representation of the Card's question and answer
* - Recording the results of review (answer chosen, time taken, etc)
*
* It does not:
* - Generate new cards (see Collection)
* - Store the templates or the style sheet (see Models)
*
* Type: 0=new, 1=learning, 2=due
* Queue: same as above, and:
* -1=suspended, -2=user buried, -3=sched buried
* Due is used differently for different queues.
* - new queue: note id or random int
* - rev queue: integer day
* - lrn queue: integer timestamp
*/
open class Card : Cloneable {
// Needed for tests
var col: Collection
/**
* Time in MS when timer was started
*/
var timerStarted: Long
// Not in LibAnki. Record time spent reviewing in MS in order to restore when resuming.
private var elapsedTime: Long = 0
// BEGIN SQL table entries
@set:VisibleForTesting
var id: Long
var nid: Long = 0
var did: Long = 0
var ord = 0
var mod: Long = 0
var usn = 0
@get:CARD_TYPE
@CARD_TYPE
var type = 0
@get:CARD_QUEUE
@CARD_QUEUE
var queue = 0
var due: Long = 0
var ivl = 0
var factor = 0
var reps = 0
private set
var lapses = 0
var left = 0
var oDue: Long = 0
var oDid: Long = 0
private var flags = 0
private var data: String? = null
// END SQL table entries
@set:JvmName("setRenderOutput")
@get:JvmName("getRenderOutput")
protected var render_output: TemplateRenderOutput?
private var note: Note?
/** Used by Sched to determine which queue to move the card to after answering. */
var wasNew = false
/** Used by Sched to record the original interval in the revlog after answering. */
var lastIvl = 0
constructor(col: Collection) {
this.col = col
timerStarted = 0L
render_output = null
note = null
// to flush, set nid, ord, and due
this.id = this.col.time.timestampID(this.col.db, "cards")
did = 1
this.type = Consts.CARD_TYPE_NEW
queue = Consts.QUEUE_TYPE_NEW
ivl = 0
factor = 0
reps = 0
lapses = 0
left = 0
oDue = 0
oDid = 0
flags = 0
data = ""
}
constructor(col: Collection, id: Long) {
this.col = col
timerStarted = 0L
render_output = null
note = null
this.id = id
load()
}
fun load() {
col.db.query("SELECT * FROM cards WHERE id = ?", this.id).use { cursor ->
if (!cursor.moveToFirst()) {
throw WrongId(this.id, "card")
}
this.id = cursor.getLong(0)
nid = cursor.getLong(1)
did = cursor.getLong(2)
ord = cursor.getInt(3)
mod = cursor.getLong(4)
usn = cursor.getInt(5)
this.type = cursor.getInt(6)
queue = cursor.getInt(7)
due = cursor.getInt(8).toLong()
ivl = cursor.getInt(9)
factor = cursor.getInt(10)
reps = cursor.getInt(11)
lapses = cursor.getInt(12)
left = cursor.getInt(13)
oDue = cursor.getLong(14)
oDid = cursor.getLong(15)
flags = cursor.getInt(16)
data = cursor.getString(17)
}
render_output = null
note = null
}
@JvmOverloads
fun flush(changeModUsn: Boolean = true) {
if (changeModUsn) {
mod = col.time.intTime()
usn = col.usn()
}
assert(due < "4294967296".toLong())
col.db.execute(
"insert or replace into cards values " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
this.id,
nid,
did,
ord,
mod,
usn,
this.type,
queue,
due,
ivl,
factor,
reps,
lapses,
left,
oDue,
oDid,
flags,
data
)
col.log(this)
}
fun flushSched() {
mod = col.time.intTime()
usn = col.usn()
assert(due < "4294967296".toLong())
val values = ContentValues()
values.put("mod", mod)
values.put("usn", usn)
values.put("type", this.type)
values.put("queue", queue)
values.put("due", due)
values.put("ivl", ivl)
values.put("factor", factor)
values.put("reps", reps)
values.put("lapses", lapses)
values.put("left", left)
values.put("odue", oDue)
values.put("odid", oDid)
values.put("did", did)
// TODO: The update DB call sets mod=true. Verify if this is intended.
col.db.update("cards", values, "id = ?", arrayOf(java.lang.Long.toString(this.id)))
col.log(this)
}
@JvmOverloads
fun q(reload: Boolean = false, browser: Boolean = false): String {
return render_output(reload, browser).question_and_style()
}
fun a(): String {
return render_output().answer_and_style()
}
@RustCleanup("legacy")
fun css(): String {
return "<style>${render_output().css}</style>"
}
/**
* @throws net.ankiweb.rsdroid.exceptions.BackendInvalidInputException: If the card does not exist
*/
@JvmOverloads
@RustCleanup("move col.render_output back to Card once the java collection is removed")
open fun render_output(reload: Boolean = false, browser: Boolean = false): TemplateRenderOutput {
if (render_output == null || reload) {
render_output = col.render_output(this, reload, browser)
}
return render_output!!
}
open fun note(): Note {
return note(false)
}
open fun note(reload: Boolean): Note {
if (note == null || reload) {
note = col.getNote(nid)
}
return note!!
}
// not in upstream
open fun model(): Model {
return note().model()
}
fun template(): JSONObject {
val m = model()
return if (m.isStd) {
m.getJSONArray("tmpls").getJSONObject(ord)
} else {
model().getJSONArray("tmpls").getJSONObject(0)
}
}
fun startTimer() {
timerStarted = col.time.intTimeMS()
}
/**
* Time limit for answering in milliseconds.
*/
fun timeLimit(): Int {
val conf = col.decks.confForDid(if (!isInDynamicDeck) did else oDid)
return conf.getInt("maxTaken") * 1000
}
/*
* Time taken to answer card, in integer MS.
*/
fun timeTaken(): Int {
// Indeed an int. Difference between two big numbers is still small.
val total = (col.time.intTimeMS() - timerStarted).toInt()
return Math.min(total, timeLimit())
}
open val isEmpty: Boolean
get() = try {
Models.emptyCard(model(), ord, note().fields)
} catch (er: TemplateError) {
Timber.w("Card is empty because the card's template has an error: %s.", er.message(col.context))
true
}
/*
* ***********************************************************
* The methods below are not in LibAnki.
* ***********************************************************
*/
fun qSimple(): String {
return render_output(false).question_text
}
/*
* Returns the answer with anything before the <hr id=answer> tag removed
*/
val pureAnswer: String
get() {
val s = render_output(false).answer_text
val target = "<hr id=answer>"
val pos = s.indexOf(target)
return if (pos == -1) {
s
} else s.substring(pos + target.length).trim { it <= ' ' }
}
/**
* Save the currently elapsed reviewing time so it can be restored on resume.
*
* Use this method whenever a review session (activity) has been paused. Use the resumeTimer()
* method when the session resumes to start counting review time again.
*/
fun stopTimer() {
elapsedTime = col.time.intTimeMS() - timerStarted
}
/**
* Resume the timer that counts the time spent reviewing this card.
*
* Unlike the desktop client, AnkiDroid must pause and resume the process in the middle of
* reviewing. This method is required to keep track of the actual amount of time spent in
* the reviewer and *must* be called on resume before any calls to timeTaken() take place
* or the result of timeTaken() will be wrong.
*/
fun resumeTimer() {
timerStarted = col.time.intTimeMS() - elapsedTime
}
@VisibleForTesting
fun setReps(reps: Int): Int {
return reps.also { this.reps = it }
}
fun incrReps(): Int {
return ++reps
}
fun showTimer(): Boolean {
val options = col.decks.confForDid(if (!isInDynamicDeck) did else oDid)
return DeckConfig.parseTimerOpt(options, true)
}
public override fun clone(): Card {
return try {
super.clone() as Card
} catch (e: CloneNotSupportedException) {
throw RuntimeException(e)
}
}
override fun toString(): String {
val declaredFields = this.javaClass.declaredFields
val members: MutableList<String?> = ArrayList(declaredFields.size)
for (f in declaredFields) {
try {
// skip non-useful elements
if (SKIP_PRINT.contains(f.name)) {
continue
}
members.add(String.format("'%s': %s", f.name, f[this]))
} catch (e: IllegalAccessException) {
members.add(String.format("'%s': %s", f.name, "N/A"))
} catch (e: IllegalArgumentException) {
members.add(String.format("'%s': %s", f.name, "N/A"))
}
}
return TextUtils.join(", ", members)
}
override fun equals(other: Any?): Boolean {
return if (other is Card) {
this.id == other.id
} else super.equals(other)
}
override fun hashCode(): Int {
// Map a long to an int. For API>=24 you would just do `Long.hashCode(this.getId())`
return (this.id xor (this.id ushr 32)).toInt()
}
fun userFlag(): Int {
return intToFlag(flags)
}
@VisibleForTesting
fun setFlag(flag: Int) {
flags = flag
}
/** Should use [userFlag] */
fun internalGetFlags() = flags
fun setUserFlag(flag: Int) {
flags = setFlagInInt(flags, flag)
}
// not in Anki.
val dueString: String
get() {
var t = nextDue()
if (queue < 0) {
t = "($t)"
}
return t
}
// as in Anki aqt/browser.py
@VisibleForTesting
fun nextDue(): String {
val date: Long
val due = due
date = if (isInDynamicDeck) {
return AnkiDroidApp.getAppResources().getString(R.string.card_browser_due_filtered_card)
} else if (queue == Consts.QUEUE_TYPE_LRN) {
due
} else if (queue == Consts.QUEUE_TYPE_NEW || type == Consts.CARD_TYPE_NEW) {
return java.lang.Long.valueOf(due).toString()
} else if (queue == Consts.QUEUE_TYPE_REV || queue == Consts.QUEUE_TYPE_DAY_LEARN_RELEARN || type == Consts.CARD_TYPE_REV && queue < 0) {
val time = col.time.intTime()
val nbDaySinceCreation = due - col.sched.today
time + nbDaySinceCreation * Stats.SECONDS_PER_DAY
} else {
return ""
}
return LanguageUtil.getShortDateFormatFromS(date)
} // In Anki Desktop, a card with oDue <> 0 && oDid == 0 is not marked as dynamic.
/** Non libAnki */
val isInDynamicDeck: Boolean
get() = // In Anki Desktop, a card with oDue <> 0 && oDid == 0 is not marked as dynamic.
oDid != 0L
val isReview: Boolean
get() = this.type == Consts.CARD_TYPE_REV && queue == Consts.QUEUE_TYPE_REV
val isNew: Boolean
get() = this.type == Consts.CARD_TYPE_NEW
/** A cache represents an intermediary step between a card id and a card object. Creating a Card has some fixed cost
* in term of database access. Using an id has an unknown cost: none if the card is never accessed, heavy if the
* card is accessed a lot of time. CardCache ensure that the cost is paid at most once, by waiting for first access
* to load the data, and then saving them. Since CPU and RAM is usually less of a bottleneck than database access,
* it may often be worth using this cache.
*
* Beware that the card is loaded only once. Change in the database are not reflected, so use it only if you can
* safely assume that the card has not changed. That is
* long id;
* Card card = col.getCard(id);
* ....
* Card card2 = col.getCard(id);
* is not equivalent to
* long id;
* Card.Cache cache = new Cache(col, id);
* Card card = cache.getCard();
* ....
* Card card2 = cache.getCard();
*
* It is equivalent to:
* long id;
* Card.Cache cache = new Cache(col, id);
* Card card = cache.getCard();
* ....
* cache.reload();
* Card card2 = cache.getCard();
*/
open class Cache : Cloneable {
val col: Collection
val id: Long
private var mCard: Card? = null
constructor(col: Collection, id: Long) {
this.col = col
this.id = id
}
/** Copy of cache. Useful to create a copy of a subclass without loosing card if it is loaded. */
protected constructor(cache: Cache) {
col = cache.col
this.id = cache.id
mCard = cache.mCard
}
/** Copy of cache. Useful to create a copy of a subclass without loosing card if it is loaded. */
constructor(card: Card) {
col = card.col
this.id = card.id
mCard = card
}
/**
* The card with id given at creation. Note that it has content of the time at which the card was loaded, which
* may have changed in database. So it is not equivalent to getCol().getCard(getId()). If you need fresh data, reload
* first. */
@get:Synchronized
val card: Card
get() {
if (mCard == null) {
mCard = col.getCard(this.id)
}
return mCard!!
}
/** Next access to card will reload the card from the database. */
@Synchronized
open fun reload() {
mCard = null
}
override fun hashCode(): Int {
return java.lang.Long.valueOf(this.id).hashCode()
}
/** The cloned version represents the same card but data are not loaded. */
public override fun clone(): Cache {
return Cache(col, this.id)
}
override fun equals(other: Any?): Boolean {
return if (other !is Cache) {
false
} else this.id == other.id
}
fun loadQA(reload: Boolean, browser: Boolean) {
card.render_output(reload, browser)
}
}
companion object {
const val TYPE_REV = 2
// A list of class members to skip in the toString() representation
val SKIP_PRINT: Set<String> = HashSet(
Arrays.asList(
"SKIP_PRINT", "\$assertionsDisabled", "TYPE_LRN",
"TYPE_NEW", "TYPE_REV", "mNote", "mQA", "mCol", "mTimerStarted", "mTimerStopped"
)
)
fun intToFlag(flags: Int): Int {
// setting all bits to 0, except the three first one.
// equivalent to `mFlags % 8`. Used this way to copy Anki.
return flags and 7
}
fun setFlagInInt(flags: Int, flag: Int): Int {
Assert.that(0 <= flag, "flag to set is negative")
Assert.that(flag <= 7, "flag to set is greater than 7.")
// Setting the 3 firsts bits to 0, keeping the remaining.
val extraData = flags and 7.inv()
// flag in 3 fist bits, same data as in mFlags everywhere else
return extraData or flag
}
@Throws(CancellationException::class)
fun deepCopyCardArray(originals: Array<Card>, cancelListener: CancelListener): Array<Card> {
val col = CollectionHelper.getInstance().getCol(AnkiDroidApp.getInstance())
val copies = mutableListOf<Card>()
for (i in originals.indices) {
if (cancelListener.isCancelled) {
Timber.i("Cancelled during deep copy, probably memory pressure?")
throw CancellationException("Cancelled during deep copy")
}
// TODO: the performance-naive implementation loads from database instead of working in memory
// the high performance version would implement .clone() on Card and test it well
copies.add(Card(col, originals[i].id))
}
return copies.toTypedArray()
}
}
}
| gpl-3.0 | e82d164ff1866ecf6ce64cbc8b097c18 | 31.963087 | 145 | 0.576504 | 4.256988 | false | false | false | false |
Andr3Carvalh0/mGBA | app/src/main/java/io/mgba/utilities/async/WorkManagerWrapper.kt | 1 | 2410 | package io.mgba.utilities.async
import androidx.work.*
import androidx.work.WorkManager
import androidx.work.OneTimeWorkRequest
import io.mgba.mgba
object WorkManagerWrapper {
// Added this to fix the tests... In cause of the workManager not working irl. This is to blame
init { WorkManager.initialize(mgba.context, Configuration.Builder().build()) }
private var workManager: WorkManager = WorkManager.getInstance()
fun scheduleToRunWhenConnected(worker: Class<out Worker>, tag: String, replace: Boolean = false) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequest.Builder(worker)
.setConstraints(constraints)
.build()
val policy = if(replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP
workManager.beginUniqueWork(tag, policy, request).enqueue()
}
fun scheduleToRunWithExtras(worker: Class<out Worker>, extras: List<Pair<String, String>>, tag: String, replace: Boolean = false) {
val data = Data.Builder()
extras.forEach { k -> data.putString(k.first, k.second) }
val request = OneTimeWorkRequest.Builder(worker)
.setInputData(data.build())
.build()
val policy = if(replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP
workManager.beginUniqueWork(tag, policy, request).enqueue()
}
fun scheduleToRunWhenConnectedWithExtras(worker: Class<out Worker>, extras: List<Pair<String, Int>>, tag: String, replace: Boolean = false) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val data = Data.Builder()
extras.forEach { k -> data.putInt(k.first, k.second) }
val request = OneTimeWorkRequest.Builder(worker)
.setConstraints(constraints)
.setInputData(data.build())
.build()
val policy = if(replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP
workManager.beginUniqueWork(tag, policy, request).enqueue()
}
}
| mpl-2.0 | 13d3795ae29afee8f5fd58ea3c2267a8 | 37.870968 | 145 | 0.613278 | 5.30837 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/common/service/location/IntentServiceFetchAddress.kt | 1 | 4065 | package com.telenav.osv.common.service.location
import android.app.IntentService
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import android.os.ResultReceiver
import com.telenav.osv.R
import com.telenav.osv.utils.Log
import java.io.IOException
import java.util.*
class IntentServiceFetchAddress : IntentService(NAME_SERVICE) {
private val TAG by lazy { IntentServiceFetchAddress::class.java.name }
var receiver: ResultReceiver? = null
override fun onHandleIntent(intent: Intent?) {
val geocoder = Geocoder(this, Locale.getDefault())
var errorMessage = ""
// Get the location passed to this service through an extra.
val location = intent!!.getParcelableExtra<Location>(LOCATION_DATA_LOC)
receiver = intent.getParcelableExtra(RECEIVER)
val sequenceId = intent.getStringExtra(LOCATION_DATA_SEQ_ID)
val sequencePos = intent.getIntExtra(LOCATION_DATA_SEQ_POS, 0)
var addresses: List<Address> = emptyList()
try {
addresses = geocoder.getFromLocation(
location.latitude,
location.longitude,
// In this sample, we get just a single address.
RESULTS_NUMBER)
} catch (ioException: IOException) {
// Catch network or other I/O problems.
errorMessage = getString(R.string.service_not_available)
Log.e(TAG, errorMessage, ioException)
} catch (illegalArgumentException: IllegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = getString(R.string.invalid_lat_long_used)
Log.e(TAG, "$errorMessage. Latitude = $location.latitude , " +
"Longitude = $location.longitude", illegalArgumentException)
}
// Handle case where no address was found.
if (addresses.isEmpty()) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found)
Log.e(TAG, errorMessage)
}
deliverResultToReceiver(FAILURE_RESULT, errorMessage, sequenceId, sequencePos)
} else {
val address = addresses[0]
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
val addressFragments = with(address) {
(0..maxAddressLineIndex).map { getAddressLine(it) }
}
Log.i(TAG, getString(R.string.address_found))
deliverResultToReceiver(SUCCESS_RESULT,
addressFragments.joinToString(separator = "\n"),
sequenceId,
sequencePos)
}
}
private fun deliverResultToReceiver(resultCode: Int, message: String, sequenceId: String, position: Int) {
val bundle = Bundle().apply {
putString(RESULT_DATA_KEY, message)
putString(RESULT_DATA_SEQUENCE_ID, sequenceId)
putInt(RESULT_DATA_SEQUENCE_POSITION, position)
}
receiver?.send(resultCode, bundle)
}
companion object {
private const val NAME_SERVICE = "intent-service-fetch-address"
const val SUCCESS_RESULT = 0
const val FAILURE_RESULT = 1
const val PACKAGE_NAME = "com.google.android.gms.location.sample.locationaddress"
const val RECEIVER = "$PACKAGE_NAME.RECEIVER"
const val RESULT_DATA_KEY = "${PACKAGE_NAME}.RESULT_DATA_KEY"
const val RESULT_DATA_SEQUENCE_ID = "${PACKAGE_NAME}.RESULT_DATA_SEQUENCE_ID"
const val RESULT_DATA_SEQUENCE_POSITION = "${PACKAGE_NAME}.RESULT_DATA_SEQUENCE_POSITION"
const val LOCATION_DATA_LOC = "${PACKAGE_NAME}.LOCATION_DATA_LOC"
const val LOCATION_DATA_SEQ_ID = "${PACKAGE_NAME}.LOCATION_DATA_SEQ_ID"
const val LOCATION_DATA_SEQ_POS = "${PACKAGE_NAME}.LOCATION_DATA_SEQ_POS"
private const val RESULTS_NUMBER = 1
}
} | lgpl-3.0 | b286efbd22a80f00faaaf555709d0dac | 41.354167 | 110 | 0.642066 | 4.645714 | false | false | false | false |
akinaru/bbox-api-client | bboxapi-router/src/main/kotlin/fr/bmartel/bboxapi/router/model/Device.kt | 2 | 1754 | package fr.bmartel.bboxapi.router.model
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.annotations.SerializedName
import fr.bmartel.bboxapi.router.BboxApiUtils
data class Device(
val device: BboxDevice? = null
){
class Deserializer : ResponseDeserializable<List<Device>> {
override fun deserialize(content: String) = BboxApiUtils.fromJson<List<Device>>(content)
}
}
data class BboxDevice(
val now: String? = null,
val status: Int? = null,
val numberofboots: Int? = null,
val modelname: String? = null,
@SerializedName("user_configured")
val userConfigured: Int? = null,
val display: Display? = null,
val main: Version? = null,
val reco: Version? = null,
val running: Version? = null,
val bcck: Version? = null,
val ldr1: Version? = null,
val ldr2: Version? = null,
val firstusedate: String? = null,
val uptime: Int? = null,
val serialnumber: String? = null,
val using: DeviceService? = null
)
data class Display(
val luminosity: Int? = null,
val state: String? = null
)
data class Version(
private val version: String? = null,
private val date: String? = null
) {
fun getMajor(): Int {
return BboxApiUtils.getVersionPattern(version, 1)
}
fun getMinor(): Int {
return BboxApiUtils.getVersionPattern(version, 2)
}
fun getPatch(): Int {
return BboxApiUtils.getVersionPattern(version, 3)
}
}
data class DeviceService(
val ipv4: Int? = null,
val ipv6: Int? = null,
val ftth: Int? = null,
val adsl: Int? = null,
val vdsl: Int? = null
) | mit | 5f55d3782afb874cddabf85155d57b8f | 26.857143 | 96 | 0.619156 | 3.932735 | false | false | false | false |
calebprior/Android-Boilerplate | app/src/main/kotlin/com/calebprior/boilerplate/ui/base/BasePresenter.kt | 1 | 1369 | package com.calebprior.boilerplate.ui.base
import android.support.design.widget.Snackbar
import com.calebprior.boilerplate.R
import com.calebprior.boilerplate.flowcontrol.FlowController
import com.calebprior.boilerplate.ui.base.BaseView
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
open class BasePresenter<V : BaseView>(
var flowController: FlowController
) : AnkoLogger {
var view: V? = null
open fun afterAttach() {}
open fun afterDetach() {}
open fun afterError() {}
fun attachView(view: V) {
this.view = view
afterAttach()
}
fun detachView() {
view = null
afterDetach()
}
fun handleError(e: Throwable, message: String = "Error Occurred") {
info(e)
hideKeyboard()
stopLoading()
showSnackBar(message)
afterError()
}
fun hideKeyboard() {
view?.hideKeyboard()
}
fun showLoading() {
view?.showLoading()
}
fun stopLoading() {
view?.stopLoading()
}
fun showSnackBar(message: String,
id: Int = R.id.root_view,
length: Int = Snackbar.LENGTH_SHORT,
actionText: String = "",
action: () -> Unit = {}
) {
view?.showSnackBar(message, id, length, actionText, action)
}
} | mit | edd263b4aa40a9f9e6b0d97050dc28f5 | 21.459016 | 71 | 0.596056 | 4.473856 | false | false | false | false |
stripe/stripe-android | financial-connections/src/main/java/com/stripe/android/financialconnections/model/FinancialConnectionsAccount.kt | 1 | 8343 | package com.stripe.android.financialconnections.model
import android.os.Parcelable
import com.stripe.android.core.model.StripeModel
import com.stripe.android.core.model.serializers.EnumIgnoreUnknownSerializer
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* A FinancialConnectionsAccount represents an account that exists outside of Stripe,
* to which you have been granted some degree of access.
*
* @param category
* @param created Time at which the object was created. Measured in seconds since the Unix epoch.
* @param id Unique identifier for the object.
* @param institutionName The name of the institution that holds this account.
* @param livemode Has the value `true` if the object exists in live mode or the value `false` if
* the object exists in test mode.
* @param status The status of the link to the account.
* @param subcategory If `category` is `cash`, one of: - `checking` - `savings` - `other`
* If `category` is `credit`, one of: - `mortgage` - `line_of_credit` - `credit_card` - `other`
* If `category` is `investment` or `other`, this will be `other`.
* @param supportedPaymentMethodTypes
* The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s)
* that can be created from this FinancialConnectionsAccount.
* @param accountholder
* @param balance The most recent information about the account's balance.
* @param balanceRefresh The state of the most recent attempt to refresh the account balance.
* @param displayName A human-readable name that has been assigned to this account,
* either by the account holder or by the institution.
* @param last4 The last 4 digits of the account number. If present, this will be 4 numeric characters.
* @param ownership The most recent information about the account's owners.
* @param ownershipRefresh The state of the most recent attempt to refresh the account owners.
* @param permissions The list of permissions granted by this account.
*/
@Serializable
@Parcelize
@Suppress("unused")
data class FinancialConnectionsAccount(
@SerialName("category")
val category: Category = Category.UNKNOWN,
/* Time at which the object was created. Measured in seconds since the Unix epoch. */
@SerialName("created")
val created: Int,
/* Unique identifier for the object. */
@SerialName("id")
val id: String,
/* The name of the institution that holds this account. */
@SerialName("institution_name")
val institutionName: String,
/* Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. */
@SerialName("livemode")
val livemode: Boolean,
/* The status of the link to the account. */
@SerialName("status")
val status: Status = Status.UNKNOWN,
/* If `category` is `cash`, one of: - `checking` - `savings` - `other`
If `category` is `credit`, one of: - `mortgage` - `line_of_credit` - `credit_card` - `other`
If `category` is `investment` or `other`, this will be `other`.
*/
@SerialName("subcategory")
val subcategory: Subcategory = Subcategory.UNKNOWN,
/* The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s)
that can be created from this FinancialConnectionsAccount. */
@SerialName("supported_payment_method_types")
val supportedPaymentMethodTypes: List<SupportedPaymentMethodTypes>,
/* The most recent information about the account's balance. */
@SerialName("balance")
val balance: Balance? = null,
/* The state of the most recent attempt to refresh the account balance. */
@SerialName("balance_refresh")
val balanceRefresh: BalanceRefresh? = null,
/* A human-readable name that has been assigned to this account,
either by the account holder or by the institution. */
@SerialName("display_name")
val displayName: String? = null,
/* The last 4 digits of the account number. If present, this will be 4 numeric characters. */
@SerialName("last4")
val last4: String? = null,
/* The most recent information about the account's owners. */
@SerialName("ownership")
val ownership: String? = null,
/* The state of the most recent attempt to refresh the account owners. */
@SerialName("ownership_refresh")
val ownershipRefresh: OwnershipRefresh? = null,
/* The list of permissions granted by this account. */
@SerialName("permissions")
val permissions: List<Permissions>? = null
) : StripeModel, Parcelable, PaymentAccount() {
/**
*
*
* Values: cash,credit,investment,other
*/
@Serializable(with = Category.Serializer::class)
enum class Category(val value: String) {
@SerialName("cash")
CASH("cash"),
@SerialName("credit")
CREDIT("credit"),
@SerialName("investment")
INVESTMENT("investment"),
@SerialName("other")
OTHER("other"),
UNKNOWN("unknown");
internal object Serializer :
EnumIgnoreUnknownSerializer<Category>(Category.values(), UNKNOWN)
}
/**
* The status of the link to the account.
*
* Values: active,disconnected,inactive
*/
@Serializable(with = Status.Serializer::class)
enum class Status(val value: String) {
@SerialName("active")
ACTIVE("active"),
@SerialName("disconnected")
DISCONNECTED("disconnected"),
@SerialName("inactive")
INACTIVE("inactive"),
UNKNOWN("unknown");
internal object Serializer : EnumIgnoreUnknownSerializer<Status>(Status.values(), UNKNOWN)
}
/**
* If `category` is `cash`, one of: - `checking` - `savings` - `other`
* If `category` is `credit`, one of: - `mortgage` - `line_of_credit` - `credit_card` - `other`
* If `category` is `investment` or `other`, this will be `other`.
*
* Values: checking,creditCard,lineOfCredit,mortgage,other,savings
*/
@Serializable(with = Subcategory.Serializer::class)
enum class Subcategory(val value: String) {
@SerialName("checking")
CHECKING("checking"),
@SerialName("credit_card")
CREDIT_CARD("credit_card"),
@SerialName("line_of_credit")
LINE_OF_CREDIT("line_of_credit"),
@SerialName("mortgage")
MORTGAGE("mortgage"),
@SerialName("other")
OTHER("other"),
@SerialName("savings")
SAVINGS("savings"),
UNKNOWN("unknown");
internal object Serializer :
EnumIgnoreUnknownSerializer<Subcategory>(Subcategory.values(), UNKNOWN)
}
/**
* The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s)
* that can be created from this FinancialConnectionsAccount.
*
* Values: link,usBankAccount
*/
@Serializable(with = SupportedPaymentMethodTypes.Serializer::class)
enum class SupportedPaymentMethodTypes(val value: String) {
@SerialName("link")
LINK("link"),
@SerialName("us_bank_account")
US_BANK_ACCOUNT("us_bank_account"),
UNKNOWN("unknown");
internal object Serializer :
EnumIgnoreUnknownSerializer<SupportedPaymentMethodTypes>(values(), UNKNOWN)
}
/**
* The list of permissions granted by this account.
*
* Values: balances,identity,ownership,paymentMethod,transactions
*/
@Serializable(with = Permissions.Serializer::class)
enum class Permissions(val value: String) {
@SerialName("balances")
BALANCES("balances"),
@SerialName("ownership")
OWNERSHIP("ownership"),
@SerialName("payment_method")
PAYMENT_METHOD("payment_method"),
@SerialName("transactions")
TRANSACTIONS("transactions"),
@SerialName("account_numbers")
ACCOUNT_NUMBERS("account_numbers"),
UNKNOWN("unknown");
internal object Serializer : EnumIgnoreUnknownSerializer<Permissions>(values(), UNKNOWN)
}
companion object {
internal const val OBJECT_OLD = "linked_account"
internal const val OBJECT_NEW = "financial_connections.account"
}
}
| mit | def96960ffa81630f599755f95ffca63 | 34.054622 | 120 | 0.671821 | 4.456731 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyFragment.kt | 1 | 23278 | package org.thoughtcrime.securesms.stories.viewer.reply.group
import android.content.ClipData
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.ColorInt
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehaviorHack
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment
import org.thoughtcrime.securesms.components.emoji.MediaKeyboard
import org.thoughtcrime.securesms.components.mention.MentionAnnotation
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.conversation.MarkReadHelper
import org.thoughtcrime.securesms.conversation.colors.Colorizer
import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQuery
import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQueryChangedListener
import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQueryResultsController
import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQueryViewModel
import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerFragment
import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerViewModel
import org.thoughtcrime.securesms.database.model.Mention
import org.thoughtcrime.securesms.database.model.MessageId
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobs.RetrieveProfileJob
import org.thoughtcrime.securesms.keyboard.KeyboardPage
import org.thoughtcrime.securesms.keyboard.KeyboardPagerViewModel
import org.thoughtcrime.securesms.keyboard.emoji.EmojiKeyboardCallback
import org.thoughtcrime.securesms.mediasend.v2.UntrustedRecords
import org.thoughtcrime.securesms.notifications.v2.ConversationId
import org.thoughtcrime.securesms.reactions.any.ReactWithAnyEmojiBottomSheetDialogFragment
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.recipients.ui.bottomsheet.RecipientBottomSheetDialogFragment
import org.thoughtcrime.securesms.safety.SafetyNumberBottomSheet
import org.thoughtcrime.securesms.sms.MessageSender
import org.thoughtcrime.securesms.stories.viewer.reply.StoryViewsAndRepliesPagerChild
import org.thoughtcrime.securesms.stories.viewer.reply.StoryViewsAndRepliesPagerParent
import org.thoughtcrime.securesms.stories.viewer.reply.composer.StoryReactionBar
import org.thoughtcrime.securesms.stories.viewer.reply.composer.StoryReplyComposer
import org.thoughtcrime.securesms.util.DeleteDialog
import org.thoughtcrime.securesms.util.FragmentDialogs.displayInDialogAboveAnchor
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.ServiceUtil
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.PagingMappingAdapter
import org.thoughtcrime.securesms.util.fragments.findListener
import org.thoughtcrime.securesms.util.fragments.requireListener
import org.thoughtcrime.securesms.util.visible
/**
* Fragment which contains UI to reply to a group story
*/
class StoryGroupReplyFragment :
Fragment(R.layout.stories_group_replies_fragment),
StoryViewsAndRepliesPagerChild,
StoryReplyComposer.Callback,
EmojiKeyboardCallback,
ReactWithAnyEmojiBottomSheetDialogFragment.Callback,
SafetyNumberBottomSheet.Callbacks {
companion object {
private val TAG = Log.tag(StoryGroupReplyFragment::class.java)
private const val ARG_STORY_ID = "arg.story.id"
private const val ARG_GROUP_RECIPIENT_ID = "arg.group.recipient.id"
private const val ARG_IS_FROM_NOTIFICATION = "is_from_notification"
private const val ARG_GROUP_REPLY_START_POSITION = "group_reply_start_position"
fun create(storyId: Long, groupRecipientId: RecipientId, isFromNotification: Boolean, groupReplyStartPosition: Int): Fragment {
return StoryGroupReplyFragment().apply {
arguments = Bundle().apply {
putLong(ARG_STORY_ID, storyId)
putParcelable(ARG_GROUP_RECIPIENT_ID, groupRecipientId)
putBoolean(ARG_IS_FROM_NOTIFICATION, isFromNotification)
putInt(ARG_GROUP_REPLY_START_POSITION, groupReplyStartPosition)
}
}
}
}
private val viewModel: StoryGroupReplyViewModel by viewModels(
factoryProducer = {
StoryGroupReplyViewModel.Factory(storyId, StoryGroupReplyRepository())
}
)
private val mentionsViewModel: MentionsPickerViewModel by viewModels(
factoryProducer = { MentionsPickerViewModel.Factory() },
ownerProducer = { requireActivity() }
)
private val inlineQueryViewModel: InlineQueryViewModel by viewModels(
ownerProducer = { requireActivity() }
)
private val keyboardPagerViewModel: KeyboardPagerViewModel by viewModels(
ownerProducer = { requireActivity() }
)
private val recyclerListener: RecyclerView.OnItemTouchListener = object : RecyclerView.SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean {
recyclerView.isNestedScrollingEnabled = view == recyclerView
composer.emojiPageView?.isNestedScrollingEnabled = view == composer.emojiPageView
val dialog = (parentFragment as FixedRoundedCornerBottomSheetDialogFragment).dialog as BottomSheetDialog
BottomSheetBehaviorHack.setNestedScrollingChild(dialog.behavior, view)
dialog.findViewById<View>(R.id.design_bottom_sheet)?.invalidate()
return false
}
}
private val colorizer = Colorizer()
private val lifecycleDisposable = LifecycleDisposable()
private val storyId: Long
get() = requireArguments().getLong(ARG_STORY_ID)
private val groupRecipientId: RecipientId
get() = requireArguments().getParcelable(ARG_GROUP_RECIPIENT_ID)!!
private val isFromNotification: Boolean
get() = requireArguments().getBoolean(ARG_IS_FROM_NOTIFICATION, false)
private val groupReplyStartPosition: Int
get() = requireArguments().getInt(ARG_GROUP_REPLY_START_POSITION, -1)
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: PagingMappingAdapter<MessageId>
private lateinit var dataObserver: RecyclerView.AdapterDataObserver
private lateinit var composer: StoryReplyComposer
private lateinit var notInGroup: View
private var markReadHelper: MarkReadHelper? = null
private var currentChild: StoryViewsAndRepliesPagerParent.Child? = null
private var resendBody: CharSequence? = null
private var resendMentions: List<Mention> = emptyList()
private var resendReaction: String? = null
private lateinit var inlineQueryResultsController: InlineQueryResultsController
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
SignalExecutors.BOUNDED.execute {
RetrieveProfileJob.enqueue(groupRecipientId)
}
recyclerView = view.findViewById(R.id.recycler)
composer = view.findViewById(R.id.composer)
notInGroup = view.findViewById(R.id.not_in_group)
lifecycleDisposable.bindTo(viewLifecycleOwner)
val emptyNotice: View = requireView().findViewById(R.id.empty_notice)
adapter = PagingMappingAdapter<MessageId>().apply {
setPagingController(viewModel.pagingController)
}
val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
recyclerView.itemAnimator = null
StoryGroupReplyItem.register(adapter)
composer.callback = this
composer.hint = getString(R.string.StoryViewerPageFragment__reply_to_group)
onPageSelected(findListener<StoryViewsAndRepliesPagerParent>()?.selectedChild ?: StoryViewsAndRepliesPagerParent.Child.REPLIES)
var firstSubmit = true
lifecycleDisposable += viewModel.state
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy { state ->
if (markReadHelper == null && state.threadId > 0L) {
if (isResumed) {
ApplicationDependencies.getMessageNotifier().setVisibleThread(ConversationId(state.threadId, storyId))
}
markReadHelper = MarkReadHelper(ConversationId(state.threadId, storyId), requireContext(), viewLifecycleOwner)
if (isFromNotification) {
markReadHelper?.onViewsRevealed(System.currentTimeMillis())
}
}
emptyNotice.visible = state.noReplies && state.loadState == StoryGroupReplyState.LoadState.READY
colorizer.onNameColorsChanged(state.nameColors)
adapter.submitList(getConfiguration(state.replies).toMappingModelList()) {
if (firstSubmit && (groupReplyStartPosition >= 0 && adapter.hasItem(groupReplyStartPosition))) {
firstSubmit = false
recyclerView.post { recyclerView.scrollToPosition(groupReplyStartPosition) }
}
}
}
dataObserver = GroupDataObserver()
adapter.registerAdapterDataObserver(dataObserver)
initializeMentions()
initializeComposer(savedInstanceState)
recyclerView.addOnScrollListener(GroupReplyScrollObserver())
}
override fun onResume() {
super.onResume()
val threadId = viewModel.stateSnapshot.threadId
if (threadId != 0L) {
ApplicationDependencies.getMessageNotifier().setVisibleThread(ConversationId(threadId, storyId))
}
}
override fun onPause() {
super.onPause()
ApplicationDependencies.getMessageNotifier().setVisibleThread(null)
}
override fun onDestroyView() {
super.onDestroyView()
composer.input.setInlineQueryChangedListener(null)
composer.input.setMentionValidator(null)
}
private fun postMarkAsReadRequest() {
if (adapter.itemCount == 0 || markReadHelper == null) {
return
}
val lastVisibleItem = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
val adapterItem = adapter.getItem(lastVisibleItem)
if (adapterItem == null || adapterItem !is StoryGroupReplyItem.Model) {
return
}
markReadHelper?.onViewsRevealed(adapterItem.replyBody.sentAtMillis)
}
private fun getConfiguration(pageData: List<ReplyBody>): DSLConfiguration {
return configure {
pageData.forEach {
when (it) {
is ReplyBody.Text -> {
customPref(
StoryGroupReplyItem.TextModel(
text = it,
nameColor = it.sender.getStoryGroupReplyColor(),
onCopyClick = { s -> onCopyClick(s) },
onMentionClick = { recipientId ->
RecipientBottomSheetDialogFragment
.create(recipientId, null)
.show(childFragmentManager, null)
},
onDeleteClick = { m -> onDeleteClick(m) },
onTapForDetailsClick = { m -> onTapForDetailsClick(m) }
)
)
}
is ReplyBody.Reaction -> {
customPref(
StoryGroupReplyItem.ReactionModel(
reaction = it,
nameColor = it.sender.getStoryGroupReplyColor(),
onCopyClick = { s -> onCopyClick(s) },
onDeleteClick = { m -> onDeleteClick(m) },
onTapForDetailsClick = { m -> onTapForDetailsClick(m) }
)
)
}
is ReplyBody.RemoteDelete -> {
customPref(
StoryGroupReplyItem.RemoteDeleteModel(
remoteDelete = it,
nameColor = it.sender.getStoryGroupReplyColor(),
onDeleteClick = { m -> onDeleteClick(m) },
onTapForDetailsClick = { m -> onTapForDetailsClick(m) }
)
)
}
}
}
}
}
private fun onCopyClick(textToCopy: CharSequence) {
val clipData = ClipData.newPlainText(requireContext().getString(R.string.app_name), textToCopy)
ServiceUtil.getClipboardManager(requireContext()).setPrimaryClip(clipData)
Toast.makeText(requireContext(), R.string.StoryGroupReplyFragment__copied_to_clipboard, Toast.LENGTH_SHORT).show()
}
private fun onDeleteClick(messageRecord: MessageRecord) {
lifecycleDisposable += DeleteDialog.show(requireActivity(), setOf(messageRecord)).subscribe { didDeleteThread ->
if (didDeleteThread) {
throw AssertionError("We should never end up deleting a Group Thread like this.")
}
}
}
private fun onTapForDetailsClick(messageRecord: MessageRecord) {
if (messageRecord.isRemoteDelete) {
// TODO [cody] Android doesn't support resending remote deletes yet
return
}
if (messageRecord.isIdentityMismatchFailure) {
SafetyNumberBottomSheet
.forMessageRecord(requireContext(), messageRecord)
.show(childFragmentManager)
} else if (messageRecord.hasFailedWithNetworkFailures()) {
MaterialAlertDialogBuilder(requireContext())
.setMessage(R.string.conversation_activity__message_could_not_be_sent)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.conversation_activity__send) { _, _ -> SignalExecutors.BOUNDED.execute { MessageSender.resend(requireContext(), messageRecord) } }
.show()
}
}
override fun onPageSelected(child: StoryViewsAndRepliesPagerParent.Child) {
currentChild = child
updateNestedScrolling()
}
private fun updateNestedScrolling() {
recyclerView.isNestedScrollingEnabled = currentChild == StoryViewsAndRepliesPagerParent.Child.REPLIES && !(mentionsViewModel.isShowing.value ?: false)
}
override fun onSendActionClicked() {
val (body, mentions) = composer.consumeInput()
performSend(body, mentions)
}
override fun onPickReactionClicked() {
displayInDialogAboveAnchor(composer.reactionButton, R.layout.stories_reaction_bar_layout) { dialog, view ->
view.findViewById<StoryReactionBar>(R.id.reaction_bar).apply {
callback = object : StoryReactionBar.Callback {
override fun onTouchOutsideOfReactionBar() {
dialog.dismiss()
}
override fun onReactionSelected(emoji: String) {
dialog.dismiss()
sendReaction(emoji)
}
override fun onOpenReactionPicker() {
dialog.dismiss()
ReactWithAnyEmojiBottomSheetDialogFragment.createForStory().show(childFragmentManager, null)
}
}
animateIn()
}
}
}
override fun onEmojiSelected(emoji: String?) {
composer.onEmojiSelected(emoji)
}
private fun sendReaction(emoji: String) {
findListener<Callback>()?.onReactionEmojiSelected(emoji)
lifecycleDisposable += StoryGroupReplySender.sendReaction(requireContext(), storyId, emoji)
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onError = { error ->
if (error is UntrustedRecords.UntrustedRecordsException) {
resendReaction = emoji
SafetyNumberBottomSheet
.forIdentityRecordsAndDestination(error.untrustedRecords, ContactSearchKey.RecipientSearchKey.Story(groupRecipientId))
.show(childFragmentManager)
} else {
Log.w(TAG, "Failed to send reply", error)
val context = context
if (context != null) {
Toast.makeText(context, R.string.message_details_recipient__failed_to_send, Toast.LENGTH_SHORT).show()
}
}
}
)
}
override fun onKeyEvent(keyEvent: KeyEvent?) = Unit
override fun onInitializeEmojiDrawer(mediaKeyboard: MediaKeyboard) {
keyboardPagerViewModel.setOnlyPage(KeyboardPage.EMOJI)
mediaKeyboard.setFragmentManager(childFragmentManager)
}
override fun onShowEmojiKeyboard() {
requireListener<Callback>().requestFullScreen(true)
recyclerView.addOnItemTouchListener(recyclerListener)
composer.emojiPageView?.addOnItemTouchListener(recyclerListener)
}
override fun onHideEmojiKeyboard() {
recyclerView.removeOnItemTouchListener(recyclerListener)
composer.emojiPageView?.removeOnItemTouchListener(recyclerListener)
requireListener<Callback>().requestFullScreen(false)
}
override fun openEmojiSearch() {
composer.openEmojiSearch()
}
override fun closeEmojiSearch() {
composer.closeEmojiSearch()
}
override fun onReactWithAnyEmojiDialogDismissed() = Unit
override fun onReactWithAnyEmojiSelected(emoji: String) {
sendReaction(emoji)
}
private fun initializeComposer(savedInstanceState: Bundle?) {
val isActiveGroup = Recipient.observable(groupRecipientId).map { it.isActiveGroup }
if (savedInstanceState == null) {
lifecycleDisposable += isActiveGroup.firstOrError().observeOn(AndroidSchedulers.mainThread()).subscribe { active ->
if (active) {
ViewUtil.focusAndShowKeyboard(composer)
}
}
}
lifecycleDisposable += isActiveGroup.distinctUntilChanged().observeOn(AndroidSchedulers.mainThread()).forEach { active ->
composer.visible = active
notInGroup.visible = !active
}
}
private fun initializeMentions() {
inlineQueryResultsController = InlineQueryResultsController(
requireContext(),
inlineQueryViewModel,
composer,
(requireView() as ViewGroup),
composer.input,
viewLifecycleOwner
)
Recipient.live(groupRecipientId).observe(viewLifecycleOwner) { recipient ->
mentionsViewModel.onRecipientChange(recipient)
composer.input.setInlineQueryChangedListener(object : InlineQueryChangedListener {
override fun onQueryChanged(inlineQuery: InlineQuery) {
when (inlineQuery) {
is InlineQuery.Mention -> {
if (recipient.isPushV2Group) {
ensureMentionsContainerFilled()
mentionsViewModel.onQueryChange(inlineQuery.query)
}
inlineQueryViewModel.onQueryChange(inlineQuery)
}
is InlineQuery.Emoji -> {
inlineQueryViewModel.onQueryChange(inlineQuery)
mentionsViewModel.onQueryChange(null)
}
is InlineQuery.NoQuery -> {
mentionsViewModel.onQueryChange(null)
inlineQueryViewModel.onQueryChange(inlineQuery)
}
}
}
override fun clearQuery() {
onQueryChanged(InlineQuery.NoQuery)
}
})
composer.input.setMentionValidator { annotations ->
if (!recipient.isPushV2Group) {
annotations
} else {
val validRecipientIds: Set<String> = recipient.participantIds
.map { id -> MentionAnnotation.idToMentionAnnotationValue(id) }
.toSet()
annotations
.filter { !validRecipientIds.contains(it.value) }
.toList()
}
}
}
mentionsViewModel.selectedRecipient.observe(viewLifecycleOwner) { recipient ->
composer.input.replaceTextWithMention(recipient.getDisplayName(requireContext()), recipient.id)
}
lifecycleDisposable += inlineQueryViewModel
.selection
.observeOn(AndroidSchedulers.mainThread())
.subscribe { r -> composer.input.replaceText(r) }
mentionsViewModel.isShowing.observe(viewLifecycleOwner) { updateNestedScrolling() }
}
private fun ensureMentionsContainerFilled() {
val mentionsFragment = childFragmentManager.findFragmentById(R.id.mentions_picker_container)
if (mentionsFragment == null) {
childFragmentManager
.beginTransaction()
.replace(R.id.mentions_picker_container, MentionsPickerFragment())
.commitNowAllowingStateLoss()
}
}
private fun performSend(body: CharSequence, mentions: List<Mention>) {
lifecycleDisposable += StoryGroupReplySender.sendReply(requireContext(), storyId, body, mentions)
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onError = { throwable ->
if (throwable is UntrustedRecords.UntrustedRecordsException) {
resendBody = body
resendMentions = mentions
SafetyNumberBottomSheet
.forIdentityRecordsAndDestination(throwable.untrustedRecords, ContactSearchKey.RecipientSearchKey.Story(groupRecipientId))
.show(childFragmentManager)
} else {
Log.w(TAG, "Failed to send reply", throwable)
val context = context
if (context != null) {
Toast.makeText(context, R.string.message_details_recipient__failed_to_send, Toast.LENGTH_SHORT).show()
}
}
}
)
}
override fun sendAnywayAfterSafetyNumberChangedInBottomSheet(destinations: List<ContactSearchKey.RecipientSearchKey>) {
val resendBody = resendBody
val resendReaction = resendReaction
if (resendBody != null) {
performSend(resendBody, resendMentions)
} else if (resendReaction != null) {
sendReaction(resendReaction)
}
}
override fun onMessageResentAfterSafetyNumberChangeInBottomSheet() {
Log.i(TAG, "Message resent")
}
override fun onCanceled() {
resendBody = null
resendMentions = emptyList()
resendReaction = null
}
@ColorInt
private fun Recipient.getStoryGroupReplyColor(): Int {
return colorizer.getIncomingGroupSenderColor(requireContext(), this)
}
private inner class GroupReplyScrollObserver : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
postMarkAsReadRequest()
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
postMarkAsReadRequest()
}
}
private inner class GroupDataObserver : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (itemCount == 0) {
return
}
val item = adapter.getItem(positionStart)
if (positionStart == adapter.itemCount - 1 && item is StoryGroupReplyItem.Model) {
val isOutgoing = item.replyBody.sender == Recipient.self()
if (isOutgoing || (!isOutgoing && !recyclerView.canScrollVertically(1))) {
recyclerView.post { recyclerView.scrollToPosition(positionStart) }
}
}
}
}
interface Callback {
fun onStartDirectReply(recipientId: RecipientId)
fun requestFullScreen(fullscreen: Boolean)
fun onReactionEmojiSelected(emoji: String)
}
}
| gpl-3.0 | 5ec11f94dda599345a5d9005c82d0439 | 37.286184 | 166 | 0.725148 | 5.273675 | false | false | false | false |
daniloqueiroz/nsync | src/main/kotlin/nsync/metadata/Metadata.kt | 1 | 540 | package nsync.metadata
import java.net.URI
internal const val URI_SCHEMA = "nsync"
internal fun buildIdentifier(folderId: String, fileId: String? = null): URI {
val uri = "$URI_SCHEMA:$folderId"
val uri1 = if (fileId != null)
"$uri:$fileId"
else
uri
return URI(uri1)
}
data class FS(
val localFolder: URI,
val remoteFolder: URI,
val identifier: URI? = null)
enum class Status {
PENDING, TRANSFERRING, SYNCHRONIZED
}
interface Metadata {
fun filesystems(): Sequence<FS>
} | gpl-3.0 | 64142b4cfcee8b61271d39c2a9483b8f | 19.037037 | 77 | 0.646296 | 3.624161 | false | false | false | false |
treelzebub/SweepingCircleProgressView | lib/src/main/java/net/treelzebub/sweepingcircleprogressview/EquilateralView.kt | 1 | 1225 | package net.treelzebub.sweepingcircleprogressview
import android.content.Context
import android.util.AttributeSet
import android.view.View
/**
* Created by Tre Murillo on 12/21/16
*
* Port from original Java by Aaron Sarazan (https://github.com/asarazan)
*/
open class EquilateralView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
): View(context, attrs, defStyle) {
protected fun getDimension() = Math.min(width, height)
/**
* This view insists on a square layout, so it will always take the lesser of the two dimensions.
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val wMode = View.MeasureSpec.getMode(widthMeasureSpec)
var w = View.MeasureSpec.getSize(widthMeasureSpec)
val hMode = View.MeasureSpec.getMode(heightMeasureSpec)
var h = View.MeasureSpec.getSize(heightMeasureSpec)
val dim = Math.min(
if (wMode == View.MeasureSpec.UNSPECIFIED) Integer.MAX_VALUE else w,
if (hMode == View.MeasureSpec.UNSPECIFIED) Integer.MAX_VALUE else h)
w = dim
h = dim
setMeasuredDimension(w, h)
}
} | mit | 00fcf7ace53ddfd5d97ed981fc530ecf | 33.055556 | 101 | 0.675102 | 4.238754 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/social/Group.kt | 1 | 2034 | package com.habitrpg.android.habitica.models.social
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.BaseMainObject
import com.habitrpg.android.habitica.models.inventory.Quest
import com.habitrpg.android.habitica.models.tasks.TaskList
import com.habitrpg.shared.habitica.models.tasks.TasksOrder
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.Ignore
import io.realm.annotations.PrimaryKey
open class Group : RealmObject(), BaseMainObject {
override val realmClass: Class<Group>
get() = Group::class.java
override val primaryIdentifier: String?
get() = id
override val primaryIdentifierName: String
get() = "id"
@SerializedName("_id")
@PrimaryKey
var id: String = ""
var balance: Double = 0.toDouble()
var description: String? = null
var summary: String? = null
var leaderID: String? = null
var leaderName: String? = null
var name: String? = null
var memberCount: Int = 0
var type: String? = null
var logo: String? = null
var quest: Quest? = null
var privacy: String? = null
var challengeCount: Int = 0
var leaderMessage: String? = null
var leaderOnlyChallenges: Boolean = false
var leaderOnlyGetGems: Boolean = false
var categories: RealmList<GroupCategory>? = null
@Ignore
var tasksOrder: TasksOrder? = null
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
val group = other as? Group
return id == group?.id
}
override fun hashCode(): Int {
return id.hashCode()
}
companion object {
const val TAVERN_ID = "00000000-0000-4000-A000-000000000000"
}
val hasActiveQuest: Boolean
get() {
return quest?.active ?: false
}
val gemCount: Int
get() {
return (balance * 4.0).toInt()
}
}
| gpl-3.0 | c7ee2ab905872bb97baf75fb2af03fa4 | 27.057143 | 68 | 0.635202 | 4.282105 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/dialogfragment/ModifyListDialogFragment.kt | 1 | 3786 | package com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView.OnEditorActionListener
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.databinding.DialogModifylistBinding
import com.rolandvitezhu.todocloud.helper.setSoftInputMode
import com.rolandvitezhu.todocloud.ui.activity.main.fragment.MainListFragment
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel
import kotlinx.android.synthetic.main.dialog_modifylist.*
import kotlinx.android.synthetic.main.dialog_modifylist.view.*
class ModifyListDialogFragment : AppCompatDialogFragment() {
private val listsViewModel by lazy {
ViewModelProvider(requireActivity()).get(ListsViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogTheme)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val dialogModifylistBinding: DialogModifylistBinding =
DialogModifylistBinding.inflate(inflater, container, false)
val view: View = dialogModifylistBinding.root
dialogModifylistBinding.modifyListDialogFragment = this
dialogModifylistBinding.listsViewModel = listsViewModel
dialogModifylistBinding.executePendingBindings()
requireDialog().setTitle(R.string.modifylist_title)
setSoftInputMode()
applyTextChangedEvents(view)
applyEditorActionEvents(view)
return view
}
private fun applyTextChangedEvents(view: View) {
view.textinputedittext_modifylist_title.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
validateTitle()
}
})
}
private fun applyEditorActionEvents(view: View) {
view.textinputedittext_modifylist_title.setOnEditorActionListener(
OnEditorActionListener { v, actionId, event ->
val pressDone = actionId == EditorInfo.IME_ACTION_DONE
var pressEnter = false
if (event != null) {
val keyCode = event.keyCode
pressEnter = keyCode == KeyEvent.KEYCODE_ENTER
}
if (pressEnter || pressDone) {
view.button_modifylist_ok!!.performClick()
return@OnEditorActionListener true
}
false
})
}
private fun validateTitle(): Boolean {
return if (listsViewModel.list.title.isBlank()) {
this.textinputlayout_modifylist_title.error = getString(R.string.all_entertitle)
false
} else {
this.textinputlayout_modifylist_title.isErrorEnabled = false
true
}
}
fun onButtonOkClick(view: View) {
if (validateTitle()) {
listsViewModel.onModifyList()
(targetFragment as MainListFragment?)?.finishActionMode()
dismiss()
}
}
fun onButtonCancelClick(view: View) {
dismiss()
}
} | mit | e50b8dd85a4d452e779f65253146263c | 35.76699 | 98 | 0.691759 | 5.317416 | false | false | false | false |
idok/react-templates-plugin | src/com/wix/rtk/cli/Npm.kt | 1 | 2010 | package com.wix.rtk.cli
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import com.intellij.execution.ExecutionException
import com.wix.nodejs.NodeRunner
import com.wix.rtk.cli.RTRunner.TIME_OUT as TIME_OUT
object Npm {
val REACT_TEMPLATES = "react-templates"
val OUTDATED = "outdated"
val VIEW = "view"
val G = "-g"
val JSON = "-json"
// npm view react-templates
fun view(cwd: String, npm: String): Output {
return try {
val command = CLI2(cwd, npm).param(VIEW).param(REACT_TEMPLATES).command
val output = NodeRunner.execute(command, RTRunner.TIME_OUT)
val json = output.stdout
parseNpmOutdated(json)
} catch (e: ExecutionException) {
// RTRunner.LOG.warn("Could not build react-templates file", e)
e.printStackTrace()
Output()
}
}
//npm ls react-templates -g --depth 0 --json
//npm outdated react-templates -g -json
fun outdated(cwd: String, npm: String): Outdated {
return try {
val command = CLI2(cwd, npm).param(OUTDATED).param(REACT_TEMPLATES).param(G).param(JSON).command
val output = NodeRunner.execute(command, RTRunner.TIME_OUT)
val json = output.stdout
Outdated.parseNpmOutdated(json)
} catch (e: ExecutionException) {
// RTRunner.LOG.warn("Could not build react-templates file", e)
e.printStackTrace()
Outdated()
}
}
fun parseNpmOutdated(json: String): Output {
val builder = GsonBuilder()
val g = builder.setPrettyPrinting().create()
val listType = object : TypeToken<Output>() {}.type
return g.fromJson<Output>(json, listType)
}
class Output(val name: String = "",
@SerializedName("dist-tags") val distTags: Tags = Tags())
class Tags(val latest: String = "")
} | mit | 4e3ebf6615f442573c32de205d82c9d6 | 34.280702 | 108 | 0.61791 | 4.093686 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/DefField.kt | 2 | 3336 | package com.intellij.workspaceModel.codegen.deft.model
import com.intellij.workspaceModel.codegen.deft.TBlob
import com.intellij.workspaceModel.codegen.deft.TRef
import com.intellij.workspaceModel.codegen.deft.*
class DefField(
val nameRange: SrcRange,
val name: String,
val type: KtType?,
val expr: Boolean,
val getterBody: String?,
val constructorParam: Boolean,
val suspend: Boolean,
val annotations: KtAnnotations,
val receiver: KtType? = null,
val extensionDelegateModuleName: SrcRange? = null
) {
val open: Boolean = annotations.flags.open
val content: Boolean = annotations.flags.content
val relation: Boolean = annotations.flags.relation
val ignored: Boolean = annotations.flags.ignored
var id = 0
override fun toString(): String = buildString {
if (ignored) append("ignored ")
if (content) append("content ")
if (open) append("open ")
if (relation) append("relation ")
if (suspend) append("suspend ")
append("def ")
if (receiver != null) {
append(receiver)
append(".")
}
append("$name: $type")
if (expr) append(" = ...")
if (extensionDelegateModuleName != null) append(" by <extension in module ${extensionDelegateModuleName.text}>")
}
fun toMemberField(scope: KtScope, owner: DefType, diagnostics: Diagnostics, keepUnknownFields: Boolean) {
if (type == null) {
diagnostics.add(nameRange, "only properties with explicit type supported")
return
}
if (receiver != null) {
todoMemberExtField(diagnostics)
return
}
val valueType = type.build(scope, diagnostics, annotations, keepUnknownFields) ?: return
val field = Field(owner, id, name, valueType)
configure(field)
}
fun todoMemberExtField(diagnostics: Diagnostics) {
diagnostics.add(nameRange, "extension properties inside classes is not supported yet")
}
fun toExtField(scope: KtScope, module: KtObjModule, diagnostics: Diagnostics) {
// if (extensionDelegateModuleName?.text != "Obj") return
//
if (type == null) {
diagnostics.add(nameRange, "only properties with explicit type supported")
return
}
if (receiver == null) {
diagnostics.add(nameRange, "<ObjModule>.extensions() property should have receiver")
return
}
val resolvedReceiver = receiver.build(scope, diagnostics, keepUnknownFields = module.keepUnknownFields)
if (resolvedReceiver !is TRef) {
diagnostics.add(receiver.classifierRange, "Only Obj types supported as receivers")
return
}
id = module.extFields.size + 1 // todo: persistent ids
val receiverObjType = resolvedReceiver.targetObjType
val valueType = type.build(scope, diagnostics, annotations, keepUnknownFields = module.keepUnknownFields) ?: return
val field = ExtField(ExtFieldId(id), receiverObjType, name, valueType)
module.extFields.add(field)
configure(field)
}
private fun configure(field: MemberOrExtField<*, *>) {
field.exDef = this
field.open = open
if (expr) {
field.hasDefault =
if (suspend) Field.Default.suspend
else Field.Default.plain
field.defaultValue = getterBody
}
field.constructorField = constructorParam
field.content = content
field.ignored = ignored
}
companion object : TBlob<DefField>("")
} | apache-2.0 | bebbba81bdb25f1c29d2f09fc6775014 | 30.481132 | 119 | 0.693945 | 4.34375 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/entity/integration/HandlesTestBase.kt | 1 | 58473 | package arcs.core.entity.integration
import arcs.core.data.Capability.Ttl
import arcs.core.data.CollectionType
import arcs.core.data.EntityType
import arcs.core.data.HandleMode
import arcs.core.data.RawEntity
import arcs.core.data.ReferenceType
import arcs.core.data.SingletonType
import arcs.core.entity.Entity
import arcs.core.entity.EntitySpec
import arcs.core.entity.ForeignReferenceChecker
import arcs.core.entity.ForeignReferenceCheckerImpl
import arcs.core.entity.HandleSpec
import arcs.core.entity.ReadCollectionHandle
import arcs.core.entity.ReadSingletonHandle
import arcs.core.entity.ReadWriteCollectionHandle
import arcs.core.entity.ReadWriteQueryCollectionHandle
import arcs.core.entity.ReadWriteSingletonHandle
import arcs.core.entity.ReadableHandle
import arcs.core.entity.Reference
import arcs.core.entity.WriteCollectionHandle
import arcs.core.entity.WriteSingletonHandle
import arcs.core.entity.awaitReady
import arcs.core.entity.testutil.EmptyEntity
import arcs.core.entity.testutil.FixtureEntities
import arcs.core.entity.testutil.FixtureEntity
import arcs.core.entity.testutil.FixtureEntitySlice
import arcs.core.entity.testutil.InnerEntity
import arcs.core.entity.testutil.InnerEntitySlice
import arcs.core.entity.testutil.MoreNested
import arcs.core.entity.testutil.MoreNestedSlice
import arcs.core.entity.testutil.TestInlineParticle_Entities
import arcs.core.entity.testutil.TestInlineParticle_Entities_InlineEntityField
import arcs.core.entity.testutil.TestInlineParticle_Entities_InlineListField
import arcs.core.entity.testutil.TestInlineParticle_Entities_InlineListField_MoreInlinesField
import arcs.core.entity.testutil.TestInlineParticle_Entities_InlinesField
import arcs.core.entity.testutil.TestNumQueryParticle_Entities
import arcs.core.entity.testutil.TestParticle_Entities
import arcs.core.entity.testutil.TestReferencesParticle_Entities
import arcs.core.entity.testutil.TestReferencesParticle_Entities_ReferencesField
import arcs.core.entity.testutil.TestTextQueryParticle_Entities
import arcs.core.host.HandleManagerImpl
import arcs.core.host.SchedulerProvider
import arcs.core.host.SimpleSchedulerProvider
import arcs.core.storage.StorageEndpointManager
import arcs.core.storage.StorageKey
import arcs.core.storage.api.DriverAndKeyConfigurator
import arcs.core.storage.driver.RamDisk
import arcs.core.storage.keys.ForeignStorageKey
import arcs.core.storage.keys.RamDiskStorageKey
import arcs.core.storage.referencemode.ReferenceModeStorageKey
import arcs.core.storage.testutil.testStorageEndpointManager
import arcs.core.storage.testutil.waitForEntity
import arcs.core.storage.testutil.waitForKey
import arcs.core.testutil.handles.dispatchClear
import arcs.core.testutil.handles.dispatchCreateReference
import arcs.core.testutil.handles.dispatchFetch
import arcs.core.testutil.handles.dispatchFetchAll
import arcs.core.testutil.handles.dispatchFetchById
import arcs.core.testutil.handles.dispatchIsEmpty
import arcs.core.testutil.handles.dispatchQuery
import arcs.core.testutil.handles.dispatchRemove
import arcs.core.testutil.handles.dispatchRemoveByQuery
import arcs.core.testutil.handles.dispatchSize
import arcs.core.testutil.handles.dispatchStore
import arcs.core.util.ArcsStrictMode
import arcs.core.util.testutil.LogRule
import arcs.flags.testing.BuildFlagsRule
import arcs.jvm.util.testutil.FakeTime
import com.google.common.truth.Truth.assertThat
import java.util.concurrent.Executors
import kotlin.test.assertFailsWith
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
/**
* This is an integration test for handles. Its subclasses are used to test different
* configurations.
*/
@Suppress("EXPERIMENTAL_API_USAGE", "UNCHECKED_CAST")
open class HandlesTestBase(val params: Params) {
@get:Rule
val log = LogRule()
@get:Rule
val buildFlagsRule = BuildFlagsRule.create()
private val fixtureEntities = FixtureEntities()
protected open fun createStorageKey(
unique: String,
hash: String = FixtureEntity.SCHEMA.hash
): StorageKey = RamDiskStorageKey(unique)
private fun backingKey(
unique: String = "entities",
hash: String = FixtureEntity.SCHEMA.hash
) = createStorageKey(unique, hash)
private val moreNestedsBackingKey get() = createStorageKey("moreNesteds", MoreNested.SCHEMA.hash)
protected lateinit var fakeTime: FakeTime
private val entity1 = FixtureEntity(
entityId = "entity1",
inlineEntityField = fixtureEntities.generateInnerEntity()
)
private val entity2 = FixtureEntity(
entityId = "entity2",
inlineEntityField = fixtureEntities.generateInnerEntity()
)
private val singletonRefKey: StorageKey get() = createStorageKey("single-reference")
private val singletonKey get() = ReferenceModeStorageKey(
backingKey = backingKey(),
storageKey = createStorageKey("single-ent")
)
private val collectionRefKey get() = createStorageKey("set-references")
private val collectionKey get() = ReferenceModeStorageKey(
backingKey = backingKey(),
storageKey = createStorageKey("set-ent")
)
private val moreNestedCollectionRefKey get() = createStorageKey(
"set-moreNesteds",
MoreNested.SCHEMA.hash
)
private val moreNestedCollectionKey get() = ReferenceModeStorageKey(
backingKey = moreNestedsBackingKey,
storageKey = moreNestedCollectionRefKey
)
private val schedulerCoroutineContext =
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val schedulerProvider: SchedulerProvider = SimpleSchedulerProvider(schedulerCoroutineContext)
private val validPackageName = "m.com.a"
private val packageChecker: suspend (String) -> Boolean =
{ name: String -> name == validPackageName }
val foreignReferenceChecker: ForeignReferenceChecker =
ForeignReferenceCheckerImpl(mapOf(EmptyEntity.SCHEMA to packageChecker))
lateinit var readHandleManagerImpl: HandleManagerImpl
lateinit var writeHandleManagerImpl: HandleManagerImpl
private lateinit var monitorHandleManagerImpl: HandleManagerImpl
var testTimeout: Long = 10000
private var i = 0
lateinit var monitorStorageEndpointManager: StorageEndpointManager
open var testRunner = { block: suspend CoroutineScope.() -> Unit ->
monitorHandleManagerImpl = HandleManagerImpl(
arcId = "testArc",
hostId = "monitorHost",
time = fakeTime,
scheduler = schedulerProvider("monitor"),
storageEndpointManager = monitorStorageEndpointManager,
foreignReferenceChecker = foreignReferenceChecker
)
runBlocking {
withTimeout(testTimeout) { block() }
monitorHandleManagerImpl.close()
readHandleManagerImpl.close()
writeHandleManagerImpl.close()
}
}
// Must call from subclasses.
open fun setUp() = runBlocking {
// We need to initialize to -1 instead of the default (999999) because our test cases around
// deleted items where we look for "nulled-out" entities can result in the
// `UNINITIALIZED_TIMESTAMP` being used for creationTimestamp, and others can result in the
// current time being used.
// TODO: Determine why this is happening. It seems for a nulled-out entity, we shouldn't
// use the current time as the creationTimestamp.
fakeTime = FakeTime(-1)
DriverAndKeyConfigurator.configure(null)
RamDisk.clear()
}
protected open fun initStorageEndpointManager(): StorageEndpointManager {
return testStorageEndpointManager()
}
// This method needs to be called from setUp methods of [HandlesTestBase] subclasses after other
// platform specific initialization has occured. Hence it is factored as a separate method, so
// that each subclass could call it at the appropriate time.
protected fun initHandleManagers() {
i++
val readerStorageEndpointManager = initStorageEndpointManager()
monitorStorageEndpointManager = readerStorageEndpointManager
readHandleManagerImpl = HandleManagerImpl(
arcId = "testArc",
hostId = "testHost",
time = fakeTime,
scheduler = schedulerProvider("reader-#$i"),
storageEndpointManager = readerStorageEndpointManager,
foreignReferenceChecker = foreignReferenceChecker
)
val writerStorageEndpointManager = if (params.isSameStore) {
readerStorageEndpointManager
} else initStorageEndpointManager()
writeHandleManagerImpl = if (params.isSameManager) readHandleManagerImpl else {
HandleManagerImpl(
arcId = "testArc",
hostId = "testHost",
time = fakeTime,
scheduler = schedulerProvider("writer-#$i"),
storageEndpointManager = writerStorageEndpointManager,
foreignReferenceChecker = foreignReferenceChecker
)
}
}
@After
open fun tearDown() = runBlocking {
// TODO(b/151366899): this is less than ideal - we should investigate how to make the entire
// test process cancellable/stoppable, even when we cross scopes into a BindingContext or
// over to other RamDisk listeners.
readHandleManagerImpl.close()
writeHandleManagerImpl.close()
schedulerProvider.cancelAll()
}
@Test
fun singleton_initialStateAndSingleHandleOperations() = testRunner {
val handle = writeHandleManagerImpl.createSingletonHandle()
// Don't use the dispatchX helpers so we can test the immediate effect of the handle ops.
withContext(handle.dispatcher) {
// Initial state.
assertThat(handle.fetch()).isNull()
// Verify that clear works on an empty singleton.
val jobs = mutableListOf<Job>()
jobs.add(handle.clear())
assertThat(handle.fetch()).isNull()
// All handle ops should be locally immediate (no joins needed).
jobs.add(handle.store(entity1))
assertThat(handle.fetch()).isEqualTo(entity1)
jobs.add(handle.clear())
assertThat(handle.fetch()).isNull()
// The joins should still work.
jobs.joinAll()
}
}
@Test
fun singleton_writeAndReadBack_unidirectional() = testRunner {
// Write-only handle -> read-only handle
val writeHandle = writeHandleManagerImpl.createHandle(
HandleSpec(
"writeOnlySingleton",
HandleMode.Write,
SingletonType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
singletonKey
).awaitReady() as WriteSingletonHandle<FixtureEntitySlice>
val readHandle = readHandleManagerImpl.createHandle(
HandleSpec(
"readOnlySingleton",
HandleMode.Read,
SingletonType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
singletonKey
).awaitReady() as ReadSingletonHandle<FixtureEntity>
var received = Job()
readHandle.onUpdate { received.complete() }
// Verify store against empty.
writeHandle.dispatchStore(entity1)
received.join()
assertThat(readHandle.dispatchFetch()).isEqualTo(entity1)
// Verify store overwrites existing.
received = Job()
writeHandle.dispatchStore(entity2)
received.join()
assertThat(readHandle.dispatchFetch()).isEqualTo(entity2)
// Verify clear.
received = Job()
writeHandle.dispatchClear()
received.join()
assertThat(readHandle.dispatchFetch()).isNull()
}
@Test
fun singleton_writeAndReadBack_bidirectional() = testRunner {
// Read/write handle <-> read/write handle
val handle1 = writeHandleManagerImpl.createHandle(
HandleSpec(
"readWriteSingleton1",
HandleMode.ReadWrite,
SingletonType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
singletonKey
).awaitReady() as ReadWriteSingletonHandle<FixtureEntity, FixtureEntitySlice>
val handle2 = readHandleManagerImpl.createHandle(
HandleSpec(
"readWriteSingleton2",
HandleMode.ReadWrite,
SingletonType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
singletonKey
).awaitReady() as ReadWriteSingletonHandle<FixtureEntity, FixtureEntitySlice>
// handle1 -> handle2
val received1to2 = Job()
handle2.onUpdate { received1to2.complete() }
// Verify that handle2 sees the entity stored by handle1.
handle1.dispatchStore(entity1)
received1to2.join()
assertThat(handle2.dispatchFetch()).isEqualTo(entity1)
// handle2 -> handle1
var received2to1 = Job()
handle1.onUpdate { received2to1.complete() }
// Verify that handle2 can clear the entity stored by handle1.
handle2.dispatchClear()
received2to1.join()
assertThat(handle1.dispatchFetch()).isNull()
// Verify that handle1 sees the entity stored by handle2.
received2to1 = Job()
handle2.dispatchStore(entity2)
received2to1.join()
assertThat(handle1.dispatchFetch()).isEqualTo(entity2)
}
@Test
fun singleton_dereferenceEntity() = testRunner {
// Arrange: reference handle.
val innerEntitiesStorageKey = ReferenceModeStorageKey(
backingKey(hash = InnerEntity.SCHEMA.hash),
createStorageKey("innerEntities", InnerEntity.SCHEMA.hash)
)
val innerEntitiesHandle =
writeHandleManagerImpl.createSingletonHandle<InnerEntity, InnerEntitySlice>(
storageKey = innerEntitiesStorageKey,
entitySpec = InnerEntity
)
val innerEntity1 = fixtureEntities.generateInnerEntity()
innerEntitiesHandle.dispatchStore(innerEntity1)
// Arrange: entity handle.
val writeHandle = writeHandleManagerImpl.createSingletonHandle()
val readHandle = readHandleManagerImpl.createSingletonHandle()
val readHandleUpdated = readHandle.onUpdateDeferred()
// Act.
writeHandle.dispatchStore(
entity1.mutate(referenceField = innerEntitiesHandle.dispatchCreateReference(innerEntity1))
)
readHandleUpdated.join()
log("Wrote entity1 to writeHandle")
// Assert: read back entity1, and dereference its inner entity.
log("Checking entity1's reference field")
val dereferencedInnerEntity = readHandle.dispatchFetch()!!.referenceField!!.dereference()!!
assertThat(dereferencedInnerEntity).isEqualTo(innerEntity1)
}
@Test
fun singleton_dereferenceEntity_nestedReference() = testRunner {
// Create a stylish new entity, and create a reference to it inside an inlined entity.
val moreNestedCollection = writeHandleManagerImpl.createHandle(
HandleSpec(
"moreNestedCollection",
HandleMode.ReadWrite,
CollectionType(EntityType(MoreNested.SCHEMA)),
MoreNested
),
moreNestedCollectionKey
) as ReadWriteCollectionHandle<MoreNested, MoreNestedSlice>
val nested = fixtureEntities.generateMoreNested()
moreNestedCollection.dispatchStore(nested)
val nestedRef = moreNestedCollection.dispatchCreateReference(nested)
// Give the moreNested to an entity and store it.
val entityWithInnerNestedField = FixtureEntity(
entityId = "entity-with-inner-nested-ref",
inlineEntityField = InnerEntity(moreReferenceField = nestedRef)
)
val writeHandle = writeHandleManagerImpl.createSingletonHandle()
val readHandle = readHandleManagerImpl.createSingletonHandle()
val readOnUpdate = readHandle.onUpdateDeferred()
writeHandle.dispatchStore(entityWithInnerNestedField)
waitForKey(nestedRef.toReferencable().referencedStorageKey(), MORE_NESTED_ENTITY_TYPE)
readOnUpdate.join()
// Read out the entity, and fetch its moreNested.
val entityOut = readHandle.dispatchFetch()!!
val moreNestedRef = entityOut.inlineEntityField.moreReferenceField!!
assertThat(moreNestedRef).isEqualTo(nestedRef)
val moreNested = moreNestedRef.dereference()!!
assertThat(moreNested).isEqualTo(nested)
}
@Test
fun singleton_referenceForeign() = testRunner {
val writeHandle =
writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
val reference = writeHandle.createForeignReference(EmptyEntity, validPackageName)
assertThat(reference).isNotNull()
assertThat(reference!!.toReferencable().storageKey).isEqualTo(ForeignStorageKey("EmptyEntity"))
assertThat(reference.dereference()).isNotNull()
val entity = TestParticle_Entities(textField = "Hello", foreignField = reference)
writeHandle.dispatchStore(entity)
val readHandle =
readHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
assertThat(readHandle.dispatchFetchAll()).containsExactly(entity)
val readBack = readHandle.dispatchFetchAll().single().foreignField!!
assertThat(readBack.entityId).isEqualTo(validPackageName)
assertThat(readBack.dereference()).isNotNull()
// Make an invalid reference.
assertThat(writeHandle.createForeignReference(EmptyEntity, "invalid")).isNull()
}
@Test
fun singleton_noTTL() = testRunner {
val handle = writeHandleManagerImpl.createSingletonHandle()
val handleB = readHandleManagerImpl.createSingletonHandle()
val handleBUpdated = handleB.onUpdateDeferred()
val expectedCreateTime = 123456789L
fakeTime.millis = expectedCreateTime
handle.dispatchStore(entity1)
handleBUpdated.join()
val readBack = handleB.dispatchFetch()!!
assertThat(readBack.creationTimestamp).isEqualTo(expectedCreateTime)
assertThat(readBack.expirationTimestamp).isEqualTo(RawEntity.UNINITIALIZED_TIMESTAMP)
}
@Test
fun singleton_withTTL() = testRunner {
fakeTime.millis = 0
val handle = writeHandleManagerImpl.createSingletonHandle(ttl = Ttl.Days(2))
val handleB = readHandleManagerImpl.createSingletonHandle()
var handleBUpdated = handleB.onUpdateDeferred()
handle.dispatchStore(entity1)
handleBUpdated.join()
val readBack = handleB.dispatchFetch()!!
assertThat(readBack.creationTimestamp).isEqualTo(0)
assertThat(readBack.expirationTimestamp).isEqualTo(2 * 24 * 3600 * 1000)
val handleC = readHandleManagerImpl.createSingletonHandle(ttl = Ttl.Minutes(2))
handleBUpdated = handleB.onUpdateDeferred()
handleC.dispatchStore(entity2)
handleBUpdated.join()
val readBack2 = handleB.dispatchFetch()!!
assertThat(readBack2.creationTimestamp).isEqualTo(0)
assertThat(readBack2.expirationTimestamp).isEqualTo(2 * 60 * 1000)
// Fast forward time to 5 minutes later, so entity2 expires.
fakeTime.millis += 5 * 60 * 1000
assertThat(handleB.dispatchFetch()).isNull()
}
@Test
fun referenceSingleton_withTtl() = testRunner {
fakeTime.millis = 0
// Create and store an entity with no TTL.
val entityHandle = writeHandleManagerImpl.createSingletonHandle()
val refHandle = writeHandleManagerImpl.createReferenceSingletonHandle(ttl = Ttl.Minutes(2))
val updated = entityHandle.onUpdateDeferred()
entityHandle.dispatchStore(entity1)
updated.join()
// Create and store a reference with TTL.
val entity1Ref = entityHandle.dispatchCreateReference(entity1)
refHandle.dispatchStore(entity1Ref)
val readBack = refHandle.dispatchFetch()!!
assertThat(readBack.creationTimestamp).isEqualTo(0)
assertThat(readBack.expirationTimestamp).isEqualTo(2 * 60 * 1000)
// Fast forward time to 5 minutes later, so the reference expires.
fakeTime.millis += 5 * 60 * 1000
assertThat(refHandle.dispatchFetch()).isNull()
}
@Test
fun singleton_referenceLiveness() = testRunner {
// Create and store an entity.
val writeEntityHandle = writeHandleManagerImpl.createCollectionHandle()
val monitorHandle = monitorHandleManagerImpl.createCollectionHandle()
val initialEntityStored = monitorHandle.onUpdateDeferred { it.size() == 1 }
writeEntityHandle.dispatchStore(entity1)
initialEntityStored.join()
log("Created and stored an entity")
// Create and store a reference to the entity.
val entity1Ref = writeEntityHandle.dispatchCreateReference(entity1)
val writeRefHandle = writeHandleManagerImpl.createReferenceSingletonHandle()
val readRefHandle = readHandleManagerImpl.createReferenceSingletonHandle()
val refHeard = readRefHandle.onUpdateDeferred()
writeRefHandle.dispatchStore(entity1Ref)
log("Created and stored a reference")
waitForKey(entity1Ref.toReferencable().referencedStorageKey(), FIXTURE_ENTITY_TYPE)
refHeard.join()
// Now read back the reference from a different handle.
var reference = readRefHandle.dispatchFetch()!!
assertThat(reference).isEqualTo(entity1Ref)
// Reference should be alive.
assertThat(reference.dereference()).isEqualTo(entity1)
var storageReference = reference.toReferencable()
assertThat(storageReference.isAlive()).isTrue()
assertThat(storageReference.isDead()).isFalse()
// Modify the entity.
val modEntity1 = entity1.mutate(textField = "Ben")
val entityModified = monitorHandle.onUpdateDeferred {
it.fetchAll().all { person -> person.textField == "Ben" }
}
writeEntityHandle.dispatchStore(modEntity1)
assertThat(writeEntityHandle.dispatchSize()).isEqualTo(1)
entityModified.join()
waitForEntity(writeEntityHandle, modEntity1, FIXTURE_ENTITY_TYPE)
// Reference should still be alive.
reference = readRefHandle.dispatchFetch()!!
val dereferenced = reference.dereference()
log("Dereferenced: $dereferenced")
assertThat(dereferenced).isEqualTo(modEntity1)
storageReference = reference.toReferencable()
assertThat(storageReference.isAlive()).isTrue()
assertThat(storageReference.isDead()).isFalse()
// Remove the entity from the collection.
val heardTheDelete = monitorHandle.onUpdateDeferred { it.isEmpty() }
writeEntityHandle.dispatchRemove(entity1)
heardTheDelete.join()
waitForEntity(writeEntityHandle, entity1, FIXTURE_ENTITY_TYPE)
// Reference should be dead. (Removed entities currently aren't actually deleted, but
// instead are "nulled out".)
assertThat(storageReference.dereference()).isEqualTo(
fixtureEntities.createNulledOutFixtureEntity("entity1")
)
}
@Test
fun singleton_referenceHandle_referenceModeNotSupported() = testRunner {
val e = assertFailsWith<IllegalArgumentException> {
writeHandleManagerImpl.createReferenceSingletonHandle(
ReferenceModeStorageKey(
backingKey = backingKey(),
storageKey = singletonRefKey
)
)
}
assertThat(e).hasMessageThat().isEqualTo(
"Reference-mode storage keys are not supported for reference-typed handles."
)
}
@Test
fun collection_initialStateAndSingleHandleOperations() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle()
// Don't use the dispatchX helpers so we can test the immediate effect of the handle ops.
withContext(handle.dispatcher) {
// Initial state.
assertThat(handle.size()).isEqualTo(0)
assertThat(handle.isEmpty()).isEqualTo(true)
assertThat(handle.fetchAll()).isEmpty()
// Verify that both clear and removing a random entity with an empty collection are ok.
val jobs = mutableListOf<Job>()
jobs.add(handle.clear())
jobs.add(handle.remove(entity1))
// All handle ops should be locally immediate (no joins needed).
jobs.add(handle.store(entity1))
jobs.add(handle.store(entity2))
assertThat(handle.size()).isEqualTo(2)
assertThat(handle.isEmpty()).isEqualTo(false)
assertThat(handle.fetchAll()).containsExactly(entity1, entity2)
assertThat(handle.fetchById(entity1.entityId!!)).isEqualTo(entity1)
assertThat(handle.fetchById(entity2.entityId!!)).isEqualTo(entity2)
jobs.add(handle.remove(entity1))
assertThat(handle.size()).isEqualTo(1)
assertThat(handle.isEmpty()).isEqualTo(false)
assertThat(handle.fetchAll()).containsExactly(entity2)
assertThat(handle.fetchById(entity1.entityId!!)).isNull()
assertThat(handle.fetchById(entity2.entityId!!)).isEqualTo(entity2)
jobs.add(handle.clear())
assertThat(handle.size()).isEqualTo(0)
assertThat(handle.isEmpty()).isEqualTo(true)
assertThat(handle.fetchAll()).isEmpty()
assertThat(handle.fetchById(entity1.entityId!!)).isNull()
assertThat(handle.fetchById(entity2.entityId!!)).isNull()
// The joins should still work.
jobs.joinAll()
}
}
@Test
fun collection_remove_needsId() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
val entity = TestParticle_Entities(textField = "Hello")
// Entity does not have an ID, it cannot be removed.
assertFailsWith<IllegalStateException> {
handle.dispatchRemove(entity)
}
// Entity with an ID, it can be removed
val entity2 = TestParticle_Entities(textField = "Hello", entityId = "id")
handle.dispatchRemove(entity2)
}
@Test
fun removeByQuery_oneRemoved() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestTextQueryParticle_Entities
)
val entity = TestTextQueryParticle_Entities(textField = "one")
val entity2 = TestTextQueryParticle_Entities(textField = "two")
handle.dispatchStore(entity, entity2)
handle.dispatchRemoveByQuery("two")
assertThat(handle.dispatchFetchAll()).containsExactly(entity)
}
@Test
fun removeByQuery_zeroRemoved() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestTextQueryParticle_Entities
)
val entity = TestTextQueryParticle_Entities(textField = "one")
val entity2 = TestTextQueryParticle_Entities(textField = "two")
handle.dispatchStore(entity, entity2)
handle.dispatchRemoveByQuery("three")
assertThat(handle.dispatchFetchAll()).containsExactly(entity, entity2)
}
@Test
fun removeByQuery_emptyCollection() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
handle.dispatchRemoveByQuery("one")
assertThat(handle.dispatchFetchAll()).isEmpty()
}
@Test
fun removeByQuery_allRemoved() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
val entity = TestParticle_Entities(textField = "two")
val entity2 = TestParticle_Entities(textField = "two")
handle.dispatchStore(entity, entity2)
handle.dispatchRemoveByQuery("two")
assertThat(handle.dispatchFetchAll()).isEmpty()
}
@Test
fun collection_writeAndReadBack_unidirectional() = testRunner {
// Write-only handle -> read-only handle
val writeHandle = writeHandleManagerImpl.createHandle(
HandleSpec(
"writeOnlyCollection",
HandleMode.Write,
CollectionType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
collectionKey
).awaitReady() as WriteCollectionHandle<FixtureEntitySlice>
val readHandle = readHandleManagerImpl.createHandle(
HandleSpec(
"readOnlyCollection",
HandleMode.Read,
CollectionType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
collectionKey
).awaitReady() as ReadCollectionHandle<FixtureEntity>
val entity3 = fixtureEntities.generate(entityId = "entity3")
var received = Job()
var size = 3
readHandle.onUpdate { if (readHandle.size() == size) received.complete() }
// Verify store.
writeHandle.dispatchStore(entity1, entity2, entity3)
received.join()
assertThat(readHandle.dispatchSize()).isEqualTo(3)
assertThat(readHandle.dispatchIsEmpty()).isEqualTo(false)
assertThat(readHandle.dispatchFetchAll()).containsExactly(entity1, entity2, entity3)
assertThat(readHandle.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1)
assertThat(readHandle.dispatchFetchById(entity2.entityId!!)).isEqualTo(entity2)
assertThat(readHandle.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3)
// Verify remove.
received = Job()
size = 2
writeHandle.dispatchRemove(entity2)
received.join()
assertThat(readHandle.dispatchSize()).isEqualTo(2)
assertThat(readHandle.dispatchIsEmpty()).isEqualTo(false)
assertThat(readHandle.dispatchFetchAll()).containsExactly(entity1, entity3)
assertThat(readHandle.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1)
assertThat(readHandle.dispatchFetchById(entity2.entityId!!)).isNull()
assertThat(readHandle.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3)
// Verify clear.
received = Job()
size = 0
writeHandle.dispatchClear()
received.join()
assertThat(readHandle.dispatchSize()).isEqualTo(0)
assertThat(readHandle.dispatchIsEmpty()).isEqualTo(true)
assertThat(readHandle.dispatchFetchAll()).isEmpty()
assertThat(readHandle.dispatchFetchById(entity1.entityId!!)).isNull()
assertThat(readHandle.dispatchFetchById(entity2.entityId!!)).isNull()
assertThat(readHandle.dispatchFetchById(entity3.entityId!!)).isNull()
}
@Test
fun collection_writeAndReadBack_bidirectional() = testRunner {
// Read/write handle <-> read/write handle
val handle1 = writeHandleManagerImpl.createHandle(
HandleSpec(
"readWriteCollection1",
HandleMode.ReadWrite,
CollectionType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
collectionKey
).awaitReady() as ReadWriteCollectionHandle<FixtureEntity, FixtureEntitySlice>
val handle2 = readHandleManagerImpl.createHandle(
HandleSpec(
"readWriteCollection2",
HandleMode.ReadWrite,
CollectionType(EntityType(FixtureEntity.SCHEMA)),
FixtureEntity
),
collectionKey
).awaitReady() as ReadWriteCollectionHandle<FixtureEntity, FixtureEntitySlice>
val entity3 = fixtureEntities.generate(entityId = "entity3")
// handle1 -> handle2
val received1to2 = Job()
handle2.onUpdate { if (handle2.size() == 3) received1to2.complete() }
// Verify that handle2 sees entities stored by handle1.
handle1.dispatchStore(entity1, entity2, entity3)
received1to2.join()
assertThat(handle2.dispatchSize()).isEqualTo(3)
assertThat(handle2.dispatchIsEmpty()).isEqualTo(false)
assertThat(handle2.dispatchFetchAll()).containsExactly(entity1, entity2, entity3)
assertThat(handle2.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1)
assertThat(handle2.dispatchFetchById(entity2.entityId!!)).isEqualTo(entity2)
assertThat(handle2.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3)
// handle2 -> handle1
var received2to1 = Job()
var size2to1 = 2
handle1.onUpdate { if (handle1.size() == size2to1) received2to1.complete() }
// Verify that handle2 can remove entities stored by handle1.
handle2.dispatchRemove(entity2)
received2to1.join()
assertThat(handle1.dispatchSize()).isEqualTo(2)
assertThat(handle1.dispatchIsEmpty()).isEqualTo(false)
assertThat(handle1.dispatchFetchAll()).containsExactly(entity1, entity3)
assertThat(handle2.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1)
assertThat(handle2.dispatchFetchById(entity2.entityId!!)).isNull()
assertThat(handle2.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3)
// Verify that handle1 sees an empty collection after a clear op from handle2.
received2to1 = Job()
size2to1 = 0
handle2.dispatchClear()
received2to1.join()
assertThat(handle1.dispatchSize()).isEqualTo(0)
assertThat(handle1.dispatchIsEmpty()).isEqualTo(true)
assertThat(handle1.dispatchFetchAll()).isEmpty()
assertThat(handle2.dispatchFetchById(entity1.entityId!!)).isNull()
assertThat(handle2.dispatchFetchById(entity2.entityId!!)).isNull()
assertThat(handle2.dispatchFetchById(entity3.entityId!!)).isNull()
}
@Test
fun collection_writeMutatedEntityReplaces() = testRunner {
val entity = TestParticle_Entities(textField = "Hello")
val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
handle.dispatchStore(entity)
assertThat(handle.dispatchFetchAll()).containsExactly(entity)
val modified = entity.mutate(textField = "Changed")
assertThat(modified).isNotEqualTo(entity)
// Entity internals should not change.
assertThat(modified.entityId).isEqualTo(entity.entityId)
assertThat(modified.creationTimestamp).isEqualTo(entity.creationTimestamp)
assertThat(modified.expirationTimestamp).isEqualTo(entity.expirationTimestamp)
handle.dispatchStore(modified)
assertThat(handle.dispatchFetchAll()).containsExactly(modified)
assertThat(handle.dispatchFetchById(entity.entityId!!)).isEqualTo(modified)
}
@Test
fun collection_writeMutatedInlineEntitiesReplaces() = testRunner {
val inline = TestInlineParticle_Entities_InlineEntityField(
longField = 32L,
textField = "inlineString"
)
val inlineSet = setOf(
TestInlineParticle_Entities_InlinesField(numberField = 10.0),
TestInlineParticle_Entities_InlinesField(numberField = 20.0),
TestInlineParticle_Entities_InlinesField(numberField = 30.0)
)
val inlineList = listOf(
TestInlineParticle_Entities_InlineListField(
moreInlinesField = setOf(
TestInlineParticle_Entities_InlineListField_MoreInlinesField(
textsField = setOf("so inline")
)
)
),
TestInlineParticle_Entities_InlineListField(
moreInlinesField = setOf(
TestInlineParticle_Entities_InlineListField_MoreInlinesField(
textsField = setOf("very inline")
)
)
)
)
val entity = TestInlineParticle_Entities(inline, inlineSet, inlineList)
val handle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestInlineParticle_Entities
)
handle.dispatchStore(entity)
val modified = entity.mutate(
inlineEntityField = TestInlineParticle_Entities_InlineEntityField(
longField = 33L,
textField = "inlineString2"
),
inlinesField = setOf(
TestInlineParticle_Entities_InlinesField(numberField = 11.0),
TestInlineParticle_Entities_InlinesField(numberField = 22.0),
TestInlineParticle_Entities_InlinesField(numberField = 33.0)
),
inlineListField = listOf(
TestInlineParticle_Entities_InlineListField(
moreInlinesField = setOf(
TestInlineParticle_Entities_InlineListField_MoreInlinesField(
textsField = setOf("so inline v2")
)
)
),
TestInlineParticle_Entities_InlineListField(
moreInlinesField = setOf(
TestInlineParticle_Entities_InlineListField_MoreInlinesField(
textsField = setOf("very inline v2")
)
)
)
)
)
handle.dispatchStore(modified)
assertThat(handle.dispatchFetchAll()).containsExactly(modified)
}
@Test
fun listsWorkEndToEnd() = testRunner {
val entity = TestParticle_Entities(
textField = "Hello",
numField = 1.0,
longListField = listOf(1L, 2L, 4L, 2L)
)
val writeHandle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestParticle_Entities
)
val readHandle = readHandleManagerImpl.createCollectionHandle(
entitySpec = TestParticle_Entities
)
val updateDeferred = readHandle.onUpdateDeferred { it.size() == 1 }
writeHandle.dispatchStore(entity)
updateDeferred.join()
assertThat(readHandle.dispatchFetchAll()).containsExactly(entity)
}
@Test
fun inlineEntitiesWorkEndToEnd() = testRunner {
val inline = TestInlineParticle_Entities_InlineEntityField(
longField = 32L,
textField = "inlineString"
)
val inlineSet = setOf(
TestInlineParticle_Entities_InlinesField(numberField = 10.0),
TestInlineParticle_Entities_InlinesField(numberField = 20.0),
TestInlineParticle_Entities_InlinesField(numberField = 30.0)
)
val inlineList = listOf(
TestInlineParticle_Entities_InlineListField(
moreInlinesField = setOf(
TestInlineParticle_Entities_InlineListField_MoreInlinesField(
textsField = setOf("so inline")
),
TestInlineParticle_Entities_InlineListField_MoreInlinesField(textsField = setOf("like"))
)
),
TestInlineParticle_Entities_InlineListField(
moreInlinesField = setOf(
TestInlineParticle_Entities_InlineListField_MoreInlinesField(textsField = setOf("very")),
TestInlineParticle_Entities_InlineListField_MoreInlinesField(
textsField = setOf("very inline")
)
)
)
)
val entity = TestInlineParticle_Entities(inline, inlineSet, inlineList)
val writeHandle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestInlineParticle_Entities
)
val readHandle = readHandleManagerImpl.createCollectionHandle(
entitySpec = TestInlineParticle_Entities
)
val updateDeferred = readHandle.onUpdateDeferred { it.size() == 1 }
writeHandle.dispatchStore(entity)
updateDeferred.join()
assertThat(readHandle.dispatchFetchAll()).containsExactly(entity)
}
@Test
fun collectionsOfReferencesWorkEndToEnd() = testRunner {
fun toReferencedEntity(value: Int) = TestReferencesParticle_Entities_ReferencesField(
numberField = value.toDouble()
)
val referencedEntitiesKey = ReferenceModeStorageKey(
backingKey = createStorageKey("referencedEntities"),
storageKey = createStorageKey("set-referencedEntities")
)
val referencedEntityHandle = writeHandleManagerImpl.createCollectionHandle(
referencedEntitiesKey,
entitySpec = TestReferencesParticle_Entities_ReferencesField
)
suspend fun toReferences(values: Iterable<Int>) = values
.map { toReferencedEntity(it) }
.map {
referencedEntityHandle.dispatchStore(it)
referencedEntityHandle.dispatchCreateReference(it)
}
suspend fun toEntity(values: Set<Int>, valueList: List<Int>) =
TestReferencesParticle_Entities(
toReferences(values).toSet(),
toReferences(valueList)
)
val entities = setOf(
toEntity(setOf(1, 2, 3), listOf(3, 3, 4)),
toEntity(setOf(200, 100, 300), listOf(2, 10, 2)),
toEntity(setOf(34, 2145, 1, 11), listOf(3, 4, 5))
)
val writeHandle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestReferencesParticle_Entities
)
val readHandle = readHandleManagerImpl.createCollectionHandle(
entitySpec = TestReferencesParticle_Entities
)
val updateDeferred = readHandle.onUpdateDeferred { it.size() == 3 }
entities.forEach { writeHandle.dispatchStore(it) }
updateDeferred.join()
val entitiesOut = readHandle.dispatchFetchAll()
assertThat(entitiesOut).containsExactlyElementsIn(entities)
entitiesOut.forEach { entity ->
entity.referencesField.forEach { it.dereference() }
entity.referenceListField.forEach { it.dereference() }
}
}
@Test
fun clientCanSetEntityId() = testRunner {
fakeTime.millis = 0
// Ask faketime to increment to test with changing timestamps.
fakeTime.autoincrement = 1
val id = "MyId"
val entity = TestParticle_Entities(textField = "Hello", numField = 1.0, entityId = id)
val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
handle.dispatchStore(entity)
assertThat(handle.dispatchFetchAll()).containsExactly(entity)
// A different entity, with the same ID, should replace the first.
val entity2 = TestParticle_Entities(textField = "New Hello", numField = 1.1, entityId = id)
handle.dispatchStore(entity2)
assertThat(handle.dispatchFetchAll()).containsExactly(entity2)
// Timestamps also get updated.
assertThat(entity2.creationTimestamp).isEqualTo(2)
// An entity with a different ID.
val entity3 = TestParticle_Entities(textField = "Bye", numField = 2.0, entityId = "OtherId")
handle.dispatchStore(entity3)
assertThat(handle.dispatchFetchAll()).containsExactly(entity3, entity2)
}
@Test
fun clientCanSetCreationTimestamp() = testRunner {
fakeTime.millis = 100
val creationTime = 20L
val entity = TestParticle_Entities(
textField = "Hello",
numField = 1.0,
creationTimestamp = creationTime
)
val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities)
handle.dispatchStore(entity)
assertThat(handle.dispatchFetchAll()).containsExactly(entity)
assertThat(entity.creationTimestamp).isEqualTo(20)
// A different entity that reuses the same creation timestamp.
val entity2 = TestParticle_Entities(
textField = "New Hello",
numField = 1.1,
creationTimestamp = entity.creationTimestamp
)
handle.dispatchStore(entity2)
assertThat(handle.dispatchFetchAll()).containsExactly(entity, entity2)
assertThat(entity2.creationTimestamp).isEqualTo(20)
}
@Test
fun collection_entityDereference() = testRunner {
// Arrange: reference handle.
val innerEntitiesStorageKey = ReferenceModeStorageKey(
backingKey(hash = InnerEntity.SCHEMA.hash),
createStorageKey("innerEntities", InnerEntity.SCHEMA.hash)
)
val innerEntitiesHandle =
writeHandleManagerImpl.createCollectionHandle(
storageKey = innerEntitiesStorageKey,
entitySpec = InnerEntity
)
val innerEntity1 = fixtureEntities.generateInnerEntity()
innerEntitiesHandle.dispatchStore(innerEntity1)
// Arrange: entity handle.
val writeHandle = writeHandleManagerImpl.createCollectionHandle()
val readHandle = readHandleManagerImpl.createCollectionHandle()
val monitorHandle = monitorHandleManagerImpl.createCollectionHandle()
val monitorInitialized = monitorHandle.onUpdateDeferred { it.size() == 1 }
val readUpdated = readHandle.onUpdateDeferred { it.size() == 1 }
// Act.
writeHandle.dispatchStore(
entity1.mutate(referenceField = innerEntitiesHandle.dispatchCreateReference(innerEntity1))
)
log("wrote entity1 to writeHandle")
monitorInitialized.join()
readUpdated.join()
log("readHandle and the ramDisk have heard of the update")
// Assert: read back entity1, and dereference its inner entity.
log("Checking entity1's reference field")
val dereferencedInnerEntity =
readHandle.dispatchFetchAll().single().referenceField!!.dereference()!!
assertThat(dereferencedInnerEntity).isEqualTo(innerEntity1)
}
@Test
fun collection_dereferenceEntity_nestedReference() = testRunner {
// Create an entity of type MoreNested, and create a reference to it.
val moreNestedSpec = HandleSpec(
"moreNestedCollection",
HandleMode.ReadWrite,
CollectionType(EntityType(MoreNested.SCHEMA)),
MoreNested
)
val moreNestedCollection = writeHandleManagerImpl.createHandle(
moreNestedSpec,
moreNestedCollectionKey
).awaitReady() as ReadWriteCollectionHandle<MoreNested, MoreNestedSlice>
val moreNestedMonitor = monitorHandleManagerImpl.createHandle(
moreNestedSpec,
moreNestedCollectionKey
).awaitReady() as ReadWriteCollectionHandle<MoreNested, MoreNestedSlice>
val writeHandle = writeHandleManagerImpl.createCollectionHandle()
val readHandle = readHandleManagerImpl.createCollectionHandle()
val nested = MoreNested(entityId = "nested-id", textsField = setOf("nested"))
val moreNestedMonitorKnows = moreNestedMonitor.onUpdateDeferred {
it.fetchAll().find { moreNested -> moreNested.entityId == "nested-id" } != null
}
moreNestedCollection.dispatchStore(nested)
val nestedRef = moreNestedCollection.dispatchCreateReference(nested)
// Give the moreNested to an entity and store it.
val entityWithInnerNestedField = FixtureEntity(
entityId = "entity-with-inner-nested-ref",
inlineEntityField = InnerEntity(moreReferenceField = nestedRef)
)
val readHandleKnows = readHandle.onUpdateDeferred {
it.fetchAll().find { person -> person.entityId == "entity-with-inner-nested-ref" } != null
}
writeHandle.dispatchStore(entityWithInnerNestedField)
// Read out the entity, and fetch its moreNested.
readHandleKnows.join()
val entityOut = readHandle.dispatchFetchAll().single {
it.entityId == "entity-with-inner-nested-ref"
}
val moreNestedRef = entityOut.inlineEntityField.moreReferenceField!!
assertThat(moreNestedRef).isEqualTo(nestedRef)
moreNestedMonitorKnows.join()
val moreNested = moreNestedRef.dereference()!!
assertThat(moreNested).isEqualTo(nested)
}
@Test
fun collection_noTTL() = testRunner {
val monitor = monitorHandleManagerImpl.createCollectionHandle()
val handle = writeHandleManagerImpl.createCollectionHandle()
val handleB = readHandleManagerImpl.createCollectionHandle()
val handleBChanged = handleB.onUpdateDeferred()
val monitorNotified = monitor.onUpdateDeferred()
val expectedCreateTime = 123456789L
fakeTime.millis = expectedCreateTime
handle.dispatchStore(entity1)
monitorNotified.join()
handleBChanged.join()
val readBack = handleB.dispatchFetchAll().first { it.entityId == entity1.entityId }
assertThat(readBack.creationTimestamp).isEqualTo(expectedCreateTime)
assertThat(readBack.expirationTimestamp).isEqualTo(RawEntity.UNINITIALIZED_TIMESTAMP)
}
@Test
fun collection_withTTL() = testRunner {
fakeTime.millis = 0
val handle = writeHandleManagerImpl.createCollectionHandle(ttl = Ttl.Days(2))
val handleB = readHandleManagerImpl.createCollectionHandle()
var handleBChanged = handleB.onUpdateDeferred()
handle.dispatchStore(entity1)
handleBChanged.join()
val readBack = handleB.dispatchFetchAll().first { it.entityId == entity1.entityId }
assertThat(readBack.creationTimestamp).isEqualTo(0)
assertThat(readBack.expirationTimestamp).isEqualTo(2 * 24 * 3600 * 1000)
val handleC = readHandleManagerImpl.createCollectionHandle(ttl = Ttl.Minutes(2))
handleBChanged = handleB.onUpdateDeferred()
handleC.dispatchStore(entity2)
handleBChanged.join()
val readBack2 = handleB.dispatchFetchAll().first { it.entityId == entity2.entityId }
assertThat(readBack2.creationTimestamp).isEqualTo(0)
assertThat(readBack2.expirationTimestamp).isEqualTo(2 * 60 * 1000)
// Fast forward time to 5 minutes later, so entity2 expires, entity1 doesn't.
fakeTime.millis += 5 * 60 * 1000
assertThat(handleB.dispatchSize()).isEqualTo(1)
assertThat(handleB.dispatchFetchAll()).containsExactly(entity1)
}
@Test
fun referenceCollection_withTtl() = testRunner {
fakeTime.millis = 0
val entityHandle = writeHandleManagerImpl.createCollectionHandle()
val refHandle = writeHandleManagerImpl.createReferenceCollectionHandle(ttl = Ttl.Minutes(2))
// Create and store an entity with no TTL.
val updated = entityHandle.onUpdateDeferred()
entityHandle.dispatchStore(entity1)
updated.join()
// Create and store a reference with TTL.
val entity1Ref = entityHandle.dispatchCreateReference(entity1)
refHandle.dispatchStore(entity1Ref)
val readBack = refHandle.dispatchFetchAll().first()
assertThat(readBack.creationTimestamp).isEqualTo(0)
assertThat(readBack.expirationTimestamp).isEqualTo(2 * 60 * 1000)
// Fast forward time to 5 minutes later, so the reference expires.
fakeTime.millis += 5 * 60 * 1000
assertThat(refHandle.dispatchFetchAll()).isEmpty()
assertThat(refHandle.dispatchSize()).isEqualTo(0)
}
@Test
fun collection_addingToA_showsUpInQueryOnB() = testRunner {
val writeHandle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestTextQueryParticle_Entities
)
val readHandle = readHandleManagerImpl.createCollectionHandle(
entitySpec = TestTextQueryParticle_Entities
)
val entity1 = TestTextQueryParticle_Entities(textField = "21.0")
val entity2 = TestTextQueryParticle_Entities(textField = "22.0")
val readUpdatedTwice = readHandle.onUpdateDeferred { it.size() == 2 }
writeHandle.dispatchStore(entity1, entity2)
readUpdatedTwice.join()
// Ensure that the query argument is being used.
assertThat(readHandle.dispatchQuery("21.0")).containsExactly(entity1)
assertThat(readHandle.dispatchQuery("22.0")).containsExactly(entity2)
// Ensure that an empty set of results can be returned.
assertThat(readHandle.dispatchQuery("60.0")).isEmpty()
}
@Test
fun collection_dataConsideredInvalidByRefinementThrows() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle(
entitySpec = TestNumQueryParticle_Entities
)
val entityOne = TestNumQueryParticle_Entities(textField = "one", numField = 1.0)
val entityTwo = TestNumQueryParticle_Entities(textField = "two", numField = 2.0)
handle.dispatchStore(entityOne, entityTwo)
assertThat(handle.dispatchFetchAll()).containsExactly(entityOne, entityTwo)
val invalidEntity = TestNumQueryParticle_Entities(textField = "two", numField = -15.0)
assertFailsWith<IllegalArgumentException> {
handle.dispatchStore(invalidEntity)
}
}
@Test
@Ignore("Need to patch ExpressionEvaluator to check types")
fun collection_queryWithInvalidQueryThrows() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle()
handle.dispatchStore(entity1, entity2)
assertThat(handle.dispatchFetchAll()).containsExactly(entity1, entity2)
// Ensure that queries can be performed with the correct query type.
(handle as ReadWriteQueryCollectionHandle<FixtureEntity, FixtureEntitySlice, Double>)
.dispatchQuery(44.0)
// Ensure that queries cannot be performed with an incorrect query type.
assertFailsWith<ClassCastException> {
(handle as ReadWriteQueryCollectionHandle<FixtureEntity, FixtureEntitySlice, String>)
.dispatchQuery("44")
}
}
@Test
fun collection_referenceLiveness() = testRunner {
// Create and store some entities.
val writeEntityHandle = writeHandleManagerImpl.createCollectionHandle()
val monitorHandle = monitorHandleManagerImpl.createCollectionHandle()
monitorHandle.onUpdate {
log("Monitor Handle: $it")
}
val monitorSawEntities = monitorHandle.onUpdateDeferred {
it.size() == 2
}
writeEntityHandle.dispatchStore(entity1, entity2)
// Wait for the monitor to see the entities (monitor handle is on a separate storage proxy
// with a separate stores-cache, so it requires the entities to have made it to the storage
// media.
monitorSawEntities.join()
// Create a store a reference to the entity.
val entity1Ref = writeEntityHandle.dispatchCreateReference(entity1)
val entity2Ref = writeEntityHandle.dispatchCreateReference(entity2)
val writeRefHandle = writeHandleManagerImpl.createReferenceCollectionHandle()
val readRefHandle = readHandleManagerImpl.createReferenceCollectionHandle()
val refWritesHappened = readRefHandle.onUpdateDeferred {
log("References created so far: $it")
it.size() == 2
}
writeRefHandle.dispatchStore(entity1Ref, entity2Ref)
// Now read back the references from a different handle.
refWritesHappened.join()
var references = readRefHandle.dispatchFetchAll()
assertThat(references).containsExactly(entity1Ref, entity2Ref)
// References should be alive.
// TODO(b/163308113): There's no way to wait for a reference's value to update right now,
// so polling is required.
var values = emptyList<FixtureEntity?>()
while (true) {
values = references.map { it.dereference() }
if (values.containsAll(listOf(entity1, entity2))) {
break
}
}
assertThat(values).containsExactly(entity1, entity2)
references.forEach {
val storageReference = it.toReferencable()
assertThat(storageReference.isAlive()).isTrue()
assertThat(storageReference.isDead()).isFalse()
}
// Modify the entities.
val modEntity1 = entity1.mutate(textField = "Ben")
val modEntity2 = entity2.mutate(textField = "Ben")
val entitiesWritten = monitorHandle.onUpdateDeferred {
log("Heard update with $it")
it.fetchAll().all { person -> person.textField == "Ben" }
}
writeEntityHandle.dispatchStore(modEntity1, modEntity2)
entitiesWritten.join()
waitForEntity(writeEntityHandle, modEntity1, FIXTURE_ENTITY_TYPE)
waitForEntity(writeEntityHandle, modEntity2, FIXTURE_ENTITY_TYPE)
// Reference should still be alive.
// TODO(b/163308113): There's no way to wait for a reference's value to update right now,
// so polling is required.
references = readRefHandle.dispatchFetchAll()
while (true) {
values = references.map { it.dereference() }
if (values[0]?.textField == "Ben" && values[1]?.textField == "Ben") {
break
}
}
assertThat(values).containsExactly(modEntity1, modEntity2)
references.forEach {
val storageReference = it.toReferencable()
assertThat(storageReference.isAlive()).isTrue()
assertThat(storageReference.isDead()).isFalse()
}
log("Removing the entities")
// Remove the entities from the collection.
val entitiesDeleted = monitorHandle.onUpdateDeferred { it.isEmpty() }
writeEntityHandle.dispatchRemove(entity1, entity2)
entitiesDeleted.join()
waitForEntity(writeEntityHandle, entity1, FIXTURE_ENTITY_TYPE)
waitForEntity(writeEntityHandle, entity2, FIXTURE_ENTITY_TYPE)
log("Checking that they are empty when de-referencing.")
// Reference should be dead. (Removed entities currently aren't actually deleted, but
// instead are "nulled out".)
assertThat(references.map { it.toReferencable().dereference() }).containsExactly(
fixtureEntities.createNulledOutFixtureEntity("entity1"),
fixtureEntities.createNulledOutFixtureEntity("entity2")
)
}
@Test
fun collection_referenceHandle_referenceModeNotSupported() = testRunner {
val e = assertFailsWith<IllegalArgumentException> {
writeHandleManagerImpl.createReferenceCollectionHandle(
ReferenceModeStorageKey(
backingKey = backingKey(),
storageKey = collectionRefKey
)
)
}
assertThat(e).hasMessageThat().isEqualTo(
"Reference-mode storage keys are not supported for reference-typed handles."
)
}
@Test
fun arcsStrictMode_handle_operation_fails() = testRunner {
val handle = writeHandleManagerImpl.createCollectionHandle()
ArcsStrictMode.enableStrictHandlesForTest {
assertFailsWith<IllegalStateException> {
handle.clear()
}
}
}
private suspend fun <E : I, I : Entity> HandleManagerImpl.createSingletonHandle(
storageKey: StorageKey = singletonKey,
name: String = "singletonWriteHandle",
ttl: Ttl = Ttl.Infinite(),
entitySpec: EntitySpec<E>
) = createHandle(
HandleSpec(
name,
HandleMode.ReadWrite,
SingletonType(EntityType(entitySpec.SCHEMA)),
entitySpec
),
storageKey,
ttl
).awaitReady() as ReadWriteSingletonHandle<E, I>
private suspend fun HandleManagerImpl.createSingletonHandle(
storageKey: StorageKey = singletonKey,
name: String = "singletonWriteHandle",
ttl: Ttl = Ttl.Infinite()
) = createSingletonHandle(storageKey, name, ttl, FixtureEntity)
private suspend fun HandleManagerImpl.createCollectionHandle(
storageKey: StorageKey = collectionKey,
name: String = "collectionReadHandle",
ttl: Ttl = Ttl.Infinite()
) = createCollectionHandle(storageKey, name, ttl, FixtureEntity)
private suspend fun <E : I, I : Entity> HandleManagerImpl.createCollectionHandle(
storageKey: StorageKey = collectionKey,
name: String = "collectionReadHandle",
ttl: Ttl = Ttl.Infinite(),
entitySpec: EntitySpec<E>
) = createHandle(
HandleSpec(
name,
HandleMode.ReadWriteQuery,
CollectionType(EntityType(entitySpec.SCHEMA)),
entitySpec
),
storageKey,
ttl
).awaitReady() as ReadWriteQueryCollectionHandle<E, I, Any>
private suspend fun HandleManagerImpl.createReferenceSingletonHandle(
storageKey: StorageKey = singletonRefKey,
name: String = "referenceSingletonWriteHandle",
ttl: Ttl = Ttl.Infinite()
) = createHandle(
HandleSpec(
name,
HandleMode.ReadWrite,
SingletonType(ReferenceType(EntityType(FixtureEntity.SCHEMA))),
FixtureEntity
),
storageKey,
ttl
).awaitReady() as ReadWriteSingletonHandle<Reference<FixtureEntity>, Reference<FixtureEntity>>
private suspend fun HandleManagerImpl.createReferenceCollectionHandle(
storageKey: StorageKey = collectionRefKey,
name: String = "referenceCollectionReadHandle",
ttl: Ttl = Ttl.Infinite()
) = createHandle(
HandleSpec(
name,
HandleMode.ReadWriteQuery,
CollectionType(ReferenceType(EntityType(FixtureEntity.SCHEMA))),
FixtureEntity
),
storageKey,
ttl
).awaitReady() as ReadWriteQueryCollectionHandle<
Reference<FixtureEntity>, Reference<FixtureEntity>, Any>
// Note the predicate receives the *handle*, not onUpdate's delta argument.
private fun <H : ReadableHandle<T, U>, T, U> H.onUpdateDeferred(
predicate: (H) -> Boolean = { true }
) = Job().also { deferred ->
onUpdate {
if (deferred.isActive && predicate(this)) {
deferred.complete()
}
}
}
data class Params(
val name: String,
val isSameManager: Boolean,
val isSameStore: Boolean
) {
override fun toString(): String = name
}
companion object {
val SAME_MANAGER = Params(
name = "Same Manager",
isSameManager = true,
isSameStore = true
)
val DIFFERENT_MANAGER = Params(
name = "Different Manager",
isSameManager = false,
isSameStore = true
)
val DIFFERENT_MANAGER_DIFFERENT_STORES = Params(
name = "Different Manager&Different Stores",
isSameManager = false,
isSameStore = false
)
private val FIXTURE_ENTITY_TYPE = EntityType(FixtureEntity.SCHEMA)
private val MORE_NESTED_ENTITY_TYPE = EntityType(MoreNested.SCHEMA)
}
}
| bsd-3-clause | dc269566488501639e039de4ed999839 | 37.092508 | 99 | 0.736147 | 5.087619 | false | true | false | false |
PolymerLabs/arcs | java/arcs/core/crdt/CrdtEntity.kt | 1 | 19055 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.crdt
import arcs.core.common.Referencable
import arcs.core.common.ReferenceId
import arcs.core.crdt.CrdtSet.Data as SetData
import arcs.core.crdt.CrdtSet.IOperation as ISetOp
import arcs.core.crdt.CrdtSet.Operation as SetOp
import arcs.core.crdt.CrdtSingleton.Data as SingletonData
import arcs.core.crdt.CrdtSingleton.IOperation as ISingletonOp
import arcs.core.crdt.CrdtSingleton.Operation as SingletonOp
import arcs.core.data.FieldName
import arcs.core.data.RawEntity
import arcs.core.data.util.ReferencableList
import arcs.core.data.util.ReferencablePrimitive
import java.lang.UnsupportedOperationException
/**
* A [CrdtModel] capable of managing a complex entity consisting of named [CrdtSingleton]s and named
* [CrdtSet]s, each of which can manage various types of [Referencable] data.
*
* The only valid ways to build a [CrdtEntity] are:
* 1. Build an empty one. [RawEntity] can describe the singleton and collection fields that
* exist on an entity without having any of those fields set; by using a [RawEntity] thus
* configured and calling [CrdtEntity.newWithEmptyEntity] one can construct an empty
* [CrdtEntity].
* 2. From valid [CrdtEntity.Data]. This is currently performed in prod by constructing an empty
* [CrdtEntity] of the appropriate shape, and calling [merge] on it with the valid data.
* However, note that it's also valid to directly construct a [CrdtEntity] from Data.
*
* There's also [CrdtEntity.newAtVersionForTest] which takes a [VersionMap] and a [RawEntity].
* Note that this will give all fields in the constructed [CrdtEntity] the same [VersionMap],
* which is generally not what we would expect in production.
*/
class CrdtEntity(
private var _data: Data = Data()
) : CrdtModel<CrdtEntity.Data, CrdtEntity.Operation, RawEntity> {
override val versionMap: VersionMap
get() = _data.versionMap.copy()
override val data: Data
get() = _data.copy()
override val consumerView: RawEntity
get() = data.toRawEntity()
/**
* Builds a [CrdtEntity] from a [RawEntity] with its clock starting at the given [VersionMap].
*/
private constructor(
versionMap: VersionMap,
rawEntity: RawEntity,
/**
* Function to convert the [Referencable]s within [rawEntity] into [Reference] objects
* needed by [CrdtEntity].
*/
referenceBuilder: (Referencable) -> Reference = Reference.Companion::defaultReferenceBuilder
) : this(Data(versionMap, rawEntity, referenceBuilder))
override fun merge(other: Data): MergeChanges<Data, Operation> {
/* ktlint-disable max-line-length */
val singletonChanges =
mutableMapOf<FieldName, MergeChanges<SingletonData<Reference>, ISingletonOp<Reference>>>()
/* ktlint-enable max-line-length */
val collectionChanges =
mutableMapOf<FieldName, MergeChanges<SetData<Reference>, ISetOp<Reference>>>()
var allOps = true
_data.singletons.forEach { (fieldName, singleton) ->
val otherSingleton = other.singletons[fieldName]
if (otherSingleton != null) {
singletonChanges[fieldName] = singleton.merge(otherSingleton.data)
}
if (singletonChanges[fieldName]?.modelChange is CrdtChange.Data ||
singletonChanges[fieldName]?.otherChange is CrdtChange.Data
) {
allOps = false
}
}
_data.collections.forEach { (fieldName, collection) ->
val otherCollection = other.collections[fieldName]
if (otherCollection != null) {
collectionChanges[fieldName] = collection.merge(otherCollection.data)
}
if (collectionChanges[fieldName]?.modelChange is CrdtChange.Data ||
collectionChanges[fieldName]?.otherChange is CrdtChange.Data
) {
allOps = false
}
}
if (_data.creationTimestamp != other.creationTimestamp) {
allOps = false
if (_data.creationTimestamp == RawEntity.UNINITIALIZED_TIMESTAMP) {
_data.creationTimestamp = other.creationTimestamp
} else if (other.creationTimestamp != RawEntity.UNINITIALIZED_TIMESTAMP) {
// Two different values, take minimum.
_data.creationTimestamp = minOf(_data.creationTimestamp, other.creationTimestamp)
}
}
if (_data.expirationTimestamp != other.expirationTimestamp) {
allOps = false
if (_data.expirationTimestamp == RawEntity.UNINITIALIZED_TIMESTAMP) {
_data.expirationTimestamp = other.expirationTimestamp
} else if (other.expirationTimestamp != RawEntity.UNINITIALIZED_TIMESTAMP) {
// Two different values, take minimum.
_data.expirationTimestamp =
minOf(_data.expirationTimestamp, other.expirationTimestamp)
}
}
if (_data.id != other.id) {
allOps = false
if (_data.id == RawEntity.NO_REFERENCE_ID) {
_data.id = other.id
} else if (other.id != RawEntity.NO_REFERENCE_ID) {
// Two different ids, this cannot be as this crdts are keyed by id in the backing store.
throw CrdtException("Found two different values for id, this should be impossible.")
}
}
val oldVersionMap = _data.versionMap.copy()
_data.versionMap = _data.versionMap mergeWith other.versionMap
if (oldVersionMap == other.versionMap) {
@Suppress("RemoveExplicitTypeArguments")
return MergeChanges(
CrdtChange.Operations(mutableListOf<Operation>()),
CrdtChange.Operations(mutableListOf<Operation>())
)
}
return if (allOps) {
val modelOps = mutableListOf<Operation>()
val otherOps = mutableListOf<Operation>()
// Convert all of our CrdtSingleton.Operations and CrdtSet.Operations into
// CrdtEntity.Operations.
singletonChanges.forEach { (fieldName, mergeChanges) ->
modelOps += when (val changes = mergeChanges.modelChange) {
is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) }
// This shouldn't happen, but strong typing forces us to check.
else -> throw CrdtException("Found a Data change when Operations expected")
}
otherOps += when (val changes = mergeChanges.otherChange) {
is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) }
// This shouldn't happen, but strong typing forces us to check.
else -> throw CrdtException("Found a Data change when Operations expected")
}
}
collectionChanges.forEach { (fieldName, mergeChanges) ->
modelOps += when (val changes = mergeChanges.modelChange) {
is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) }
// This shouldn't happen, but strong typing forces us to check.
else -> throw CrdtException("Found a Data change when Operations expected")
}
otherOps += when (val changes = mergeChanges.otherChange) {
is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) }
// This shouldn't happen, but strong typing forces us to check.
else -> throw CrdtException("Found a Data change when Operations expected")
}
}
MergeChanges(
modelChange = CrdtChange.Operations(modelOps),
otherChange = CrdtChange.Operations(otherOps)
)
} else {
val resultData = data // call `data` only once, since it's nontrivial to copy.
// Check if there are no other changes.
val otherChangesEmpty =
singletonChanges.values.all { it.otherChange.isEmpty() } &&
collectionChanges.values.all { it.otherChange.isEmpty() }
val otherChange: CrdtChange<Data, Operation> = if (otherChangesEmpty) {
CrdtChange.Operations(mutableListOf())
} else {
CrdtChange.Data(resultData)
}
if (oldVersionMap == _data.versionMap) {
return MergeChanges(
modelChange = CrdtChange.Operations(mutableListOf<Operation>()),
otherChange = otherChange
)
}
MergeChanges(
modelChange = CrdtChange.Data(resultData),
otherChange = otherChange
)
}
}
override fun applyOperation(op: Operation): Boolean {
return when (op) {
is Operation.SetSingleton ->
_data.singletons[op.field]?.applyOperation(op.toSingletonOp())
is Operation.ClearSingleton ->
_data.singletons[op.field]?.applyOperation(op.toSingletonOp())
is Operation.AddToSet ->
_data.collections[op.field]?.applyOperation(op.toSetOp())
is Operation.RemoveFromSet ->
_data.collections[op.field]?.applyOperation(op.toSetOp())
is Operation.ClearAll -> {
_data.singletons.values.forEach {
it.applyOperation(CrdtSingleton.Operation.Clear(op.actor, versionMap))
}
_data.collections.values.forEach {
it.applyOperation(CrdtSet.Operation.Clear(op.actor, versionMap))
}
_data.creationTimestamp = RawEntity.UNINITIALIZED_TIMESTAMP
_data.expirationTimestamp = RawEntity.UNINITIALIZED_TIMESTAMP
return true
}
}?.also { success ->
if (success) {
_data.versionMap = _data.versionMap mergeWith op.versionMap
}
} ?: throw CrdtException("Invalid op: $op.")
}
/** Defines the type of data managed by [CrdtEntity] for its singletons and collections. */
interface Reference : Referencable {
companion object {
/** Simple converter from [Referencable] to [Reference]. */
fun buildReference(referencable: Referencable): Reference =
ReferenceImpl(referencable.id)
fun wrapReferencable(referencable: Referencable): Reference =
WrappedReferencable(referencable)
fun defaultReferenceBuilder(referencable: Referencable): Reference {
return when (referencable) {
is ReferencableList<*> -> wrapReferencable(referencable)
is ReferencablePrimitive<*> -> buildReference(referencable)
is RawEntity -> wrapReferencable(referencable)
else -> {
throw UnsupportedOperationException(
"Can't use entities with ${referencable::class} fields without " +
"installing a reference builder that can handle them"
)
}
}
}
}
}
data class WrappedReferencable(val referencable: Referencable) : Reference {
override fun unwrap(): Referencable = referencable
override val id: String
get() = referencable.id
}
/** Minimal [Reference] for contents of a singletons/collections in [Data]. */
data class ReferenceImpl(override val id: ReferenceId) : Reference {
override fun unwrap(): Referencable =
ReferencablePrimitive.unwrap(id) ?: this
override fun toString(): String = when (val deref = unwrap()) {
this -> "Reference($id)"
else -> "Reference($deref)"
}
}
/** Data contained within a [CrdtEntity]. */
data class Data(
/** Master version of the entity. */
override var versionMap: VersionMap = VersionMap(),
/** Singleton fields. */
val singletons: Map<FieldName, CrdtSingleton<Reference>> = emptyMap(),
/** Collection fields. */
val collections: Map<FieldName, CrdtSet<Reference>> = emptyMap(),
var creationTimestamp: Long = RawEntity.UNINITIALIZED_TIMESTAMP,
var expirationTimestamp: Long = RawEntity.UNINITIALIZED_TIMESTAMP,
var id: ReferenceId = RawEntity.NO_REFERENCE_ID
) : CrdtData {
/** Builds a [CrdtEntity.Data] object from an initial version and a [RawEntity]. */
constructor(
versionMap: VersionMap,
rawEntity: RawEntity,
referenceBuilder: (Referencable) -> Reference
) : this(
versionMap,
rawEntity.buildCrdtSingletonMap({ versionMap }, referenceBuilder),
rawEntity.buildCrdtSetMap({ versionMap }, referenceBuilder),
rawEntity.creationTimestamp,
rawEntity.expirationTimestamp,
rawEntity.id
)
constructor(
rawEntity: RawEntity,
entityVersion: VersionMap,
versionProvider: (FieldName) -> VersionMap,
referenceBuilder: (Referencable) -> Reference
) : this(
entityVersion,
rawEntity.buildCrdtSingletonMap(versionProvider, referenceBuilder),
rawEntity.buildCrdtSetMap(versionProvider, referenceBuilder),
rawEntity.creationTimestamp,
rawEntity.expirationTimestamp,
rawEntity.id
)
fun toRawEntity() = RawEntity(
id,
singletons.mapValues { it.value.consumerView?.unwrap() },
collections.mapValues {
it.value.consumerView.map { item -> item.unwrap() }.toSet()
},
creationTimestamp,
expirationTimestamp
)
fun toRawEntity(refId: ReferenceId) = RawEntity(
refId,
singletons.mapValues { it.value.consumerView?.unwrap() },
collections.mapValues {
it.value.consumerView.map { item -> item.unwrap() }.toSet()
},
creationTimestamp,
expirationTimestamp
)
/** Makes a deep copy of this [CrdtEntity.Data] object. */
// We can't rely on the Data Class's .copy(param=val,..) because it doesn't deep-copy the
// inners, unfortunately.
/* internal */ fun copy(): Data = Data(
versionMap.copy(),
HashMap(singletons.mapValues { it.value.copy() }),
HashMap(collections.mapValues { it.value.copy() }),
creationTimestamp,
expirationTimestamp,
id
)
companion object {
private fun RawEntity.buildCrdtSingletonMap(
versionProvider: (FieldName) -> VersionMap,
referenceBuilder: (Referencable) -> Reference
): Map<FieldName, CrdtSingleton<Reference>> = singletons.mapValues { entry ->
CrdtSingleton(
versionProvider(entry.key).copy(),
entry.value?.let { referenceBuilder(it) }
)
}
@Suppress("UNCHECKED_CAST")
private fun RawEntity.buildCrdtSetMap(
versionProvider: (FieldName) -> VersionMap,
referenceBuilder: (Referencable) -> Reference
): Map<FieldName, CrdtSet<Reference>> = collections.mapValues { entry ->
val version = versionProvider(entry.key).copy()
CrdtSet(
CrdtSet.DataImpl(
version,
entry.value.map { CrdtSet.DataValue(version.copy(), referenceBuilder(it)) }
.associateBy { it.value.id }
.toMutableMap()
)
)
}
}
}
/** Valid [CrdtOperation]s for [CrdtEntity]. */
sealed class Operation(
open val actor: Actor,
override val versionMap: VersionMap
) : CrdtOperation {
/**
* Represents an [actor] having set the value of a member [CrdtSingleton] [field] to the
* specified [value] at the time denoted by [versionMap].
*/
data class SetSingleton(
override val actor: Actor,
override val versionMap: VersionMap,
val field: FieldName,
val value: Reference
) : Operation(actor, versionMap) {
/**
* Converts the [CrdtEntity.Operation] into its corresponding [CrdtSingleton.Operation].
*/
fun toSingletonOp(): SingletonOp.Update<Reference> =
CrdtSingleton.Operation.Update(actor, versionMap, value)
}
/**
* Represents an [actor] having cleared the value from a member [CrdtSingleton] [field] to
* at the time denoted by [versionMap].
*/
data class ClearSingleton(
override val actor: Actor,
override val versionMap: VersionMap,
val field: FieldName
) : Operation(actor, versionMap) {
/**
* Converts the [CrdtEntity.Operation] into its corresponding [CrdtSingleton.Operation].
*/
fun toSingletonOp(): SingletonOp.Clear<Reference> =
CrdtSingleton.Operation.Clear(actor, versionMap)
}
/**
* Represents an [actor] having added a [Reference] to a member [CrdtSet] [field] at the
* time denoted by [versionMap].
*/
data class AddToSet(
override val actor: Actor,
override val versionMap: VersionMap,
val field: FieldName,
val added: Reference
) : Operation(actor, versionMap) {
/**
* Converts the [CrdtEntity.Operation] into its corresponding [CrdtSet.Operation].
*/
fun toSetOp(): SetOp.Add<Reference> = CrdtSet.Operation.Add(actor, versionMap, added)
}
/**
* Represents an [actor] having removed the a value from a member [CrdtSet] [field] at the
* time denoted by [versionMap].
*/
data class RemoveFromSet(
override val actor: Actor,
override val versionMap: VersionMap,
val field: FieldName,
val removed: ReferenceId
) : Operation(actor, versionMap) {
/**
* Converts the [CrdtEntity.Operation] into its corresponding [CrdtSet.Operation].
*/
fun toSetOp(): SetOp.Remove<Reference> = CrdtSet.Operation.Remove(actor, versionMap, removed)
}
data class ClearAll(
override val actor: Actor,
override val versionMap: VersionMap
) : Operation(actor, versionMap)
}
companion object {
/**
* Builds a [CrdtEntity] from a [RawEntity] with its clock starting at the given [VersionMap].
*
* This is probably not what you want to do in production; all fields end up being given
* the version provided by the [VersionMap].
*/
fun newAtVersionForTest(versionMap: VersionMap, rawEntity: RawEntity): CrdtEntity {
return CrdtEntity(versionMap, rawEntity)
}
/**
* Builds a [CrdtEntity] with no version map information. This is only intended to be used
* with [RawEntity]s that have no field values set!
*/
fun newWithEmptyEntity(rawEntity: RawEntity): CrdtEntity {
return CrdtEntity(VersionMap(), rawEntity)
}
}
}
/** Converts the [RawEntity] into a [CrdtEntity.Data] model, at the given version. */
fun RawEntity.toCrdtEntityData(
versionMap: VersionMap,
referenceBuilder: (Referencable) -> CrdtEntity.Reference = { CrdtEntity.ReferenceImpl(it.id) }
): CrdtEntity.Data = CrdtEntity.Data(versionMap.copy(), this, referenceBuilder)
/** Visible for testing. */
fun ISingletonOp<CrdtEntity.Reference>.toEntityOp(
fieldName: FieldName
): CrdtEntity.Operation = when (this) {
is SingletonOp.Update -> CrdtEntity.Operation.SetSingleton(actor, versionMap, fieldName, value)
is SingletonOp.Clear -> CrdtEntity.Operation.ClearSingleton(actor, versionMap, fieldName)
else -> throw CrdtException("Invalid operation")
}
/** Visible for testing. */
fun ISetOp<CrdtEntity.Reference>.toEntityOp(
fieldName: FieldName
): CrdtEntity.Operation = when (this) {
is SetOp.Add -> CrdtEntity.Operation.AddToSet(actor, versionMap, fieldName, added)
is SetOp.Remove -> CrdtEntity.Operation.RemoveFromSet(actor, versionMap, fieldName, removed)
else -> throw CrdtException("Cannot convert FastForward or Clear to CrdtEntity Operation")
}
| bsd-3-clause | bdba7067eafa1aa3bb1936f08a7b4c1f | 37.417339 | 100 | 0.674993 | 4.76018 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/insert/InsertCharacterAroundCursorAction.kt | 1 | 2804 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.change.insert
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.MutableVimEditor
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimVisualPosition
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.lineLength
import com.maddyhome.idea.vim.api.visualLineToBufferLine
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler
class InsertCharacterAboveCursorAction : ChangeEditorActionHandler.ForEachCaret() {
override val type: Command.Type = Command.Type.INSERT
override fun execute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Boolean {
return if (editor.isOneLineMode()) {
false
} else insertCharacterAroundCursor(editor, caret, -1)
}
}
class InsertCharacterBelowCursorAction : ChangeEditorActionHandler.ForEachCaret() {
override val type: Command.Type = Command.Type.INSERT
override fun execute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Boolean {
return if (editor.isOneLineMode()) {
false
} else insertCharacterAroundCursor(editor, caret, 1)
}
}
/**
* Inserts the character above/below the cursor at the cursor location
*
* @param editor The editor to insert into
* @param caret The caret to insert after
* @param dir 1 for getting from line below cursor, -1 for getting from line above cursor
* @return true if able to get the character and insert it, false if not
*/
private fun insertCharacterAroundCursor(editor: VimEditor, caret: VimCaret, dir: Int): Boolean {
var res = false
var vp = caret.getVisualPosition()
vp = VimVisualPosition(vp.line + dir, vp.column, false)
val len = editor.lineLength(editor.visualLineToBufferLine(vp.line))
if (vp.column < len) {
val offset = editor.visualPositionToOffset(VimVisualPosition(vp.line, vp.column, false)).point
val charsSequence = editor.text()
if (offset < charsSequence.length) {
val ch = charsSequence[offset]
(editor as MutableVimEditor).insertText(caret.offset, ch.toString())
caret.moveToOffset(injector.motion.getOffsetOfHorizontalMotion(editor, caret, 1, true))
res = true
}
}
return res
}
| mit | de617578d3af697ced33c4df9b015bff | 34.493671 | 98 | 0.752853 | 4.147929 | false | false | false | false |
yyYank/Kebab | src/main/kotlin/core/Page.kt | 1 | 6172 | package kebab.core
import js.JavascriptInterface
import kebab.navigator.Navigable
import kebab.support.alert.AlertAndConfirmSupport
import kebab.support.alert.DefaultAlertAndConfirmSupport
import kebab.support.alert.UninitializedAlertAndConfirmSupport
import kebab.support.download.DefaultDownloadSupport
import kebab.support.download.DownloadSupport
import kebab.support.download.UninitializedDownloadSupport
import kebab.support.frame.DefaultFrameSupport
import kebab.support.frame.FrameSupport
import kebab.support.frame.UninitializedFrameSupport
import kebab.support.interaction.DefaultInteractionsSupport
import kebab.support.interaction.InteractionsSupport
import kebab.support.interaction.UninitializedInteractionSupport
import kebab.support.navigate.NavigableSupport
import kebab.support.navigate.Navigatable
import kebab.support.navigate.UninitializedNavigableSupport
import kebab.support.page.DefaultPageContentSupport
import kebab.support.page.PageContentSupport
import kebab.support.page.UninitializedPageContentSupport
import kebab.support.waiting.DefaultWaitingSupport
import kebab.support.waiting.UninitializedWaitingSupport
import kebab.support.waiting.WaitingSupport
import org.openqa.selenium.By
import support.text.TextMatchingSupport
/**
* Created by yy_yank on 2015/12/19.
*/
class Page : Navigatable, PageContentContainer, Initializable, WaitingSupport {
var at = null
var url = ""
var atCheckWaiting = null
private var browser: Browser? = null
var title: String? = null
get () {
return this.browser?.config?.driver?.title
}
// @Delegate
var pageContentSupport: PageContentSupport? = UninitializedPageContentSupport(this)
// @Delegate
var downloadSupport: DownloadSupport? = UninitializedDownloadSupport(this)
var waitingSupport: WaitingSupport = UninitializedWaitingSupport(this)
var textMatchingSupport: TextMatchingSupport = TextMatchingSupport()
var alertAndConfirmSupport: AlertAndConfirmSupport = UninitializedAlertAndConfirmSupport(this)
var navigableSupport: Navigable = UninitializedNavigableSupport(this)
// @Delegate
var frameSupport: FrameSupport = UninitializedFrameSupport(this)
// @Delegate
var interactionsSupport: InteractionsSupport = UninitializedInteractionSupport(this)
/**
* Initialises this page instance, connecting it to the browser.
* <p>
* <b>This method is called internally, and should not be called by users of Kebab.</b>
*/
fun init(browser: Browser): Page {
this.browser = browser
title = browser.config.driver.title
val contentTemplates = PageContentTemplateBuilder.build(browser, DefaultPageContentContainer(), browser.navigatorFactory, "content", this.javaClass)
pageContentSupport = DefaultPageContentSupport(this, contentTemplates, browser.navigatorFactory)
navigableSupport = NavigableSupport(browser.navigatorFactory!!)
downloadSupport = DefaultDownloadSupport(browser)
waitingSupport = DefaultWaitingSupport(browser.config)
frameSupport = DefaultFrameSupport(browser)
interactionsSupport = DefaultInteractionsSupport(browser)
alertAndConfirmSupport = DefaultAlertAndConfirmSupport({ this.getJs() }, browser.config)
return this
}
fun find() = navigableSupport.find()
fun find(index: Int) = navigableSupport.find(index)
fun find(range: ClosedRange<Int>) = navigableSupport.find(range)
fun find(selector: String) = navigableSupport.find(selector)
fun find(selector: String, index: Int) = navigableSupport.find(selector, index)
fun find(selector: String, range: ClosedRange<Int>) = navigableSupport.find(selector, range)
fun find(attributes: MutableMap<String, Any>) = navigableSupport.find(attributes)
fun find(attributes: MutableMap<String, Any>, index: Int) = navigableSupport.find(attributes, index)
fun find(attributes: MutableMap<String, Any>, range: ClosedRange<Int>) = navigableSupport.find(attributes, range)
fun find(attributes: MutableMap<String, Any>, selector: String) = navigableSupport.find(attributes, selector)
fun find(attributes: MutableMap<String, Any>, selector: String, index: Int) = navigableSupport.find(attributes, selector, index)
fun find(attributes: MutableMap<String, Any>, selector: String, range: ClosedRange<Int>) = navigableSupport.find(attributes, selector, range)
fun find(attributes: MutableMap<String, Any>, bySelector: By) = navigableSupport.find(attributes, bySelector)
fun find(attributes: MutableMap<String, Any>, bySelector: By, index: Int) = navigableSupport.find(attributes, bySelector, index)
fun find(attributes: MutableMap<String, Any>, bySelector: By, range: ClosedRange<Int>) = navigableSupport.find(attributes, bySelector, range)
fun find(bySelector: By) = navigableSupport.find(bySelector)
fun find(bySelector: By, index: Int) = navigableSupport.find(bySelector, index)
fun find(bySelector: By, range: ClosedRange<Int>) = navigableSupport.find(bySelector, range)
override fun <T> waitFor(waitPreset: String, f: () -> T): T {
throw UnsupportedOperationException()
}
override fun <T> waitFor(params: Map<String, Any>, waitPreset: String, f: () -> T): T {
throw UnsupportedOperationException()
}
override fun <T> waitFor(f: () -> T): T = waitingSupport.waitFor(f)
override fun <T> waitFor(params: Map<String, Any>, f: () -> T): T {
throw UnsupportedOperationException()
}
override fun <T> waitFor(timeout: Double, f: () -> T): T {
throw UnsupportedOperationException()
}
override fun <T> waitFor(params: Map<String, Any>, timeout: Double, f: () -> T): T {
throw UnsupportedOperationException()
}
override fun <T> waitFor(timeout: Double, interval: Double, f: () -> T): T {
throw UnsupportedOperationException()
}
override fun <T> waitFor(params: Map<String, Any>, timeout: Double, interval: Double, f: () -> T): T {
throw UnsupportedOperationException()
}
fun getJs() = JavascriptInterface(this.browser)
}
interface Initializable {} | apache-2.0 | e7a3a1ed081a8e77075743240262b55f | 45.765152 | 156 | 0.751296 | 4.700685 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadUtilsWrapper.kt | 1 | 4266 | package org.wordpress.android.ui.uploads
import android.app.Activity
import android.content.Intent
import android.view.View
import android.view.View.OnClickListener
import dagger.Reusable
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.store.PostStore.PostError
import org.wordpress.android.ui.uploads.UploadActionUseCase.UploadAction
import org.wordpress.android.ui.uploads.UploadUtils.OnPublishingCallback
import org.wordpress.android.util.SnackbarSequencer
import javax.inject.Inject
/**
* Injectable wrapper around UploadUtils.
*
* UploadUtils interface is consisted of static methods, which makes the client code difficult to test/mock.
* Main purpose of this wrapper is to make testing easier.
*/
@Reusable
class UploadUtilsWrapper @Inject constructor(
private val sequencer: SnackbarSequencer,
private val dispatcher: Dispatcher
) {
fun userCanPublish(site: SiteModel): Boolean {
return UploadUtils.userCanPublish(site)
}
@Suppress("LongParameterList")
fun onMediaUploadedSnackbarHandler(
activity: Activity?,
snackbarAttachView: View?,
isError: Boolean,
mediaList: List<MediaModel?>?,
site: SiteModel?,
messageForUser: String?
) = UploadUtils.onMediaUploadedSnackbarHandler(
activity,
snackbarAttachView,
isError,
mediaList,
site,
messageForUser,
sequencer
)
@JvmOverloads
@Suppress("LongParameterList")
fun onPostUploadedSnackbarHandler(
activity: Activity?,
snackbarAttachView: View?,
isError: Boolean,
isFirstTimePublish: Boolean,
post: PostModel?,
errorMessage: String?,
site: SiteModel?,
onPublishingCallback: OnPublishingCallback? = null
) = UploadUtils.onPostUploadedSnackbarHandler(
activity,
snackbarAttachView,
isError,
isFirstTimePublish,
post,
errorMessage,
site,
dispatcher,
sequencer,
onPublishingCallback
)
@JvmOverloads
@Suppress("LongParameterList")
fun handleEditPostResultSnackbars(
activity: Activity,
snackbarAttachView: View,
data: Intent,
post: PostModel,
site: SiteModel,
uploadAction: UploadAction,
publishPostListener: OnClickListener?,
onPublishingCallback: OnPublishingCallback? = null
) = UploadUtils.handleEditPostModelResultSnackbars(
activity,
dispatcher,
snackbarAttachView,
data,
post,
site,
uploadAction,
sequencer,
publishPostListener,
onPublishingCallback
)
fun showSnackbarError(
view: View?,
message: String?,
buttonTitleRes: Int,
buttonListener: OnClickListener?
) = UploadUtils.showSnackbarError(view, message, buttonTitleRes, buttonListener, sequencer)
fun showSnackbarError(
view: View?,
message: String?
) = UploadUtils.showSnackbarError(view, message, sequencer)
fun showSnackbar(
view: View?,
messageRes: Int
) = UploadUtils.showSnackbar(view, messageRes, sequencer)
fun showSnackbar(
view: View?,
messageText: String
) = UploadUtils.showSnackbar(view, messageText, sequencer)
fun getErrorMessageResIdFromPostError(
postStatus: PostStatus,
isPage: Boolean,
postError: PostError,
isEligibleForAutoUpload: Boolean
) = UploadUtils.getErrorMessageResIdFromPostError(
postStatus,
isPage,
postError,
isEligibleForAutoUpload
)
fun publishPost(
activity: Activity,
post: PostModel,
site: SiteModel,
onPublishingCallback: OnPublishingCallback? = null
) = UploadUtils.publishPost(activity, post, site, dispatcher, onPublishingCallback)
}
| gpl-2.0 | 47fc34dbf0bf98c2f7601d8b11723dae | 29.471429 | 108 | 0.666901 | 5.286245 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/completion/tests/testData/weighers/basic/Callables.kt | 13 | 1358 | public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
fun aaGlobalFun(){}
val aaGlobalProp = 1
open class Base {
fun aaBaseFun(){}
val aaBaseProp = 1
}
class Derived : Base(), Common {
fun aaDerivedFun(){}
val aaDerivedProp = 1
fun foo(y: Y) {
val aaLocalVal = 1
fun aaLocalFun(){}
with (y) {
if (this is Z1 && this is Z2) {
aa<caret>
}
}
}
}
interface X {
fun aaX()
}
interface Y : X {
fun aaY()
}
interface Z1 : Common {
fun aaaZ1()
fun aabZ1()
}
interface Z2 {
fun aaaZ2()
fun aabZ2()
}
interface Common {
fun aazCommon()
}
fun Any.aaAnyExtensionFun(){}
fun Derived.aaExtensionFun(){}
val Any.aaAnyExtensionProp: Int get() = 1
val Derived.aaExtensionProp: Int get() = 1
fun <T> T.aaTypeParamExt(){}
fun X.aaXExt(){}
fun Y.aaYExt(){}
// ORDER: aaLocalVal
// ORDER: aaLocalFun
// ORDER: aaY
// ORDER: aaaZ1
// ORDER: aaaZ2
// ORDER: aabZ1
// ORDER: aabZ2
// ORDER: aaX
// ORDER: aaYExt
// ORDER: aaXExt
// ORDER: aaDerivedProp
// ORDER: aaDerivedFun
// ORDER: aaBaseProp
// ORDER: aaBaseFun
// ORDER: aaExtensionProp
// ORDER: aaExtensionFun
// ORDER: aazCommon
// ORDER: aaAnyExtensionProp
// ORDER: aaAnyExtensionFun
// ORDER: aaGlobalProp
// ORDER: aaGlobalFun
// ORDER: aaTypeParamExt
| apache-2.0 | 811d9e5914f0b53be4e619a08be39fa0 | 15.765432 | 82 | 0.611193 | 3.011086 | false | false | false | false |
SneakSpeak/sp-android | app/src/main/kotlin/io/sneakspeak/sneakspeak/fragments/ChatFragment.kt | 1 | 3794 | package io.sneakspeak.sneakspeak.fragments
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.annotation.UiThread
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.text.format.Time
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.gcm.GoogleCloudMessaging
import io.sneakspeak.sneakspeak.activities.MainActivity
import io.sneakspeak.sneakspeak.R
import io.sneakspeak.sneakspeak.SneakSpeak
import io.sneakspeak.sneakspeak.adapters.ChatAdapter
import io.sneakspeak.sneakspeak.data.Channel
import io.sneakspeak.sneakspeak.data.Message
import io.sneakspeak.sneakspeak.managers.DatabaseManager
import io.sneakspeak.sneakspeak.managers.HttpManager
import io.sneakspeak.sneakspeak.managers.SettingsManager
import io.sneakspeak.sneakspeak.receiver.MessageResultReceiver
import kotlinx.android.synthetic.main.fragment_chat.*
import org.jetbrains.anko.async
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.uiThread
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
class ChatFragment(user: String?) : Fragment(), View.OnClickListener, MessageResultReceiver.Receiver {
init {
chatUser = user
chatChannel = null
}
constructor(channel: Channel) : this(null) {
chatChannel = channel
}
val TAG = "ChatFragment"
companion object {
var messageReceiver: MessageResultReceiver? = null
var chatUser: String? = null
var chatChannel: Channel? = null
}
lateinit var adapter: ChatAdapter
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
if (resultData == null) return
adapter.addMessage(Message(resultData.getString("sender"),
resultData.getString("message"), resultData.getString("time")))
messageList.scrollToPosition(adapter.itemCount - 1)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, bundle: Bundle?)
= inflater?.inflate(R.layout.fragment_chat, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
sendButton.setOnClickListener(this)
adapter = ChatAdapter()
messageList.adapter = adapter
val manager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
manager.stackFromEnd = true
messageList.layoutManager = manager
messageReceiver = MessageResultReceiver(Handler())
}
override fun onClick(button: View?) {
if (messageText.text.isEmpty()) return
val df = SimpleDateFormat("HH:mm:ss")
val time = df.format(Calendar.getInstance().time)
adapter.addMessage(Message(SettingsManager.getUsername(),
messageText.text.toString(), time))
messageList.scrollToPosition(adapter.itemCount - 1)
val server = DatabaseManager.getCurrentServer()
if (server == null) {
toast("Something is wrong.")
return
}
async() {
if (chatUser != null) {
HttpManager.sendMessage(server, chatUser ?: return@async, messageText.text.toString())
} else {
HttpManager.sendChannelMessage(server, chatChannel ?: return@async, messageText.text.toString())
}
uiThread {
messageText.text.clear()
}
}
}
override fun onResume() {
super.onResume()
messageReceiver?.receiver = this
}
override fun onPause() {
super.onPause()
messageReceiver?.receiver = null
}
}
| mit | ea0bb29ecbf3f788e6cf55088f799568 | 31.152542 | 112 | 0.702688 | 4.851662 | false | false | false | false |
all-of-us/workbench | api/src/main/java/org/pmiops/workbench/actionaudit/targetproperties/PreviousNewValuePair.kt | 1 | 378 | package org.pmiops.workbench.actionaudit.targetproperties
data class PreviousNewValuePair(var previousValue: String?, var newValue: String?) {
val valueChanged: Boolean
get() {
return previousValue == null && newValue != null ||
newValue == null && previousValue != null ||
previousValue != newValue
}
}
| bsd-3-clause | e9b3d87d12cf0294aae9227a9d71d789 | 33.363636 | 84 | 0.608466 | 5.641791 | false | false | false | false |
thaapasa/jalkametri-android | app/src/main/java/fi/tuska/jalkametri/gui/TextIconView.kt | 1 | 1205 | package fi.tuska.jalkametri.gui
import android.content.Context
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import fi.tuska.jalkametri.R
class TextIconView(context: Context, vertical: Boolean, gravity: Int) : LinearLayout(context) {
private lateinit var textView: TextView
private lateinit var iconView: ImageView
init {
this.gravity = gravity
}
var text: String
get() = textView.text.toString()
set(text) {
textView.text = text
}
private fun initView(vertical: Boolean) {
val li = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
li.inflate(layout(vertical), this, true)
textView = findViewById(R.id.text) as TextView
iconView = findViewById(R.id.icon) as ImageView
}
fun layout(vertical: Boolean) = if (vertical) R.layout.text_icon_vertical else R.layout.text_icon_horizontal
fun setImageResource(resID: Int) {
iconView.setImageResource(resID)
}
override fun toString(): String = text
init {
initView(vertical)
}
}
| mit | f0412135b8778cd46dc3e908e253a41e | 25.195652 | 112 | 0.682158 | 4.22807 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/list/ChallengeListViewState.kt | 1 | 2097 | package io.ipoli.android.challenge.list
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
/**
* Created by Venelin Valkov <[email protected]>
* on 03/05/2018.
*/
sealed class ChallengeListAction : Action {
object Load : ChallengeListAction()
object AddChallenge : ChallengeListAction()
}
object ChallengeListReducer : BaseViewStateReducer<ChallengeListViewState>() {
override fun reduce(
state: AppState,
subState: ChallengeListViewState,
action: Action
) =
when (action) {
is ChallengeListAction.Load ->
createState(state.dataState.challenges, subState)
is ChallengeListAction.AddChallenge ->
subState.copy(
type = ChallengeListViewState.StateType.SHOW_ADD
)
is DataLoadedAction.ChallengesChanged ->
createState(action.challenges, subState)
else -> subState
}
private fun createState(challenges: List<Challenge>?, state: ChallengeListViewState) =
when {
challenges == null -> state.copy(type = ChallengeListViewState.StateType.LOADING)
challenges.isEmpty() -> state.copy(type = ChallengeListViewState.StateType.EMPTY)
else -> state.copy(
type = ChallengeListViewState.StateType.DATA_CHANGED,
challenges = createChallengeItems(challenges)
)
}
override fun defaultState() = ChallengeListViewState(
type = ChallengeListViewState.StateType.LOADING,
challenges = emptyList()
)
override val stateKey = key<ChallengeListViewState>()
}
data class ChallengeListViewState(val type: StateType, val challenges: List<ChallengeItem>) :
BaseViewState() {
enum class StateType {
LOADING, EMPTY, SHOW_ADD, DATA_CHANGED
}
} | gpl-3.0 | bb685b37f0c31d73acaa85458bb2a410 | 29.852941 | 93 | 0.672866 | 5.203474 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/quest/schedule/ScheduleViewState.kt | 1 | 4560 | package io.ipoli.android.quest.schedule
import android.content.Context
import io.ipoli.android.common.AppDataState
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.common.text.CalendarFormatter
import io.ipoli.android.player.data.Player
import io.ipoli.android.quest.schedule.agenda.view.AgendaAction
import io.ipoli.android.quest.schedule.calendar.CalendarAction
import org.threeten.bp.LocalDate
/**
* Created by Venelin Valkov <[email protected]>
* on 10/21/17.
*/
sealed class ScheduleAction : Action {
object ToggleViewMode : ScheduleAction()
object ToggleAgendaPreviewMode : ScheduleAction()
data class Load(val viewMode: Player.Preferences.AgendaScreen) : ScheduleAction()
object GoToToday : ScheduleAction()
object ResetAgendaDate : ScheduleAction()
}
object ScheduleReducer : BaseViewStateReducer<ScheduleViewState>() {
override val stateKey = key<ScheduleViewState>()
override fun defaultState() =
ScheduleViewState(
type = ScheduleViewState.StateType.LOADING,
currentDate = LocalDate.now(),
viewMode = Player.Preferences.AgendaScreen.AGENDA
)
override fun reduce(state: AppState, subState: ScheduleViewState, action: Action) =
when (action) {
is ScheduleAction ->
reduceCalendarAction(
state.dataState,
subState,
action
)
is CalendarAction.ChangeDate ->
subState.copy(
type = ScheduleViewState.StateType.SWIPE_DATE_CHANGED,
currentDate = action.date
)
is AgendaAction.AutoChangeDate ->
autoChangeDate(subState, action.date)
is AgendaAction.ChangePreviewDate ->
autoChangeDate(subState, action.date)
else -> subState
}
private fun autoChangeDate(
subState: ScheduleViewState,
date: LocalDate
) =
if (subState.currentDate.isEqual(date)) {
subState.copy(
type = ScheduleViewState.StateType.IDLE
)
} else {
subState.copy(
type = ScheduleViewState.StateType.DATE_AUTO_CHANGED,
currentDate = date
)
}
private fun reduceCalendarAction(
dataState: AppDataState,
state: ScheduleViewState,
action: ScheduleAction
) =
when (action) {
is ScheduleAction.Load -> {
if (state.type != ScheduleViewState.StateType.LOADING) {
state.copy(
currentDate = dataState.agendaDate
)
} else {
state.copy(
type = ScheduleViewState.StateType.INITIAL,
viewMode = action.viewMode,
currentDate = dataState.agendaDate
)
}
}
is ScheduleAction.ToggleViewMode -> {
state.copy(
type = ScheduleViewState.StateType.VIEW_MODE_CHANGED,
viewMode = if (state.viewMode == Player.Preferences.AgendaScreen.DAY)
Player.Preferences.AgendaScreen.AGENDA
else
Player.Preferences.AgendaScreen.DAY
)
}
is ScheduleAction.GoToToday -> {
state.copy(
type = ScheduleViewState.StateType.DATE_AUTO_CHANGED,
currentDate = LocalDate.now()
)
}
else -> state
}
}
data class ScheduleViewState(
val type: StateType,
val currentDate: LocalDate,
val viewMode: Player.Preferences.AgendaScreen
) : BaseViewState() {
enum class StateType {
LOADING, INITIAL, IDLE,
CALENDAR_DATE_CHANGED,
SWIPE_DATE_CHANGED,
DATE_PICKER_CHANGED,
VIEW_MODE_CHANGED,
DATE_AUTO_CHANGED
}
}
val ScheduleViewState.viewModeTitle
get() = if (viewMode == Player.Preferences.AgendaScreen.DAY) "Agenda" else "Calendar"
fun ScheduleViewState.dayText(context: Context) =
CalendarFormatter(context).day(currentDate)
fun ScheduleViewState.dateText(context: Context) =
CalendarFormatter(context).date(currentDate) | gpl-3.0 | 5d338d53caaed485f2a834893a46749f | 30.027211 | 89 | 0.597368 | 5.283893 | false | false | false | false |
andgate/Ikou | core/src/com/andgate/ikou/ui/SinglePlayerUI.kt | 1 | 2925 | package com.andgate.ikou.ui;
import com.andgate.ikou.Constants;
import com.andgate.ikou.Ikou;
import com.andgate.ikou.actor.maze.MazeActor;
import com.andgate.ikou.actor.player.PlayerActor;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Disposable;
class SinglePlayerUI(val game: Ikou,
val maze: MazeActor,
val player: PlayerActor)
: Disposable
{
private val TAG: String = "HelpScreen"
val stage = Stage()
private val uiLabelStyle = Label.LabelStyle(game.arial_fnt, Color.BLACK)
private var depthLabel = Label("", uiLabelStyle)
private var fpsLabel = Label("", uiLabelStyle)
private var game_ui_font_scale: Float = 0f
private var debug_font_scale: Float = 0f
init
{
val bg = Constants.BACKGROUND_COLOR
Gdx.gl.glClearColor(bg.r, bg.g, bg.b, bg.a)
}
fun build()
{
stage.clear()
stage.getViewport().setWorldSize(Gdx.graphics.getWidth().toFloat(), Gdx.graphics.getHeight().toFloat())
stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true)
calc_font_size()
val depthString: String = "" + player.model.transform.getTranslation(Vector3()).y
depthLabel = Label(depthString, uiLabelStyle)
depthLabel.setText(depthString)
depthLabel.setFontScale(game_ui_font_scale)
fpsLabel.setFontScale(debug_font_scale)
val seedString: String = "Seed: " + maze.seed_phrase
val seedLabel = Label(seedString, uiLabelStyle)
seedLabel.setFontScale(debug_font_scale)
val infoTable = Table()
infoTable.add(depthLabel).expandX().row()
if(game.debug) {
infoTable.add(fpsLabel).left().row()
infoTable.add(seedLabel).left().row()
}
infoTable.setBackground(game.whiteTransparentOverlay)
val table = Table()
table.setFillParent(true)
table.top().left()
table.add(infoTable).expandX().fillX()
stage.addActor(table)
//stage.setDebugAll(true)
}
fun update()
{
val depthString: String = "" + (player.model.transform.getTranslation(Vector3()).y)
depthLabel.setText(depthString)
val fpsString: String = "FPS: " + Gdx.graphics.getFramesPerSecond()
fpsLabel.setText(fpsString)
}
private fun calc_font_size()
{
val font_scale_factor: Float = game.ppu / Constants.ARIAL_FONT_SIZE
game_ui_font_scale = Constants.GAME_UI_FONT_UNIT_SIZE * font_scale_factor
debug_font_scale = Constants.DEBUG_FONT_UNIT_SIZE * font_scale_factor
}
override fun dispose()
{
stage.dispose()
}
}
| gpl-2.0 | 1ca6398c0dbf1ae2b72885088bc8769a | 29.789474 | 111 | 0.657436 | 3.798701 | false | false | false | false |
ianhanniballake/ContractionTimer | mobile/src/main/java/com/ianhanniballake/contractiontimer/ui/TimePickerDialogFragment.kt | 1 | 4062 | package com.ianhanniballake.contractiontimer.ui
import android.app.Dialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import androidx.fragment.app.DialogFragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.ianhanniballake.contractiontimer.BuildConfig
import com.ikovac.timepickerwithseconds.view.MyTimePickerDialog
import java.util.Calendar
/**
* Provides a DialogFragment for selecting a time
*/
class TimePickerDialogFragment : DialogFragment() {
companion object {
private const val TAG = "TimePickerDialog"
/**
* Argument key for storing/retrieving the callback action
*/
const val CALLBACK_ACTION = "com.ianhanniballake.contractiontimer.CALLBACK_ACTION_ARGUMENT"
/**
* Extra corresponding with the hour of the day that was set
*/
const val HOUR_OF_DAY_EXTRA = "com.ianhanniballake.contractionTimer.HOUR_OF_DAY_EXTRA"
/**
* Extra corresponding with the minute that was set
*/
const val MINUTE_EXTRA = "com.ianhanniballake.contractionTimer.MINUTE_EXTRA"
/**
* Extra corresponding with the second that was set
*/
const val SECOND_EXTRA = "com.ianhanniballake.contractionTimer.SECOND_EXTRA"
/**
* Argument key for storing/retrieving the time associated with this dialog
*/
const val TIME_ARGUMENT = "com.ianhanniballake.contractiontimer.TIME_ARGUMENT"
/**
* Gets an API level specific implementation of the time picker
*
* @param context context used to create the Dialog
* @param callback Callback to pass the returned time to
* @param date starting date
* @return A valid TimePickerDialog
*/
private fun getTimePickerDialog(
context: Context,
callback: TimePickerDialogFragment,
date: Calendar
): Dialog {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
val onTimeSetListener = MyTimePickerDialog.OnTimeSetListener { _, hourOfDay, minute, seconds ->
callback.onTimeSet(hourOfDay, minute, seconds)
}
return MyTimePickerDialog(context,
onTimeSetListener,
date.get(Calendar.HOUR_OF_DAY),
date.get(Calendar.MINUTE),
date.get(Calendar.SECOND),
DateFormat.is24HourFormat(context))
} else {
val onTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
callback.onTimeSet(hourOfDay, minute, 0)
}
return TimePickerDialog(context,
onTimeSetListener,
date.get(Calendar.HOUR_OF_DAY),
date.get(Calendar.MINUTE),
DateFormat.is24HourFormat(context))
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val date = requireArguments().getSerializable(TIME_ARGUMENT) as Calendar
val dialog = getTimePickerDialog(requireContext(), this, date)
dialog.setOnDismissListener(this)
return dialog
}
internal fun onTimeSet(hourOfDay: Int, minute: Int, second: Int) {
val action = requireArguments().getString(CALLBACK_ACTION)
if (BuildConfig.DEBUG)
Log.d(TAG, "onTimeSet: $action")
val broadcast = Intent(action).apply {
putExtra(HOUR_OF_DAY_EXTRA, hourOfDay)
putExtra(MINUTE_EXTRA, minute)
putExtra(SECOND_EXTRA, second)
}
val localBroadcastManager = LocalBroadcastManager.getInstance(requireContext())
localBroadcastManager.sendBroadcast(broadcast)
}
}
| bsd-3-clause | b92a6cdc5253041e9b52ca134c735640 | 40.030303 | 111 | 0.632447 | 5.351779 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/exception/EntityClassNotFoundException.kt | 1 | 1234 | package com.onyx.exception
/**
* Created by timothy.osborn on 12/6/14.
*
* Class that is trying to work on is not a persistable type
*/
class EntityClassNotFoundException @JvmOverloads constructor(message: String? = "") : OnyxException(message) {
private var entityClassName: String? = null
/**
* Constructor with message
*
* @param message Error message
*/
constructor(message: String, entityType: Class<*>) : this(message + " for class " + entityType.name) {
entityClassName = entityType.name
}
companion object {
const val RELATIONSHIP_ENTITY_BASE_NOT_FOUND = "Relationship type does not extend from ManagedEntity"
const val RELATIONSHIP_ENTITY_NOT_FOUND = "Relationship type does not have entity annotation"
const val ENTITY_NOT_FOUND = "Entity is not able to persist because entity annotation does not exist"
const val PERSISTED_NOT_FOUND = "Entity is not able to persist because entity does not implement IManagedEntity"
const val EXTENSION_NOT_FOUND = "Entity is not able to persist because entity does not extend from ManagedEntity"
const val TO_MANY_INVALID_TYPE = "To Many relationship must by type List.class"
}
}
| agpl-3.0 | f030b1fd78d166ca38f22a8b1185651a | 40.133333 | 121 | 0.706645 | 4.587361 | false | false | false | false |
aedans/Quartz | compiler/src/main/kotlin/io/quartz/gen/jvm/asm/JvmClassGenerator.kt | 1 | 1654 | package io.quartz.gen.jvm.asm
import io.quartz.gen.jvm.JvmGenerator
import io.quartz.gen.jvm.tree.*
import io.quartz.nil
import io.quartz.tree.util.Name
import org.objectweb.asm.*
import org.objectweb.asm.commons.*
fun JvmClass.generate(jg: JvmGenerator) = run {
val cg = ClassGenerator(jg, name, ClassWriter(ClassWriter.COMPUTE_FRAMES))
val access = Opcodes.ACC_PUBLIC +
(if (isFinal) Opcodes.ACC_FINAL else 0) +
(if (isInterface) Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT else 0)
annotations.forEach { it.generate(cg) }
cg.run {
cw.visit(
Opcodes.V1_8,
access,
name.locatableString,
classSignature(foralls, listOf(JvmType.`object`) + interfaces),
"java/lang/Object",
interfaces.map { it.qualified }.toTypedArray()
)
if (!isInterface)
visitDefaultConstructor()
decls.forEach { it.generate(cg) }
cw.visitEnd()
cw
}
}
fun ClassGenerator.visitDefaultConstructor() = run {
val ga = GeneratorAdapter(Opcodes.ACC_PUBLIC, Method.getMethod("void <init> ()"), null, emptyArray(), cw)
ga.loadThis()
ga.invokeConstructor(JvmType.`object`.asmType, Method.getMethod("void <init> ()"))
ga.returnValue()
ga.visitEnd()
}
fun classSignature(
foralls: Set<Name>,
superTypes: List<JvmType>
) = when (foralls) {
nil -> ""
else -> foralls.joinToString(prefix = "<", postfix = ">", separator = "") { "${it.string}:Ljava/lang/Object;" }
} + superTypes.joinToString(separator = "", prefix = "", postfix = "") { it.signature }
| mit | da4df881312f5cdfbbaaa5bfd61abdf5 | 34.191489 | 115 | 0.622128 | 3.882629 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/NextBookmarkService.kt | 5 | 3610 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.*
import com.intellij.ide.bookmark.BookmarkBundle.messagePointer
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Supplier
internal class NextBookmarkAction : IterateBookmarksAction(true, messagePointer("bookmark.go.to.next.action.text"))
internal class PreviousBookmarkAction : IterateBookmarksAction(false, messagePointer("bookmark.go.to.previous.action.text"))
internal abstract class IterateBookmarksAction(val forward: Boolean, dynamicText: Supplier<String>) : DumbAwareAction(dynamicText) {
private val AnActionEvent.nextBookmark
get() = project?.service<NextBookmarkService>()?.next(forward, contextBookmark as? LineBookmark)
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = when (val view = event.bookmarksView) {
null -> event.nextBookmark != null
else -> if (forward) view.hasNextOccurence() else view.hasPreviousOccurence()
}
}
override fun actionPerformed(event: AnActionEvent) {
when (val view = event.bookmarksView) {
null -> event.nextBookmark?.run { if (canNavigate()) navigate(true) }
else -> if (forward) view.goNextOccurence() else view.goPreviousOccurence()
}
}
}
internal class NextBookmarkService(private val project: Project) : BookmarksListener, Comparator<LineBookmark> {
private val cache = AtomicReference<List<LineBookmark>>()
private val bookmarks: List<LineBookmark>
get() = BookmarksManager.getInstance(project)?.bookmarks?.filterIsInstance<LineBookmark>()?.sortedWith(this) ?: emptyList()
private fun getCachedBookmarks() = synchronized(cache) {
cache.get() ?: bookmarks.also { cache.set(it) }
}
override fun bookmarkAdded(group: BookmarkGroup, bookmark: Bookmark) = bookmarksChanged(bookmark)
override fun bookmarkRemoved(group: BookmarkGroup, bookmark: Bookmark) = bookmarksChanged(bookmark)
private fun bookmarksChanged(bookmark: Bookmark) {
if (bookmark is LineBookmark) cache.set(null)
}
private fun compareFiles(bookmark1: LineBookmark, bookmark2: LineBookmark) = bookmark1.file.path.compareTo(bookmark2.file.path)
private fun compareLines(bookmark1: LineBookmark, bookmark2: LineBookmark) = bookmark1.line.compareTo(bookmark2.line)
override fun compare(bookmark1: LineBookmark, bookmark2: LineBookmark) = when (val result = compareFiles(bookmark1, bookmark2)) {
0 -> compareLines(bookmark1, bookmark2)
else -> result
}
private fun next(forward: Boolean, index: Int) = when {
index < 0 -> (-index - if (forward) 1 else 2)
else -> (index - if (forward) -1 else 1)
}
fun next(forward: Boolean, bookmark: LineBookmark?): LineBookmark? {
val bookmarks = getCachedBookmarks().ifEmpty { return null }
if (bookmark != null) {
val next = bookmarks.getOrNull(next(forward, bookmarks.binarySearch(bookmark, this)))
if (next != null || !BookmarkOccurrence.cyclic) return next
}
return if (forward) bookmarks.first() else bookmarks.last()
}
init {
project.messageBus.connect(project).subscribe(BookmarksListener.TOPIC, this)
}
}
| apache-2.0 | 47bcf2242c9c65db3f0fc1ad1557d39b | 45.883117 | 132 | 0.760388 | 4.429448 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogCommitSelection.kt | 5 | 2057 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.vcs.log
import com.intellij.util.Consumer
import org.jetbrains.annotations.ApiStatus
/**
* Commit selection in the Vcs Log table.
*
* @see VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION
*/
@ApiStatus.Experimental
interface VcsLogCommitSelection {
/**
* Selection size.
*/
val size: Int
/**
* Identifiers of the commits selected in the table.
*
* @see com.intellij.vcs.log.data.VcsLogStorage.getCommitIndex
*/
val ids: List<Int>
/**
* [CommitId] of the commits selected in the table.
*/
val commits: List<CommitId>
/**
* Cached metadata of the commits selected in the table.
* When metadata of the commit is not available in the cache, a placeholder object
* (an instance of [com.intellij.vcs.log.data.LoadingDetails]) is returned.
*
* Metadata are loaded faster than full details and since it is done while scrolling,
* there is a better chance that details for a commit are loaded when user selects it.
*
* @see com.intellij.vcs.log.data.LoadingDetails
*/
val cachedMetadata: List<VcsCommitMetadata>
/**
* Cached full details of the commits selected in the table.
* When full details of the commit are not available in the cache, a placeholder object
* (an instance of [com.intellij.vcs.log.data.LoadingDetails]) is returned.
*
* @see com.intellij.vcs.log.data.LoadingDetails
*/
val cachedFullDetails: List<VcsFullCommitDetails>
/**
* Sends a request to load full details of the selected commits in a background thread.
* After all details are loaded they are provided to the consumer in the EDT.
*
* @param consumer called in EDT after all details are loaded.
*/
fun requestFullDetails(consumer: Consumer<in List<VcsFullCommitDetails>>)
companion object {
@JvmStatic
fun VcsLogCommitSelection.isEmpty() = size == 0
@JvmStatic
fun VcsLogCommitSelection.isNotEmpty() = size != 0
}
} | apache-2.0 | 487eacdb8306b970b41a5471328c4d69 | 30.181818 | 120 | 0.715605 | 4.189409 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/CoroutineDebugProbesProxy.kt | 4 | 2585 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.proxy
import com.intellij.debugger.engine.DebuggerManagerThreadImpl
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutinesInfoFromJsonAndReferencesProvider
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoCache
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.DebugProbesImpl
import org.jetbrains.kotlin.idea.debugger.coroutine.util.executionContext
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext
class CoroutineDebugProbesProxy(val suspendContext: SuspendContextImpl) {
/**
* Invokes DebugProbes from debugged process's classpath and returns states of coroutines
* Should be invoked on debugger manager thread
*/
@Synchronized
fun dumpCoroutines(): CoroutineInfoCache {
DebuggerManagerThreadImpl.assertIsManagerThread()
val coroutineInfoCache = CoroutineInfoCache()
try {
val executionContext = suspendContext.executionContext() ?: return coroutineInfoCache.fail()
val libraryAgentProxy = findProvider(executionContext) ?: return coroutineInfoCache.ok()
val infoList = libraryAgentProxy.dumpCoroutinesInfo()
coroutineInfoCache.ok(infoList)
} catch (e: Throwable) {
log.error("Exception is thrown by calling dumpCoroutines.", e)
coroutineInfoCache.fail()
}
return coroutineInfoCache
}
private fun findProvider(executionContext: DefaultExecutionContext): CoroutineInfoProvider? {
val debugProbesImpl = DebugProbesImpl.instance(executionContext)
return when {
debugProbesImpl != null && debugProbesImpl.isInstalled ->
CoroutinesInfoFromJsonAndReferencesProvider.instance(executionContext, debugProbesImpl) ?:
CoroutineLibraryAgent2Proxy(executionContext, debugProbesImpl)
standaloneCoroutineDebuggerEnabled() ->
CoroutineNoLibraryProxy(executionContext)
else ->
null
}
}
companion object {
private val log by logger
}
}
fun standaloneCoroutineDebuggerEnabled() = Registry.`is`("kotlin.debugger.coroutines.standalone")
| apache-2.0 | ecaf6debc8fea6a089fd9e1e2e640ef4 | 47.773585 | 158 | 0.744294 | 5.419287 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/changenumber/ChangeNumberLockActivity.kt | 1 | 4313 | package org.thoughtcrime.securesms.components.settings.app.changenumber
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.MainActivity
import org.thoughtcrime.securesms.PassphraseRequiredActivity
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.logsubmit.SubmitDebugLogActivity
import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter
import org.thoughtcrime.securesms.util.DynamicNoActionBarTheme
import org.thoughtcrime.securesms.util.DynamicTheme
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.whispersystems.signalservice.api.push.PNI
import java.util.Objects
private val TAG: String = Log.tag(ChangeNumberLockActivity::class.java)
/**
* A captive activity that can determine if an interrupted/erred change number request
* caused a disparity between the server and our locally stored number.
*/
class ChangeNumberLockActivity : PassphraseRequiredActivity() {
private val dynamicTheme: DynamicTheme = DynamicNoActionBarTheme()
private val disposables: LifecycleDisposable = LifecycleDisposable()
private lateinit var changeNumberRepository: ChangeNumberRepository
override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) {
dynamicTheme.onCreate(this)
disposables.bindTo(lifecycle)
setContentView(R.layout.activity_change_number_lock)
changeNumberRepository = ChangeNumberRepository(applicationContext)
checkWhoAmI()
}
override fun onResume() {
super.onResume()
dynamicTheme.onResume(this)
}
override fun onBackPressed() = Unit
private fun checkWhoAmI() {
disposables.add(
changeNumberRepository.whoAmI()
.flatMap { whoAmI ->
if (Objects.equals(whoAmI.number, SignalStore.account().e164)) {
Log.i(TAG, "Local and remote numbers match, nothing needs to be done.")
Single.just(false)
} else {
Log.i(TAG, "Local (${SignalStore.account().e164}) and remote (${whoAmI.number}) numbers do not match, updating local.")
changeNumberRepository.changeLocalNumber(whoAmI.number, PNI.parseOrThrow(whoAmI.pni))
.map { true }
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(onSuccess = { onChangeStatusConfirmed() }, onError = this::onFailedToGetChangeNumberStatus)
)
}
private fun onChangeStatusConfirmed() {
SignalStore.misc().unlockChangeNumber()
MaterialAlertDialogBuilder(this)
.setTitle(R.string.ChangeNumberLockActivity__change_status_confirmed)
.setMessage(getString(R.string.ChangeNumberLockActivity__your_number_has_been_confirmed_as_s, PhoneNumberFormatter.prettyPrint(SignalStore.account().e164!!)))
.setPositiveButton(android.R.string.ok) { _, _ ->
startActivity(MainActivity.clearTop(this))
finish()
}
.setCancelable(false)
.show()
}
private fun onFailedToGetChangeNumberStatus(error: Throwable) {
Log.w(TAG, "Unable to determine status of change number", error)
MaterialAlertDialogBuilder(this)
.setTitle(R.string.ChangeNumberLockActivity__change_status_unconfirmed)
.setMessage(getString(R.string.ChangeNumberLockActivity__we_could_not_determine_the_status_of_your_change_number_request, error.javaClass.simpleName))
.setPositiveButton(R.string.ChangeNumberLockActivity__retry) { _, _ -> checkWhoAmI() }
.setNegativeButton(R.string.ChangeNumberLockActivity__leave) { _, _ -> finish() }
.setNeutralButton(R.string.ChangeNumberLockActivity__submit_debug_log) { _, _ ->
startActivity(Intent(this, SubmitDebugLogActivity::class.java))
finish()
}
.setCancelable(false)
.show()
}
companion object {
@JvmStatic
fun createIntent(context: Context): Intent {
return Intent(context, ChangeNumberLockActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
}
}
}
}
| gpl-3.0 | 404be54085d9835a74cf90ae4c89bdb1 | 38.935185 | 164 | 0.747508 | 4.598081 | false | false | false | false |
CzBiX/v2ex-android | app/src/main/kotlin/com/czbix/v2ex/ViewerProvider.kt | 1 | 4341 | package com.czbix.v2ex
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.MatrixCursor
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.OpenableColumns
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.czbix.v2ex.util.MiscUtils
import java.io.File
import java.io.IOException
class ViewerProvider : ContentProvider() {
override fun onCreate(): Boolean {
return true
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?): Cursor? {
@Suppress("NAME_SHADOWING")
var projection = projection
// ContentProvider has already checked granted permissions
val file = getFileForUri(uri)
if (projection == null) {
projection = COLUMNS
}
var cols = arrayOfNulls<String>(projection.size)
var values = arrayOfNulls<Any>(projection.size)
var i = 0
for (col in projection) {
when (col) {
OpenableColumns.DISPLAY_NAME -> {
cols[i] = OpenableColumns.DISPLAY_NAME
values[i++] = file.name
}
OpenableColumns.SIZE -> {
cols[i] = OpenableColumns.SIZE
values[i++] = file.length()
}
}
}
cols = cols.sliceArray(0 until i)
values = values.sliceArray(0 until i)
val cursor = MatrixCursor(cols, 1)
cursor.addRow(values)
return cursor
}
override fun getType(uri: Uri): String? {
return "application/octet-stream"
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw UnsupportedOperationException("No external inserts")
}
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("No external updates")
}
override fun delete(uri: Uri, selection: String?,
selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("No external deletes")
}
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
// ContentProvider has already checked granted permissions
val file = getFileForUri(uri)
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
}
private fun getFileForUri(uri: Uri): File {
val path = uri.encodedPath
if (path != "/image" || tempPath == null) {
throw IllegalArgumentException("Invalid file path")
}
var file = File(tempPath)
try {
file = file.canonicalFile
} catch (e: IOException) {
throw IllegalArgumentException("Failed to resolve canonical path for $file")
}
return file
}
companion object {
private const val AUTHORITY = BuildConfig.APPLICATION_ID + ".viewer"
var tempPath: String? = null
private val COLUMNS = arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)
fun getUriForFile(): Uri {
return Uri.Builder().scheme("content")
.authority(AUTHORITY).encodedPath("image").build()
}
fun viewImage(context: Context, glide: RequestManager, url: String) {
@Suppress("NAME_SHADOWING")
val url = MiscUtils.formatUrl(url)
glide.downloadOnly().load(url).into(object : CustomTarget<File>() {
override fun onResourceReady(resource: File, transition: Transition<in File>?) {
tempPath = resource.canonicalPath
val contentUri = getUriForFile()
val intent = MiscUtils.getViewImageIntent(context, contentUri)
context.startActivity(intent)
}
override fun onLoadCleared(placeholder: Drawable?) {}
})
}
}
}
| apache-2.0 | 6b8b7f6ed3f30a5254671378b0c0da5d | 32.651163 | 96 | 0.614605 | 5.089097 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtGotoDeclarationHandler.kt | 1 | 4084 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtClassName
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtEntry
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFieldName
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFuncName
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFunction
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtTypes
import com.demonwav.mcdev.util.findQualifiedClass
import com.demonwav.mcdev.util.getPrimitiveType
import com.demonwav.mcdev.util.parseClassDescriptor
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
class AtGotoDeclarationHandler : GotoDeclarationHandler {
override fun getGotoDeclarationTargets(sourceElement: PsiElement?, offset: Int, editor: Editor): Array<out PsiElement>? {
if (sourceElement?.language !== AtLanguage) {
return null
}
val module = ModuleUtilCore.findModuleForPsiElement(sourceElement) ?: return null
val instance = MinecraftFacet.getInstance(module) ?: return null
val mcpModule = instance.getModuleOfType(McpModuleType) ?: return null
val srgMap = mcpModule.srgManager?.srgMapNow ?: return null
return when {
sourceElement.node.treeParent.elementType === AtTypes.CLASS_NAME -> {
val className = sourceElement.parent as AtClassName
val classSrgToMcp = srgMap.mapToMcpClass(className.classNameText)
val psiClass = findQualifiedClass(sourceElement.project, classSrgToMcp) ?: return null
arrayOf(psiClass)
}
sourceElement.node.treeParent.elementType === AtTypes.FUNC_NAME -> {
val funcName = sourceElement.parent as AtFuncName
val function = funcName.parent as AtFunction
val entry = function.parent as AtEntry
val reference = srgMap.mapToMcpMethod(AtMemberReference.get(entry, function) ?: return null)
val member = reference.resolveMember(sourceElement.project) ?: return null
arrayOf(member)
}
sourceElement.node.treeParent.elementType === AtTypes.FIELD_NAME -> {
val fieldName = sourceElement.parent as AtFieldName
val entry = fieldName.parent as AtEntry
val reference = srgMap.mapToMcpField(AtMemberReference.get(entry, fieldName) ?: return null)
val member = reference.resolveMember(sourceElement.project) ?: return null
arrayOf(member)
}
sourceElement.node.elementType === AtTypes.CLASS_VALUE -> {
val className = srgMap.mapToMcpClass(parseClassDescriptor(sourceElement.text))
val psiClass = findQualifiedClass(sourceElement.project, className) ?: return null
arrayOf(psiClass)
}
sourceElement.node.elementType === AtTypes.PRIMITIVE -> {
val text = sourceElement.text
if (text.length != 1) {
return null
}
val type = getPrimitiveType(text[0]) ?: return null
val boxedType = type.boxedTypeName ?: return null
val psiClass = JavaPsiFacade.getInstance(sourceElement.project).findClass(boxedType,
GlobalSearchScope.allScope(sourceElement.project)) ?: return null
arrayOf(psiClass)
}
else -> null
}
}
override fun getActionText(context: DataContext): String? = null
}
| mit | 5af80356cbbe44651c80888afde70e6b | 42.446809 | 125 | 0.676787 | 4.932367 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/opengl/OpenGLRenderpass.kt | 2 | 4840 | package graphics.scenery.backends.opengl
import cleargl.GLFramebuffer
import org.joml.Vector3f
import graphics.scenery.Settings
import graphics.scenery.backends.RenderConfigReader
import graphics.scenery.utils.LazyLogger
import graphics.scenery.utils.StickyBoolean
import org.joml.Vector2f
import org.joml.Vector4f
import java.util.concurrent.ConcurrentHashMap
/**
* Class to contain an OpenGL render pass with name [passName] and associated configuration
* [passConfig].
*
* @author Ulrik Guenther <[email protected]>
*/
class OpenGLRenderpass(var passName: String = "", var passConfig: RenderConfigReader.RenderpassConfig) {
private val logger by LazyLogger()
/** OpenGL metadata */
var openglMetadata: OpenGLMetadata = OpenGLMetadata()
/** Output(s) of the pass */
var output = ConcurrentHashMap<String, GLFramebuffer>()
/** Inputs of the pass */
var inputs = ConcurrentHashMap<String, GLFramebuffer>()
/** The default shader the pass uses */
var defaultShader: OpenGLShaderProgram? = null
/** UBOs required by this pass */
var UBOs = ConcurrentHashMap<String, OpenGLUBO>()
/** Class to store 2D rectangles with [width], [height] and offsets [offsetX] and [offsetY] */
data class Rect2D(var width: Int = 0, var height: Int = 0, var offsetX: Int = 0, var offsetY: Int = 0)
/** Class to store viewport information, [area], and minimal/maximal depth coordinates ([minDepth] and [maxDepth]). */
data class Viewport(var area: Rect2D = Rect2D(), var minDepth: Float = 0.0f, var maxDepth: Float = 1.0f)
/** Class to store clear values for color targets ([clearColor]) and depth targets ([clearDepth]) */
data class ClearValue(var clearColor: Vector4f = Vector4f(0.0f, 0.0f, 0.0f, 1.0f), var clearDepth: Float = 0.0f)
/**
* OpenGL metadata class, storing [scissor] areas, [renderArea]s, [clearValues], [viewports], and
* for which [eye] this metadata is valid.
*/
data class OpenGLMetadata(
var scissor: Rect2D = Rect2D(),
var renderArea: Rect2D = Rect2D(),
var clearValues: ClearValue = ClearValue(),
var viewport: Viewport = Viewport(),
var eye: Int = 0
)
/**
* Initialises shader parameters for this pass from [settings], which will be serialised
* into [backingBuffer].
*/
fun initializeShaderParameters(settings: Settings, backingBuffer: OpenGLRenderer.OpenGLBuffer) {
val ubo = OpenGLUBO(backingBuffer)
ubo.name = "ShaderParameters-$passName"
passConfig.parameters.forEach { entry ->
// Entry could be created in Java, so we check for both Java and Kotlin strings
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
val value = if (entry.value is String || entry.value is java.lang.String) {
val s = entry.value as String
val split = s.split(",").map { it.trim().trimStart().toFloat() }.toFloatArray()
when(split.size) {
2 -> Vector2f(split[0], split[1])
3 -> Vector3f(split[0], split[1], split[2])
4 -> Vector4f(split[0], split[1], split[2], split[3])
else -> throw IllegalStateException("Dont know how to handle ${split.size} elements in Shader Parameter split")
}
} else if (entry.value is Double) {
(entry.value as Double).toFloat()
} else {
entry.value
}
val settingsKey = when {
entry.key.startsWith("System") -> "System.${entry.key.substringAfter("System.")}"
entry.key.startsWith("Global") -> "Renderer.${entry.key.substringAfter("Global.")}"
entry.key.startsWith("Pass") -> "Renderer.$passName.${entry.key.substringAfter("Pass.")}"
else -> "Renderer.$passName.${entry.key}"
}
if (!entry.key.startsWith("Global") && !entry.key.startsWith("Pass.") && !entry.key.startsWith("System.")) {
settings.setIfUnset(settingsKey, value)
}
ubo.add(entry.key, { settings.get(settingsKey) })
}
ubo.setOffsetFromBackingBuffer()
ubo.populate()
UBOs.put(ubo.name, ubo)
}
/**
* Updates previously set-up shader parameters.
*
* Returns true if the parameters have been updated, and false if not.
*/
fun updateShaderParameters(): Boolean {
var updated: Boolean by StickyBoolean(false)
logger.trace("Updating shader parameters for ${this.passName}")
UBOs.forEach { uboName, ubo ->
if(uboName.startsWith("ShaderParameters-")) {
ubo.setOffsetFromBackingBuffer()
updated = ubo.populate()
}
}
return updated
}
}
| lgpl-3.0 | afeecfd5a1ec20e85f3c49ff8c44a6fd | 40.724138 | 131 | 0.625826 | 4.275618 | false | true | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/ForEachStatement.kt | 1 | 5394 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) 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 com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.Instructions
import com.github.jonathanxd.kores.common.MethodTypeSpec
/**
* For each statement.
*
* For each statement behavior depends on [IterationType]. For Source generation [iterationType] is useless,
* but for bytecode generation it is useful because `foreach` is translated to a [ForStatement], and arrays
* requires a special treatment to access length and values.
*
* @property variable Variable to store each element
* @property iterationType Type of the iteration
* @property iterableElement Element to iterate
* @see IterationType
*/
data class ForEachStatement(
val variable: VariableDeclaration,
val iterationType: IterationType,
val iterableElement: Instruction,
override val body: Instructions
) : BodyHolder, Instruction {
init {
BodyHolder.checkBody(this)
}
override fun builder(): Builder = Builder(this)
class Builder() : BodyHolder.Builder<ForEachStatement, Builder> {
lateinit var variable: VariableDeclaration
lateinit var iterationType: IterationType
lateinit var iterableElement: Instruction
var body: Instructions = Instructions.empty()
constructor(defaults: ForEachStatement) : this() {
this.variable = defaults.variable
this.iterationType = defaults.iterationType
this.iterableElement = defaults.iterableElement
}
/**
* See [ForEachStatement.variable]
*/
fun variable(value: VariableDeclaration): Builder {
this.variable = value
return this
}
/**
* See [ForEachStatement.iterationType]
*/
fun iterationType(value: IterationType): Builder {
this.iterationType = value
return this
}
/**
* See [ForEachStatement.iterableElement]
*/
fun iterableElement(value: Instruction): Builder {
this.iterableElement = value
return this
}
override fun body(value: Instructions): Builder {
this.body = value
return this
}
override fun build(): ForEachStatement =
ForEachStatement(this.variable, this.iterationType, this.iterableElement, this.body)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: ForEachStatement): Builder = Builder(defaults)
}
}
}
/**
* Iteration type used to generate bytecode and source code iterations.
*
* @property iteratorMethodSpec Specification of iterator method.
* @property hasNextName Name of method which returns true if has next elements.
* @property nextMethodSpec Specification of method which returns the next element.
*/
data class IterationType(
val iteratorMethodSpec: MethodTypeSpec,
val hasNextName: String,
val nextMethodSpec: MethodTypeSpec
) {
companion object {
private val NOTHING_SPEC =
MethodTypeSpec(Nothing::class.java, "", TypeSpec(Nothing::class.java))
/**
* Foreach on array. Requires special handling.
*/
@JvmField
val ARRAY = IterationType(NOTHING_SPEC, "", NOTHING_SPEC)
/**
* Foreach on an element which extends iterable
*/
@JvmField
val ITERABLE_ELEMENT = IterationType(
MethodTypeSpec(
localization = Iterable::class.java,
methodName = "iterator",
typeSpec = TypeSpec(Iterator::class.java)
),
"hasNext",
MethodTypeSpec(
localization = Iterator::class.java,
methodName = "next",
typeSpec = TypeSpec(Any::class.java)
)
)
}
} | mit | 27d322f601ceecc2eaeaafa5d9ceca22 | 32.930818 | 118 | 0.652762 | 5.093484 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveCurlyBracesFromTemplateInspection.kt | 1 | 2306 | // 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.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.canDropCurlyBrackets
import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible
import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry
class RemoveCurlyBracesFromTemplateInspection(@JvmField var reportWithoutWhitespace: Boolean = false) :
AbstractApplicabilityBasedInspection<KtBlockStringTemplateEntry>(KtBlockStringTemplateEntry::class.java), CleanupLocalInspectionTool {
override fun inspectionText(element: KtBlockStringTemplateEntry): String =
KotlinBundle.message("redundant.curly.braces.in.string.template")
override fun inspectionHighlightType(element: KtBlockStringTemplateEntry) =
if (reportWithoutWhitespace || element.hasWhitespaceAround()) ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else ProblemHighlightType.INFORMATION
override val defaultFixText: String get() = KotlinBundle.message("remove.curly.braces")
override fun isApplicable(element: KtBlockStringTemplateEntry): Boolean = element.canDropCurlyBrackets()
override fun applyTo(element: KtBlockStringTemplateEntry, project: Project, editor: Editor?) {
element.dropCurlyBracketsIfPossible()
}
override fun createOptionsPanel() = MultipleCheckboxOptionsPanel(this).apply {
addCheckbox(KotlinBundle.message("report.also.for.a.variables.without.a.whitespace.around"), "reportWithoutWhitespace")
}
}
private fun KtBlockStringTemplateEntry.hasWhitespaceAround(): Boolean =
prevSibling?.isWhitespaceOrQuote(true) == true && nextSibling?.isWhitespaceOrQuote(false) == true
private fun PsiElement.isWhitespaceOrQuote(prev: Boolean): Boolean {
val char = if (prev) text.lastOrNull() else text.firstOrNull()
return char != null && (char.isWhitespace() || char == '"')
}
| apache-2.0 | d8ca09e049d645458fe9020640268c58 | 51.409091 | 138 | 0.804423 | 5.301149 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/statistics/DispersionPatternUtils.kt | 1 | 2735 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.features.statistics
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.print.PageRange
import androidx.annotation.RequiresApi
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.shared.targets.drawable.TargetImpactAggregationDrawable
import de.dreier.mytargets.utils.print.CustomPrintDocumentAdapter
import de.dreier.mytargets.utils.print.DrawableToPdfWriter
import de.dreier.mytargets.utils.writeToJPGFile
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
object DispersionPatternUtils {
@Throws(IOException::class)
fun createDispersionPatternImageFile(size: Int, file: File, statistic: ArrowStatistic) {
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE)
val target = targetFromArrowStatistics(statistic)
target.bounds = Rect(0, 0, size, size)
target.draw(canvas)
bitmap.writeToJPGFile(file)
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Throws(FileNotFoundException::class)
fun generatePdf(f: File, statistic: ArrowStatistic) {
FileOutputStream(f).use { outputStream ->
val target = targetFromArrowStatistics(statistic)
val pdfWriter = DrawableToPdfWriter(target)
pdfWriter.layoutPages(
CustomPrintDocumentAdapter.DEFAULT_RESOLUTION,
CustomPrintDocumentAdapter.DEFAULT_MEDIA_SIZE
)
pdfWriter.writePdfDocument(arrayOf(PageRange(0, 0)), outputStream)
}
}
fun targetFromArrowStatistics(statistic: ArrowStatistic): TargetImpactAggregationDrawable {
val target = TargetImpactAggregationDrawable(statistic.target)
target.replaceShotsWith(statistic.shots)
target.setAggregationStrategy(SettingsManager.statisticsDispersionPatternAggregationStrategy)
target.setArrowDiameter(statistic.arrowDiameter, SettingsManager.inputArrowDiameterScale)
return target
}
}
| gpl-2.0 | 6d2794faf7de4198a31fd7b23cd8ae59 | 38.637681 | 101 | 0.755759 | 4.651361 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/ec2/src/main/kotlin/com/kotlin/ec2/CreateInstance.kt | 1 | 2495 | // snippet-sourcedescription:[CreateInstance.kt demonstrates how to create an Amazon Elastic Compute Cloud (Amazon EC2) instance.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon EC2]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.ec2
// snippet-start:[ec2.kotlin.create_instance.import]
import aws.sdk.kotlin.services.ec2.Ec2Client
import aws.sdk.kotlin.services.ec2.model.CreateTagsRequest
import aws.sdk.kotlin.services.ec2.model.InstanceType
import aws.sdk.kotlin.services.ec2.model.RunInstancesRequest
import aws.sdk.kotlin.services.ec2.model.Tag
import kotlin.system.exitProcess
// snippet-end:[ec2.kotlin.create_instance.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<name> <amiId>
Where:
name - An instance name that you can obtain from the AWS Management Console (for example, ami-xxxxxx5c8b987b1a0).
amiId - An Amazon Machine Image (AMI) value that you can obtain from the AWS Management Console (for example, i-xxxxxx2734106d0ab).
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val name = args[0]
val amiId = args[1]
createEC2Instance(name, amiId)
}
// snippet-start:[ec2.kotlin.create_instance.main]
suspend fun createEC2Instance(name: String, amiId: String): String? {
val request = RunInstancesRequest {
imageId = amiId
instanceType = InstanceType.T1Micro
maxCount = 1
minCount = 1
}
Ec2Client { region = "us-west-2" }.use { ec2 ->
val response = ec2.runInstances(request)
val instanceId = response.instances?.get(0)?.instanceId
val tag = Tag {
key = "Name"
value = name
}
val requestTags = CreateTagsRequest {
resources = listOf(instanceId.toString())
tags = listOf(tag)
}
ec2.createTags(requestTags)
println("Successfully started EC2 Instance $instanceId based on AMI $amiId")
return instanceId
}
}
// snippet-end:[ec2.kotlin.create_instance.main]
| apache-2.0 | fadcbfbaf951f01b61e480f8c5b96faf | 30.402597 | 140 | 0.666132 | 3.814985 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/androidarch/room/database/Car.kt | 1 | 505 | package com.esafirm.androidplayground.androidarch.room.database
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
@Entity(
tableName = "car",
foreignKeys = [ForeignKey(
entity = User::class,
parentColumns = ["userId"],
childColumns = ["owner"]
)]
)
data class Car(
@PrimaryKey(autoGenerate = true)
val carId: Int? = null,
val name: String,
val owner: Int
)
| mit | 4810ef07b100dd10b4fda17a4da2fc9f | 24.25 | 63 | 0.60198 | 4.54955 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/visible/VcsLogFiltererImpl.kt | 1 | 22792 | // 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.vcs.log.visible
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.*
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.data.index.VcsLogIndex
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.graph.utils.DfsWalk
import com.intellij.vcs.log.history.FileNamesData
import com.intellij.vcs.log.history.removeTrivialMerges
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.*
import com.intellij.vcs.log.util.VcsLogUtil.FULL_HASH_LENGTH
import com.intellij.vcs.log.util.VcsLogUtil.SHORT_HASH_LENGTH
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.fromHashes
import com.intellij.vcs.log.visible.filters.with
import com.intellij.vcs.log.visible.filters.without
import gnu.trove.TIntHashSet
import java.util.stream.Collectors
class VcsLogFiltererImpl(private val logProviders: Map<VirtualFile, VcsLogProvider>,
private val storage: VcsLogStorage,
private val topCommitsDetailsCache: TopCommitsCache,
private val commitDetailsGetter: DataGetter<out VcsFullCommitDetails>,
private val index: VcsLogIndex) : VcsLogFilterer {
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = false
override fun filter(dataPack: DataPack,
sortType: PermanentGraph.SortType,
allFilters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val hashFilter = allFilters.get(VcsLogFilterCollection.HASH_FILTER)
val filters = allFilters.without(VcsLogFilterCollection.HASH_FILTER)
val start = System.currentTimeMillis()
if (hashFilter != null && !hashFilter.hashes.isEmpty()) { // hashes should be shown, no matter if they match other filters or not
val hashFilterResult = applyHashFilter(dataPack, hashFilter.hashes, sortType, commitCount)
if (hashFilterResult != null) {
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) +
" for filtering by " + hashFilterResult.first.filters)
return hashFilterResult
}
}
val visibleRoots = VcsLogUtil.getAllVisibleRoots(dataPack.logProviders.keys, filters)
var matchingHeads = getMatchingHeads(dataPack.refsModel, visibleRoots, filters)
val rangeFilters = allFilters.get(VcsLogFilterCollection.RANGE_FILTER)
val commitCandidates: TIntHashSet?
val forceFilterByVcs: Boolean
if (rangeFilters != null) {
/*
If we have both a range filter and a branch filter (e.g. `183\nmaster..feature`) they should be united: the graph should show both
commits contained in the range, and commits reachable from branches.
But the main filtering logic is opposite: matchingHeads + some other filter => makes the intersection of commits.
To overcome this logic for the range filter case, we are not using matchingHeads, but are collecting all commits reachable from
matchingHeads, and unite them with commits belonging to the range.
*/
val branchFilter = filters.get(VcsLogFilterCollection.BRANCH_FILTER)
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
val explicitMatchingHeads = getMatchingHeads(dataPack.refsModel, visibleRoots, branchFilter, revisionFilter)
val commitsReachableFromHeads = if (explicitMatchingHeads != null)
collectCommitsReachableFromHeads(dataPack, explicitMatchingHeads)
else TIntHashSet()
val commitsForRangeFilter = filterByRange(dataPack, rangeFilters)
if (commitsForRangeFilter != null) {
commitCandidates = TroveUtil.union(listOf(commitsReachableFromHeads, commitsForRangeFilter))
forceFilterByVcs = false
}
else {
commitCandidates = null
forceFilterByVcs = true
}
/*
At the same time, the root filter should intersect with the range filter (and the branch filter),
therefore we take matching heads from the root filter, but use reachable commits set for the branch filter.
*/
val matchingHeadsFromRoots = getMatchingHeads(dataPack.refsModel, visibleRoots)
matchingHeads = matchingHeadsFromRoots
}
else {
commitCandidates = null
forceFilterByVcs = false
}
val filterResult = filterByDetails(dataPack, filters, commitCount, visibleRoots, matchingHeads, commitCandidates, forceFilterByVcs)
val visibleGraph = createVisibleGraph(dataPack, sortType, matchingHeads, filterResult.matchingCommits, filterResult.fileNamesData)
val visiblePack = VisiblePack(dataPack, visibleGraph, filterResult.canRequestMore, filters)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for filtering by " + filters)
return Pair(visiblePack, filterResult.commitCount)
}
private fun collectCommitsReachableFromHeads(dataPack: DataPack, matchingHeads: Set<Int>): TIntHashSet {
@Suppress("UNCHECKED_CAST") val permanentGraph = dataPack.permanentGraph as? PermanentGraphInfo<Int> ?: return TIntHashSet()
val startIds = matchingHeads.map { permanentGraph.permanentCommitsInfo.getNodeId(it) }
val result = TIntHashSet()
DfsWalk(startIds, permanentGraph.linearGraph).walk(true) { node: Int ->
result.add(permanentGraph.permanentCommitsInfo.getCommitId(node))
true
}
return result
}
fun createVisibleGraph(dataPack: DataPack,
sortType: PermanentGraph.SortType,
matchingHeads: Set<Int>?,
matchingCommits: Set<Int>?,
fileNamesData: FileNamesData? = null): VisibleGraph<Int> {
return if (matchingHeads.matchesNothing() || matchingCommits.matchesNothing()) {
EmptyVisibleGraph.getInstance()
}
else {
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl || fileNamesData == null) {
permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits)
}
else {
permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits) { controller, permanentGraphInfo ->
removeTrivialMerges(controller, permanentGraphInfo, fileNamesData) { trivialMerges ->
LOG.debug("Removed ${trivialMerges.size} trivial merges")
}
}
}
}
}
private fun filterByDetails(dataPack: DataPack,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage,
visibleRoots: Collection<VirtualFile>,
matchingHeads: Set<Int>?,
commitCandidates: TIntHashSet?,
forceFilterByVcs: Boolean): FilterByDetailsResult {
val detailsFilters = filters.detailsFilters
if (!forceFilterByVcs && detailsFilters.isEmpty()) {
val matchingCommits = if (commitCandidates != null) TroveUtil.createJavaSet(commitCandidates) else null
return FilterByDetailsResult(matchingCommits, false, commitCount)
}
val dataGetter = index.dataGetter
val (rootsForIndex, rootsForVcs) = if (dataGetter != null && dataGetter.canFilter(detailsFilters) && !forceFilterByVcs) {
visibleRoots.partition { index.isIndexed(it) }
}
else {
Pair(emptyList(), visibleRoots.toList())
}
val (filteredWithIndex, namesData) = if (rootsForIndex.isNotEmpty())
filterWithIndex(dataGetter!!, detailsFilters, commitCandidates)
else Pair(null, null)
if (rootsForVcs.isEmpty()) return FilterByDetailsResult(filteredWithIndex, false, commitCount, namesData)
val filterAllWithVcs = rootsForVcs.containsAll(visibleRoots)
val filtersForVcs = if (filterAllWithVcs) filters else filters.with(VcsLogFilterObject.fromRoots(rootsForVcs))
val headsForVcs = if (filterAllWithVcs) matchingHeads else getMatchingHeads(dataPack.refsModel, rootsForVcs, filtersForVcs)
val filteredWithVcs = filterWithVcs(dataPack.permanentGraph, filtersForVcs, headsForVcs, commitCount, commitCandidates)
val filteredCommits: Set<Int>? = union(filteredWithIndex, filteredWithVcs.matchingCommits)
return FilterByDetailsResult(filteredCommits, filteredWithVcs.canRequestMore, filteredWithVcs.commitCount, namesData)
}
private fun filterByRange(dataPack: DataPack, rangeFilter: VcsLogRangeFilter): TIntHashSet? {
val set = TIntHashSet()
for (range in rangeFilter.ranges) {
var rangeResolvedAnywhere = false
for ((root, _) in logProviders) {
val resolvedRange = resolveCommits(dataPack, root, range)
if (resolvedRange != null) {
val commits = getCommitsByRange(dataPack, root, resolvedRange)
if (commits == null) return null // error => will be handled by the VCS provider
else TroveUtil.addAll(set, commits)
rangeResolvedAnywhere = true
}
}
// If a range is resolved in some roots, but not all of them => skip others and handle those which know about the range.
// Otherwise, if none of the roots know about the range => return null and let VcsLogProviders handle the range
if (!rangeResolvedAnywhere) {
LOG.warn("Range limits unresolved for: $range")
return null
}
}
return set
}
private fun resolveCommits(dataPack: DataPack, root: VirtualFile, range: VcsLogRangeFilter.RefRange): Pair<CommitId, CommitId>? {
val from = resolveCommit(dataPack, root, range.exclusiveRef)
val to = resolveCommit(dataPack, root, range.inclusiveRef)
if (from == null || to == null) {
LOG.debug("Range limits unresolved for: $range in $root")
return null
}
return from to to
}
private fun getCommitsByRange(dataPack: DataPack, root: VirtualFile, range: Pair<CommitId, CommitId>): TIntHashSet? {
val fromIndex = storage.getCommitIndex(range.first.hash, root)
val toIndex = storage.getCommitIndex(range.second.hash, root)
return dataPack.subgraphDifference(toIndex, fromIndex)
}
private fun resolveCommit(dataPack: DataPack, root: VirtualFile, refName: String): CommitId? {
if (refName.length == FULL_HASH_LENGTH && VcsLogUtil.HASH_REGEX.matcher(refName).matches()) {
return CommitId(HashImpl.build(refName), root)
}
val ref = dataPack.refsModel.findBranch(refName, root)
return if (ref != null) {
CommitId(ref.commitHash, root)
}
else if (refName.length >= SHORT_HASH_LENGTH && VcsLogUtil.HASH_REGEX.matcher(refName).matches()) {
// don't search for too short hashes: high probability to treat a ref, existing not in all roots, as a hash
storage.findCommitId(CommitIdByStringCondition(refName))
}
else null
}
private fun filterWithIndex(dataGetter: IndexDataGetter,
detailsFilters: List<VcsLogDetailsFilter>,
commitCandidates: TIntHashSet?): Pair<Set<Int>?, FileNamesData?> {
val structureFilter = detailsFilters.filterIsInstance(VcsLogStructureFilter::class.java).singleOrNull()
?: return Pair(dataGetter.filter(detailsFilters, commitCandidates), null)
val namesData = dataGetter.createFileNamesData(structureFilter.files)
val candidates = TroveUtil.intersect(TroveUtil.createTroveSet(namesData.getCommits()), commitCandidates)
val filtersWithoutStructure = detailsFilters.filterNot { it is VcsLogStructureFilter }
if (filtersWithoutStructure.isEmpty()) return Pair(TroveUtil.createJavaSet(candidates), namesData)
return Pair(dataGetter.filter(filtersWithoutStructure, candidates), namesData)
}
private fun filterWithVcs(graph: PermanentGraph<Int>,
filters: VcsLogFilterCollection,
matchingHeads: Set<Int>?,
commitCount: CommitCountStage,
commitCandidates: TIntHashSet?): FilterByDetailsResult {
var commitCountToTry = commitCount
if (commitCountToTry == CommitCountStage.INITIAL) {
val commitsFromMemory = filterDetailsInMemory(graph, filters.detailsFilters, matchingHeads, commitCandidates).toCommitIndexes()
if (commitsFromMemory.size >= commitCountToTry.count) {
return FilterByDetailsResult(commitsFromMemory, true, commitCountToTry)
}
commitCountToTry = commitCountToTry.next()
}
try {
val commitsFromVcs = filteredDetailsInVcs(logProviders, filters, commitCountToTry.count).toCommitIndexes()
return FilterByDetailsResult(commitsFromVcs, commitsFromVcs.size >= commitCountToTry.count, commitCountToTry)
}
catch (e: VcsException) {
//TODO show an error balloon or something else for non-ea guys.
LOG.error(e)
return FilterByDetailsResult(emptySet(), true, commitCountToTry)
}
}
@Throws(VcsException::class)
private fun filteredDetailsInVcs(providers: Map<VirtualFile, VcsLogProvider>,
filterCollection: VcsLogFilterCollection,
maxCount: Int): Collection<CommitId> {
val commits = mutableListOf<CommitId>()
val visibleRoots = VcsLogUtil.getAllVisibleRoots(providers.keys, filterCollection)
for (root in visibleRoots) {
val userFilter = filterCollection.get(VcsLogFilterCollection.USER_FILTER)
if (userFilter != null && userFilter.getUsers(root).isEmpty()) {
// there is a structure or user filter, but it doesn't match this root
continue
}
val filesForRoot = VcsLogUtil.getFilteredFilesForRoot(root, filterCollection)
val rootSpecificCollection = if (filesForRoot.isEmpty()) {
filterCollection.without(VcsLogFilterCollection.STRUCTURE_FILTER)
}
else {
filterCollection.with(VcsLogFilterObject.fromPaths(filesForRoot))
}
val matchingCommits = providers[root]!!.getCommitsMatchingFilter(root, rootSpecificCollection, maxCount)
commits.addAll(matchingCommits.map { commit -> CommitId(commit.id, root) })
}
return commits
}
private fun applyHashFilter(dataPack: DataPack,
hashes: Collection<String>,
sortType: PermanentGraph.SortType,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage>? {
val hashFilterResult = hashSetOf<Int>()
for (partOfHash in hashes) {
if (partOfHash.length == FULL_HASH_LENGTH) {
val hash = HashImpl.build(partOfHash)
for (root in dataPack.logProviders.keys) {
if (storage.containsCommit(CommitId(hash, root))) {
hashFilterResult.add(storage.getCommitIndex(hash, root))
}
}
}
else {
val commitId = storage.findCommitId(CommitIdByStringCondition(partOfHash))
if (commitId != null) hashFilterResult.add(storage.getCommitIndex(commitId.hash, commitId.root))
}
}
if (!Registry.`is`("vcs.log.filter.messages.by.hash")) {
if (hashFilterResult.isEmpty()) return null
val visibleGraph = dataPack.permanentGraph.createVisibleGraph(sortType, null, hashFilterResult)
val visiblePack = VisiblePack(dataPack, visibleGraph, false, VcsLogFilterObject.collection(fromHashes(hashes)))
return Pair(visiblePack, CommitCountStage.ALL)
}
val textFilter = VcsLogFilterObject.fromPatternsList(ArrayList(hashes), false)
val textFilterResult = filterByDetails(dataPack, VcsLogFilterObject.collection(textFilter),
commitCount, dataPack.logProviders.keys, null, null, false)
if (hashFilterResult.isEmpty() && textFilterResult.matchingCommits.matchesNothing()) return null
val filterResult = union(textFilterResult.matchingCommits, hashFilterResult)
val visibleGraph = dataPack.permanentGraph.createVisibleGraph(sortType, null, filterResult)
val visiblePack = VisiblePack(dataPack, visibleGraph, textFilterResult.canRequestMore,
VcsLogFilterObject.collection(fromHashes(hashes), textFilter))
return Pair(visiblePack, textFilterResult.commitCount)
}
fun getMatchingHeads(refs: RefsModel,
roots: Collection<VirtualFile>,
filters: VcsLogFilterCollection): Set<Int>? {
val branchFilter = filters.get(VcsLogFilterCollection.BRANCH_FILTER)
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
if (branchFilter == null &&
revisionFilter == null &&
filters.get(VcsLogFilterCollection.ROOT_FILTER) == null &&
filters.get(VcsLogFilterCollection.STRUCTURE_FILTER) == null) {
return null
}
if (revisionFilter != null) {
if (branchFilter == null) {
return getMatchingHeads(roots, revisionFilter)
}
return getMatchingHeads(refs, roots, branchFilter).union(getMatchingHeads(roots, revisionFilter))
}
if (branchFilter == null) return getMatchingHeads(refs, roots)
return getMatchingHeads(refs, roots, branchFilter)
}
private fun getMatchingHeads(refs: RefsModel,
roots: Collection<VirtualFile>,
branchFilter: VcsLogBranchFilter?,
revisionFilter: VcsLogRevisionFilter?): Set<Int>? {
if (branchFilter == null && revisionFilter == null) return null
val branchMatchingHeads = if (branchFilter != null) getMatchingHeads(refs, roots, branchFilter) else emptySet()
val revisionMatchingHeads = if (revisionFilter != null) getMatchingHeads(roots, revisionFilter) else emptySet()
return branchMatchingHeads.union(revisionMatchingHeads)
}
private fun getMatchingHeads(refsModel: RefsModel, roots: Collection<VirtualFile>, filter: VcsLogBranchFilter): Set<Int> {
return mapRefsForRoots(refsModel, roots) { refs ->
refs.streamBranches().filter { filter.matches(it.name) }.collect(Collectors.toList())
}.toReferencedCommitIndexes()
}
private fun getMatchingHeads(roots: Collection<VirtualFile>, filter: VcsLogRevisionFilter): Set<Int> {
return filter.heads.filter { roots.contains(it.root) }.toCommitIndexes()
}
private fun getMatchingHeads(refsModel: RefsModel, roots: Collection<VirtualFile>): Set<Int> {
return mapRefsForRoots(refsModel, roots) { refs -> refs.commits }
}
private fun <T> mapRefsForRoots(refsModel: RefsModel, roots: Collection<VirtualFile>, mapping: (CompressedRefs) -> Iterable<T>) =
refsModel.allRefsByRoot.filterKeys { roots.contains(it) }.values.flatMapTo(mutableSetOf(), mapping)
private fun filterDetailsInMemory(permanentGraph: PermanentGraph<Int>,
detailsFilters: List<VcsLogDetailsFilter>,
matchingHeads: Set<Int>?,
commitCandidates: TIntHashSet?): Collection<CommitId> {
val result = mutableListOf<CommitId>()
for (commit in permanentGraph.allCommits) {
if (commitCandidates == null || commitCandidates.contains(commit.id)) {
val data = getDetailsFromCache(commit.id)
?: // no more continuous details in the cache
break
if (matchesAllFilters(data, permanentGraph, detailsFilters, matchingHeads)) {
result.add(CommitId(data.id, data.root))
}
}
}
return result
}
private fun matchesAllFilters(commit: VcsCommitMetadata,
permanentGraph: PermanentGraph<Int>,
detailsFilters: List<VcsLogDetailsFilter>,
matchingHeads: Set<Int>?): Boolean {
val matchesAllDetails = detailsFilters.all { filter -> filter.matches(commit) }
return matchesAllDetails && matchesAnyHead(permanentGraph, commit, matchingHeads)
}
private fun matchesAnyHead(permanentGraph: PermanentGraph<Int>,
commit: VcsCommitMetadata,
matchingHeads: Set<Int>?): Boolean {
if (matchingHeads == null) {
return true
}
// TODO O(n^2)
val commitIndex = storage.getCommitIndex(commit.id, commit.root)
return ContainerUtil.intersects(permanentGraph.getContainingBranches(commitIndex), matchingHeads)
}
private fun getDetailsFromCache(commitIndex: Int): VcsCommitMetadata? {
return topCommitsDetailsCache.get(commitIndex) ?: UIUtil.invokeAndWaitIfNeeded(
Computable<VcsCommitMetadata> { commitDetailsGetter.getCommitDataIfAvailable(commitIndex) })
}
private fun Collection<CommitId>.toCommitIndexes(): Set<Int> {
return this.mapTo(mutableSetOf()) { commitId ->
storage.getCommitIndex(commitId.hash, commitId.root)
}
}
private fun Collection<VcsRef>.toReferencedCommitIndexes(): Set<Int> {
return this.mapTo(mutableSetOf()) { ref ->
storage.getCommitIndex(ref.commitHash, ref.root)
}
}
}
private val LOG = Logger.getInstance(VcsLogFiltererImpl::class.java)
private data class FilterByDetailsResult(val matchingCommits: Set<Int>?,
val canRequestMore: Boolean,
val commitCount: CommitCountStage,
val fileNamesData: FileNamesData? = null)
fun areFiltersAffectedByIndexing(filters: VcsLogFilterCollection, roots: List<VirtualFile>): Boolean {
val detailsFilters = filters.detailsFilters
if (detailsFilters.isEmpty()) return false
val affectedRoots = VcsLogUtil.getAllVisibleRoots(roots, filters)
val needsIndex = affectedRoots.isNotEmpty()
if (needsIndex) {
LOG.debug("$filters are affected by indexing of $affectedRoots")
}
return needsIndex
}
internal fun <T> Collection<T>?.matchesNothing(): Boolean {
return this != null && this.isEmpty()
}
internal fun <T> union(c1: Set<T>?, c2: Set<T>?): Set<T>? {
if (c1 == null) return c2
if (c2 == null) return c1
return c1.union(c2)
}
| apache-2.0 | 193bc6a022e0136cb699eff361c89d0c | 46.483333 | 140 | 0.699456 | 5.277147 | false | false | false | false |