repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
genonbeta/TrebleShot
|
app/src/main/java/org/monora/uprotocol/client/android/activity/HomeActivity.kt
|
1
|
8063
|
/*
* Copyright (C) 2019 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.annotation.IdRes
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import dagger.hilt.android.AndroidEntryPoint
import org.monora.uprotocol.client.android.BuildConfig
import org.monora.uprotocol.client.android.NavHomeDirections
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.app.Activity
import org.monora.uprotocol.client.android.database.model.SharedText
import org.monora.uprotocol.client.android.database.model.Transfer
import org.monora.uprotocol.client.android.database.model.WebTransfer
import org.monora.uprotocol.client.android.databinding.LayoutUserProfileBinding
import org.monora.uprotocol.client.android.viewmodel.ChangelogViewModel
import org.monora.uprotocol.client.android.viewmodel.CrashLogViewModel
import org.monora.uprotocol.client.android.viewmodel.UserProfileViewModel
@AndroidEntryPoint
class HomeActivity : Activity(), NavigationView.OnNavigationItemSelectedListener {
private val changelogViewModel: ChangelogViewModel by viewModels()
private val crashLogViewModel: CrashLogViewModel by viewModels()
private val userProfileViewModel: UserProfileViewModel by viewModels()
private val userProfileBinding by lazy {
LayoutUserProfileBinding.bind(navigationView.getHeaderView(0)).also {
it.viewModel = userProfileViewModel
it.lifecycleOwner = this
it.editProfileClickListener = View.OnClickListener {
openItem(R.id.edit_profile)
}
}
}
private val navigationView: NavigationView by lazy {
findViewById(R.id.nav_view)
}
private val drawerLayout: DrawerLayout by lazy {
findViewById(R.id.drawer_layout)
}
private var pendingMenuItemId = 0
private val navController by lazy {
navController(R.id.nav_host_fragment)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
drawerLayout.addDrawerListener(
object : DrawerLayout.SimpleDrawerListener() {
override fun onDrawerClosed(drawerView: View) {
applyAwaitingDrawerAction()
}
}
)
toolbar.setupWithNavController(navController, AppBarConfiguration(navController.graph, drawerLayout))
navigationView.setNavigationItemSelectedListener(this)
navController.addOnDestinationChangedListener { _, destination, _ -> title = destination.label }
userProfileBinding.executePendingBindings()
if (BuildConfig.FLAVOR == "googlePlay") {
navigationView.menu.findItem(R.id.donate).isVisible = true
}
if (hasIntroductionShown()) {
if (changelogViewModel.shouldShowChangelog) {
navController.navigate(NavHomeDirections.actionGlobalChangelogFragment())
} else if (crashLogViewModel.shouldShowCrashLog) {
navController.navigate(NavHomeDirections.actionGlobalCrashLogFragment())
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
when (intent?.action) {
ACTION_OPEN_TRANSFER_DETAILS -> if (intent.hasExtra(EXTRA_TRANSFER)) {
val transfer = intent.getParcelableExtra<Transfer>(EXTRA_TRANSFER)
if (transfer != null) {
navController.navigate(NavHomeDirections.actionGlobalNavTransferDetails(transfer))
}
}
ACTION_OPEN_SHARED_TEXT -> if (intent.hasExtra(EXTRA_SHARED_TEXT)) {
val sharedText = intent.getParcelableExtra<SharedText>(EXTRA_SHARED_TEXT)
if (sharedText != null) {
navController.navigate(NavHomeDirections.actionGlobalNavTextEditor(sharedText = sharedText))
}
}
ACTION_OPEN_WEB_TRANSFER -> if (intent.hasExtra(EXTRA_WEB_TRANSFER)) {
val webTransfer = intent.getParcelableExtra<WebTransfer>(EXTRA_WEB_TRANSFER)
if (webTransfer != null) {
Log.d("HomeActivity", "onNewIntent: $webTransfer")
navController.navigate(NavHomeDirections.actionGlobalWebTransferDetailsFragment(webTransfer))
}
}
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
openItem(item.itemId)
return true
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.close()
} else {
super.onBackPressed()
}
}
private fun applyAwaitingDrawerAction() {
if (pendingMenuItemId == 0) {
return // drawer was opened, but nothing was clicked.
}
when (pendingMenuItemId) {
R.id.edit_profile -> navController.navigate(NavHomeDirections.actionGlobalProfileEditorFragment())
R.id.manage_clients -> navController.navigate(NavHomeDirections.actionGlobalNavManageDevices())
R.id.about -> navController.navigate(NavHomeDirections.actionGlobalNavAbout())
R.id.preferences -> navController.navigate(NavHomeDirections.actionGlobalNavPreferences())
R.id.about_uprotocol -> navController.navigate(NavHomeDirections.actionGlobalAboutUprotocolFragment())
R.id.donate -> try {
startActivity(
Intent(
applicationContext,
Class.forName("org.monora.uprotocol.client.android.activity.DonationActivity")
)
)
} catch (e: ClassNotFoundException) {
e.printStackTrace()
}
}
pendingMenuItemId = 0
}
private fun openItem(@IdRes id: Int) {
pendingMenuItemId = id
drawerLayout.close()
}
companion object {
const val ACTION_OPEN_TRANSFER_DETAILS = "org.monora.uprotocol.client.android.action.OPEN_TRANSFER_DETAILS"
const val ACTION_OPEN_WEB_TRANSFER = "org.monora.uprotocol.client.android.action.OPEN_WEB_TRANSFER"
const val ACTION_OPEN_SHARED_TEXT = "org.monora.uprotocol.client.android.action.OPEN_SHARED_TEXT"
const val EXTRA_TRANSFER = "extraTransfer"
const val EXTRA_WEB_TRANSFER = "extraWebTransfer"
const val EXTRA_SHARED_TEXT = "extraSharedText"
}
}
|
gpl-2.0
|
c47199899359e00bb273370bf4e5dddb
| 39.31 | 115 | 0.688043 | 4.952088 | false | false | false | false |
flamurey/koltin-func
|
src/main/kotlin/com/flamurey/kfunc/core/Monoid.kt
|
1
|
1466
|
package com.flamurey.kfunc.core
interface Monoid<A> {
fun op(l: A, r: A): A
fun zero(): A
companion object Factory {
fun getStringMonoid() = object : Monoid<String> {
override fun op(l: String, r: String) = l + r
override fun zero(): String = ""
}
fun getIntAddition() = object : Monoid<Int> {
override fun op(l: Int, r: Int): Int = l + r
override fun zero(): Int = 0
}
fun getIntMultiplication() = object : Monoid<Int> {
override fun op(l: Int, r: Int): Int = l * r
override fun zero(): Int = 1
}
fun getBooleanOr() = object : Monoid<Boolean> {
override fun op(l: Boolean, r: Boolean) = l || r
override fun zero() = false
}
fun getBooleanAnd() = object : Monoid<Boolean> {
override fun op(l: Boolean, r: Boolean) = l && r
override fun zero() = true
}
fun <T> getOptionMonoid(m: Monoid<T>) = object : Monoid<Option<T>> {
override fun zero() = Option(m.zero())
override fun op(l: Option<T>, r: Option<T>): Option<T> {
val lValue = l.getOrElse(m.zero())
val rValue = r.getOrElse(m.zero())
return Option(m.op(lValue, rValue))
}
}
fun <A, B> getProductMonoid(a: Monoid<A>, b: Monoid<B>) = object : Monoid<Pair<A, B>> {
override fun zero(): Pair<A, B> = a.zero() to b.zero()
override fun op(l: Pair<A, B>, r: Pair<A, B>) = a.op(l.first, r.first) to b.op(l.second, r.second)
}
}
}
|
mit
|
d2bffa4e71e0cd66819a4c68a13405da
| 27.192308 | 104 | 0.566849 | 3.17316 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-meta/src/main/kotlin/slatekit/meta/models/ModelField.kt
|
1
|
7620
|
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.meta.models
import slatekit.common.data.DataType
import slatekit.utils.naming.Namer
import slatekit.meta.KTypes
import slatekit.meta.Reflector
import kotlin.reflect.*
import kotlin.reflect.jvm.jvmErasure
data class ModelField(
@JvmField val name: String,
@JvmField val desc: String = "",
@JvmField val prop: KProperty<*>? = null,
@JvmField val dataCls: KClass<*>,
@JvmField val dataTpe: DataType = ModelUtils.fieldType(dataCls),
@JvmField val storedName: String = "",
@JvmField val pos: Int = 0,
@JvmField val isRequired: Boolean = true,
@JvmField val minLength: Int = -1,
@JvmField val maxLength: Int = -1,
@JvmField val isEnum: Boolean = false,
@JvmField val isUnique: Boolean = false,
@JvmField val isIndexed: Boolean = false,
@JvmField val isUpdatable: Boolean = true,
@JvmField val defaultValue: Any? = null,
@JvmField val encrypt: Boolean = false,
@JvmField val key: String = "",
@JvmField val extra: String = "",
@JvmField val example: String = "",
@JvmField val format: String = "",
@JvmField val tags: List<String> = listOf(),
@JvmField val category: FieldCategory = FieldCategory.Data,
@JvmField val model: Model? = null
) {
override fun toString(): String {
val text = StringBuilder()
text.append("( name : $name")
text.append(", desc : $desc")
text.append(", dataCls : $dataCls")
text.append(", storedName : $storedName")
text.append(", pos : $pos")
text.append(", isRequired : $isRequired")
text.append(", minLength : $minLength")
text.append(", maxLength : $maxLength")
text.append(", defaultValue : $defaultValue")
text.append(", encrypt : $encrypt")
text.append(", example : $example")
text.append(", format : $format")
text.append(", key : $key")
text.append(", extra : $extra")
text.append(", tag : $tags")
text.append(", category : $category")
text.append(" )")
return text.toString()
}
fun isBasicType(): Boolean = KTypes.isBasicType(dataCls) || isEnum
fun isStandard(): Boolean {
val result = listOf("standard", "id", "meta").filter { tags.contains(it) }
return result.isNotEmpty()
}
companion object {
/**
* builds a new model field that is an id
* @param name
* @param dataType
* @return
*/
@JvmStatic
fun id(name: String, dataType: KClass<*>, dataTpe: DataType): ModelField {
return build(null, name, "", dataType, dataTpe, true,
true, true, false,
0, 0, name, 0, cat = FieldCategory.Id)
}
/**
* builds an model field using all the fields supplied.
* @param name
* @param dataType
* @param desc
* @param isRequired
* @param minLength
* @param maxLength
* @param destName
* @param defaultValue
* @param tag
* @param cat
* @return
*/
@JvmStatic
fun build(
prop: KProperty<*>?,
name: String,
desc: String = "",
dataType: KClass<*>,
dataFieldType: DataType,
isRequired: Boolean = false,
isUnique: Boolean = false,
isIndexed: Boolean = false,
isUpdatable: Boolean = true,
minLength: Int = -1,
maxLength: Int = -1,
destName: String? = null,
defaultValue: Any? = null,
encrypt: Boolean = false,
tags: List<String> = listOf(),
cat: FieldCategory = FieldCategory.Data,
namer: Namer? = null
): ModelField {
val finalName = buildDestName(name, destName, namer)
val isEnum = Reflector.isSlateKitEnum(dataType)
val field = ModelField(
name = name,
desc = desc,
prop = prop,
dataCls = dataType,
dataTpe = dataFieldType,
isEnum = isEnum,
storedName = finalName,
pos = 0,
isRequired = isRequired,
isUnique = isUnique,
isIndexed = isIndexed,
isUpdatable = isUpdatable,
minLength = minLength,
maxLength = maxLength,
defaultValue = defaultValue,
encrypt = encrypt,
key = "",
tags = tags,
category = cat
)
return field
}
@JvmStatic
fun buildDestName(name: String, destName: String?, namer: Namer?): String {
return when (destName) {
null -> namer?.rename(name) ?: name
else -> destName
}
}
@JvmStatic
fun ofId(prop:KProperty<*>, rawName:String, namer: Namer?):ModelField {
val name = if (rawName.isNullOrEmpty()) prop.name else rawName
val fieldKType = prop.returnType
val fieldType = ModelUtils.fieldType(prop)
val fieldCls = fieldKType.jvmErasure
val optional = fieldKType.isMarkedNullable
val field = ModelField.build(
prop = prop, name = name,
dataType = fieldCls,
dataFieldType = fieldType,
isRequired = !optional,
isIndexed = false,
isUnique = false,
isUpdatable = false,
cat = FieldCategory.Id,
namer = namer
)
return field
}
@JvmStatic
fun ofData(prop:KProperty<*>, anno: Field, namer: Namer?, checkForId:Boolean, idFieldName:String?):ModelField {
val name = if (anno.name.isNullOrEmpty()) prop.name else anno.name
val cat = idFieldName?.let {
if(it == name)
FieldCategory.Id
else
FieldCategory.Data
} ?: FieldCategory.Data
val required = anno.required
val length = anno.length
val encrypt = anno.encrypt
val fieldKType = prop.returnType
val fieldType = ModelUtils.fieldType(prop)
val fieldCls = fieldKType.jvmErasure
val field = ModelField.build(
prop = prop, name = name,
dataType = fieldCls,
dataFieldType = fieldType,
isRequired = required,
isIndexed = anno.indexed,
isUnique = anno.unique,
isUpdatable = anno.updatable,
maxLength = length,
encrypt = encrypt,
cat = cat,
namer = namer
)
return field
}
}
}
|
apache-2.0
|
e165d9a441284c60791f508c2d9883a2
| 33.636364 | 119 | 0.51273 | 4.925663 | false | false | false | false |
zdary/intellij-community
|
platform/lang-impl/src/com/intellij/internal/performance/TypingLatencyReportDialog.kt
|
5
|
7331
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.performance
import com.intellij.execution.filters.TextConsoleBuilderFactory
import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.fileChooser.FileSaverDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.ColoredTreeCellRenderer
import com.intellij.ui.JBSplitter
import com.intellij.ui.components.JBBox
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.treeStructure.Tree
import com.intellij.unscramble.AnalyzeStacktraceUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.tree.TreeUtil
import java.awt.event.ActionEvent
import java.nio.file.Path
import javax.swing.*
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
private class TypingLatencyReportAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
TypingLatencyReportDialog(project).show()
}
}
internal class TypingLatencyReportDialog(
private val project: Project,
private val threadDumps: List<String> = emptyList()
) : DialogWrapper(project) {
private var currentThreadDump = 0
private lateinit var consoleView: ConsoleView
private lateinit var prevThreadDumpButton: JButton
private lateinit var nextThreadDumpButton: JButton
init {
init()
title = "Typing Latency Report"
}
override fun createCenterPanel(): JComponent {
val jbScrollPane = createReportTree()
val panel: JComponent = if (latencyRecorderProperties.isNotEmpty()) {
val header = JLabel(formatHeader(true))
JBSplitter(true).apply {
setResizeEnabled(false)
setResizable(false)
proportion = 0.01f
firstComponent = header
secondComponent = jbScrollPane
}
}
else {
jbScrollPane
}
if (threadDumps.isEmpty()) {
return panel
}
return JBSplitter(true).apply {
firstComponent = panel
secondComponent = createThreadDumpBrowser()
}
}
private fun createReportTree(): JBScrollPane {
val root = DefaultMutableTreeNode()
for (row in latencyMap.values.sortedBy { it.key.name }) {
val rowNode = DefaultMutableTreeNode(row)
root.add(rowNode)
for (actionLatencyRecord in row.actionLatencyRecords.entries.sortedByDescending { it.value.averageLatency }) {
rowNode.add(DefaultMutableTreeNode(actionLatencyRecord.toPair()))
}
}
val reportList = Tree(DefaultTreeModel(root))
reportList.isRootVisible = false
reportList.cellRenderer = object : ColoredTreeCellRenderer() {
override fun customizeCellRenderer(tree: JTree,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean) {
if (value == null) return
val obj = (value as DefaultMutableTreeNode).userObject
if (obj is LatencyDistributionRecord) {
append(formatLatency(obj.key.name, obj.totalLatency, obj.key.details))
}
else if (obj is Pair<*, *>) {
append(formatLatency(obj.first as String, obj.second as LatencyRecord))
}
}
}
TreeUtil.expandAll(reportList)
return JBScrollPane(reportList)
}
private fun formatLatency(action: String, latencyRecord: LatencyRecord, details: String? = null): String {
val result = "$action - avg ${latencyRecord.averageLatency} ms, max ${latencyRecord.maxLatency} ms, 90% percentile ${latencyRecord.percentile(
90)} ms"
if (details != null) {
return "$result, $details"
}
return result
}
private fun formatHeader(htmlStyle: Boolean): String {
return if (htmlStyle) latencyRecorderProperties.map { (key, value) -> "- $key: $value" }.joinToString(
prefix = "<html>Latency Recorder Properties<br/>",
separator = "<br/>", postfix = "</html>")
else latencyRecorderProperties.map { (key, value) -> " - $key: $value" }.joinToString(
prefix = "Latency Recorder Properties\n",
separator = "\n")
}
private fun createThreadDumpBrowser(): JComponent {
val builder = TextConsoleBuilderFactory.getInstance().createBuilder(project)
builder.filters(AnalyzeStacktraceUtil.EP_NAME.getExtensions(project))
consoleView = builder.console
Disposer.register(disposable, consoleView)
val buttonsPanel = JBBox.createHorizontalBox()
prevThreadDumpButton = JButton("<<").apply {
addActionListener {
currentThreadDump--
updateCurrentThreadDump()
}
}
nextThreadDumpButton = JButton(">>").apply {
addActionListener {
currentThreadDump++
updateCurrentThreadDump()
}
}
buttonsPanel.add(prevThreadDumpButton)
buttonsPanel.add(Box.createHorizontalGlue())
buttonsPanel.add(nextThreadDumpButton)
updateCurrentThreadDump()
return JBUI.Panels.simplePanel().addToCenter(consoleView.component).addToBottom(buttonsPanel)
}
private fun updateCurrentThreadDump() {
consoleView.clear()
consoleView.print(threadDumps[currentThreadDump], ConsoleViewContentType.NORMAL_OUTPUT)
consoleView.scrollTo(0)
prevThreadDumpButton.isEnabled = currentThreadDump > 0
nextThreadDumpButton.isEnabled = currentThreadDump < threadDumps.size - 1
}
private fun formatReportAsText(): String {
return buildString {
appendln(formatHeader(false))
appendln()
for (row in latencyMap.values.sortedBy { it.key.name }) {
appendln(formatLatency(row.key.name, row.totalLatency, row.key.details))
appendln("Actions:")
for (actionLatencyRecord in row.actionLatencyRecords.entries.sortedByDescending { it.value.averageLatency }) {
appendln(" ${formatLatency(actionLatencyRecord.key, actionLatencyRecord.value)}")
}
}
appendln()
if (threadDumps.isNotEmpty()) {
appendln("Thread dumps:")
for (threadDump in threadDumps) {
appendln(threadDump)
appendln("-".repeat(40))
}
}
}
}
override fun createActions(): Array<Action> {
return arrayOf(ExportToFileAction(), okAction)
}
private inner class ExportToFileAction : AbstractAction("Export to File") {
override fun actionPerformed(e: ActionEvent) {
val descriptor = FileSaverDescriptor("Export Typing Latency Report", "File name:", "txt")
val dialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, contentPane)
val virtualFileWrapper = dialog.save(null as Path?, "typing-latency.txt") ?: return
FileUtil.writeToFile(virtualFileWrapper.file, formatReportAsText())
}
}
}
|
apache-2.0
|
3878b06f96ba482592cf4d95d74b6ea0
| 36.025253 | 146 | 0.695676 | 4.705392 | false | false | false | false |
JuliusKunze/kotlin-native
|
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/MappingBridgeGeneratorImpl.kt
|
1
|
7821
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.indexer.RecordType
import org.jetbrains.kotlin.native.interop.indexer.Type
import org.jetbrains.kotlin.native.interop.indexer.VoidType
/**
* The [MappingBridgeGenerator] implementation which uses [SimpleBridgeGenerator] as the backend and
* maps the type using [mirror].
*/
class MappingBridgeGeneratorImpl(
val declarationMapper: DeclarationMapper,
val simpleBridgeGenerator: SimpleBridgeGenerator
) : MappingBridgeGenerator {
override fun kotlinToNative(
builder: KotlinCodeBuilder,
nativeBacked: NativeBacked,
returnType: Type,
kotlinValues: List<TypedKotlinValue>,
block: NativeCodeBuilder.(nativeValues: List<NativeExpression>) -> NativeExpression
): KotlinExpression {
val bridgeArguments = mutableListOf<BridgeTypedKotlinValue>()
kotlinValues.forEach { (type, value) ->
if (type.unwrapTypedefs() is RecordType) {
builder.pushMemScoped()
val bridgeArgument = "$value.getPointer(memScope).rawValue"
bridgeArguments.add(BridgeTypedKotlinValue(BridgedType.NATIVE_PTR, bridgeArgument))
} else {
val info = mirror(declarationMapper, type).info
bridgeArguments.add(BridgeTypedKotlinValue(info.bridgedType, info.argToBridged(value)))
}
}
val unwrappedReturnType = returnType.unwrapTypedefs()
val kniRetVal = "kniRetVal"
val bridgeReturnType = when (unwrappedReturnType) {
VoidType -> BridgedType.VOID
is RecordType -> {
val mirror = mirror(declarationMapper, returnType)
val tmpVarName = kniRetVal
builder.out("val $tmpVarName = nativeHeap.alloc<${mirror.pointedType.render(builder.scope)}>()")
builder.pushBlock("try {", free = "finally { nativeHeap.free($tmpVarName) }")
bridgeArguments.add(BridgeTypedKotlinValue(BridgedType.NATIVE_PTR, "$tmpVarName.rawPtr"))
BridgedType.VOID
}
else -> {
val mirror = mirror(declarationMapper, returnType)
mirror.info.bridgedType
}
}
val callExpr = simpleBridgeGenerator.kotlinToNative(
nativeBacked, bridgeReturnType, bridgeArguments
) { bridgeNativeValues ->
val nativeValues = mutableListOf<String>()
kotlinValues.forEachIndexed { index, (type, _) ->
val unwrappedType = type.unwrapTypedefs()
if (unwrappedType is RecordType) {
nativeValues.add("*(${unwrappedType.decl.spelling}*)${bridgeNativeValues[index]}")
} else {
nativeValues.add(
mirror(declarationMapper, type).info.cFromBridged(
bridgeNativeValues[index], scope, nativeBacked
)
)
}
}
val nativeResult = block(nativeValues)
when (unwrappedReturnType) {
is VoidType -> {
out(nativeResult + ";")
""
}
is RecordType -> {
out("*(${unwrappedReturnType.decl.spelling}*)${bridgeNativeValues.last()} = $nativeResult;")
""
}
else -> {
nativeResult
}
}
}
val result = when (unwrappedReturnType) {
is VoidType -> callExpr
is RecordType -> {
builder.out(callExpr)
"$kniRetVal.readValue()"
}
else -> {
val mirror = mirror(declarationMapper, returnType)
mirror.info.argFromBridged(callExpr, builder.scope, nativeBacked)
}
}
return result
}
override fun nativeToKotlin(
builder: NativeCodeBuilder,
nativeBacked: NativeBacked,
returnType: Type,
nativeValues: List<TypedNativeValue>,
block: KotlinCodeBuilder.(kotlinValues: List<KotlinExpression>) -> KotlinExpression
): NativeExpression {
val bridgeArguments = mutableListOf<BridgeTypedNativeValue>()
nativeValues.forEachIndexed { _, (type, value) ->
val bridgeArgument = if (type.unwrapTypedefs() is RecordType) {
BridgeTypedNativeValue(BridgedType.NATIVE_PTR, "&$value")
} else {
val info = mirror(declarationMapper, type).info
BridgeTypedNativeValue(info.bridgedType, value)
}
bridgeArguments.add(bridgeArgument)
}
val unwrappedReturnType = returnType.unwrapTypedefs()
val kniRetVal = "kniRetVal"
val bridgeReturnType = when (unwrappedReturnType) {
VoidType -> BridgedType.VOID
is RecordType -> {
val tmpVarName = kniRetVal
builder.out("${unwrappedReturnType.decl.spelling} $tmpVarName;")
bridgeArguments.add(BridgeTypedNativeValue(BridgedType.NATIVE_PTR, "&$tmpVarName"))
BridgedType.VOID
}
else -> {
val mirror = mirror(declarationMapper, returnType)
mirror.info.bridgedType
}
}
val callExpr = simpleBridgeGenerator.nativeToKotlin(
nativeBacked,
bridgeReturnType,
bridgeArguments
) { bridgeKotlinValues ->
val kotlinValues = mutableListOf<String>()
nativeValues.forEachIndexed { index, (type, _) ->
val mirror = mirror(declarationMapper, type)
if (type.unwrapTypedefs() is RecordType) {
val pointedTypeName = mirror.pointedType.render(this.scope)
kotlinValues.add(
"interpretPointed<$pointedTypeName>(${bridgeKotlinValues[index]}).readValue()"
)
} else {
kotlinValues.add(mirror.info.argFromBridged(bridgeKotlinValues[index], this.scope, nativeBacked))
}
}
val kotlinResult = block(kotlinValues)
when (unwrappedReturnType) {
is RecordType -> {
"$kotlinResult.write(${bridgeKotlinValues.last()})"
}
is VoidType -> {
kotlinResult
}
else -> {
mirror(declarationMapper, returnType).info.argToBridged(kotlinResult)
}
}
}
val result = when (unwrappedReturnType) {
is VoidType -> callExpr
is RecordType -> {
builder.out("$callExpr;")
kniRetVal
}
else -> {
mirror(declarationMapper, returnType).info.cFromBridged(callExpr, builder.scope, nativeBacked)
}
}
return result
}
}
|
apache-2.0
|
9cb91fb705da304c9045e08f3ec96918
| 37.915423 | 117 | 0.569492 | 5.263122 | false | false | false | false |
faceofcat/Tesla-Core-Lib
|
src/main/kotlin/net/ndrei/teslacorelib/tileentities/ElectricGenerator.kt
|
1
|
9139
|
package net.ndrei.teslacorelib.tileentities
import net.minecraft.inventory.Slot
import net.minecraft.item.EnumDyeColor
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraftforge.items.ItemStackHandler
import net.modcrafters.mclib.energy.IGenericEnergyStorage
import net.ndrei.teslacorelib.MOD_ID
import net.ndrei.teslacorelib.containers.BasicTeslaContainer
import net.ndrei.teslacorelib.containers.FilteredSlot
import net.ndrei.teslacorelib.energy.EnergySystemFactory
import net.ndrei.teslacorelib.gui.BasicRenderedGuiPiece
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import net.ndrei.teslacorelib.gui.IGeneratorInfoProvider
import net.ndrei.teslacorelib.gui.IGuiContainerPiece
import net.ndrei.teslacorelib.inventory.BoundingRectangle
import net.ndrei.teslacorelib.inventory.ColoredItemHandler
import net.ndrei.teslacorelib.inventory.EnergyStorage
import net.ndrei.teslacorelib.inventory.SyncProviderLevel
/**
* Created by CF on 2017-06-27.
*/
@Suppress("MemberVisibilityCanPrivate")
abstract class ElectricGenerator protected constructor(typeId: Int) : ElectricTileEntity(typeId), IGeneratorInfoProvider {
private lateinit var generatedPower: EnergyStorage
private lateinit var chargePadItems: ItemStackHandler
//#region inventory methods
override fun initializeInventories() {
super.initializeInventories()
this.chargePadItems = object : ItemStackHandler(2) {
override fun onContentsChanged(slot: Int) {
// [email protected]()
[email protected](SYNC_CHARGE_PAD_ITEMS)
}
override fun getSlotLimit(slot: Int): Int {
return 1
}
}
super.addInventory(object : ColoredItemHandler(this.chargePadItems, EnumDyeColor.BROWN, "$MOD_ID:Charge Pad", -10, BoundingRectangle(34, 34, 18, 36)) {
override fun canInsertItem(slot: Int, stack: ItemStack)
= EnergySystemFactory.wrapItemStack(stack)?.canGive ?: false
override fun canExtractItem(slot: Int): Boolean {
val wrapper = EnergySystemFactory.wrapItemStack(this.getStackInSlot(slot))
if (wrapper != null) {
return (wrapper.givePower(1L, true) > 0L)
}
return true
}
override fun getSlots(container: BasicTeslaContainer<*>): MutableList<Slot> {
val slots = super.getSlots(container)
slots.add(FilteredSlot(this.itemHandlerForContainer, 0, 35, 35))
slots.add(FilteredSlot(this.itemHandlerForContainer, 1, 35, 53))
return slots
}
override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> {
val pieces = super.getGuiContainerPieces(container)
pieces.add(BasicRenderedGuiPiece(25, 26, 27, 52,
BasicTeslaGuiContainer.MACHINE_BACKGROUND, 206, 4))
return pieces
}
})
super.addInventoryToStorage(this.chargePadItems, SYNC_CHARGE_PAD_ITEMS)
this.generatedPower = object : EnergyStorage(0, 0, 0) {
override fun onChanged(old: Long, current: Long) {
super.onChanged(old, current)
[email protected](SYNC_GENERATED_ENERGY)
}
}
this.registerSyncTagPart(SYNC_GENERATED_ENERGY, this.generatedPower, SyncProviderLevel.GUI)
}
//#endregion
//region energy methods
override val maxEnergy: Long
get() = 100000
override val energyInputRate: Long
get() = 0
override val energyOutputRate: Long
get() = 80
protected open val energyFillRate: Long
get() = 160
override final val generatedPowerCapacity: Long
get() = this.generatedPower.capacity
override final val generatedPowerStored: Long
get() = this.generatedPower.stored
override final val generatedPowerReleaseRate: Long
get() = this.generatedPower.getEnergyOutputRate()
//endregion
//#region write/read/sync methods
// override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound {
// var compound = compound
// compound = super.writeToNBT(compound)
//
// if (this.generatedPower != null) {
// compound.setTag("generated_energy", this.generatedPower.serializeNBT())
// }
//
// return compound
// }
//
// override fun readFromNBT(compound: NBTTagCompound) {
// super.readFromNBT(compound)
//
// if (compound.hasKey("generated_energy")) {
// if (this.generatedPower == null) {
// this.generatedPower = EnergyStorage(0, 0, 0)
// }
// this.generatedPower.deserializeNBT(compound.getCompoundTag("generated_energy"))
// }
// }
//#endregion
//#region work methods
protected abstract fun consumeFuel(): Long
protected open fun fuelConsumed() {}
protected val isGeneratedPowerLostIfFull: Boolean
get() = true
public override fun protectedUpdate() {
if (!this.generatedPower.isEmpty) {
val power = this.generatedPower.takePower(this.generatedPower.getEnergyOutputRate(), !this.isGeneratedPowerLostIfFull)
val consumed = this.energyStorage.givePower(power)
if (consumed > 0 && this.isGeneratedPowerLostIfFull) {
this.generatedPower.takePower(consumed)
}
// TeslaCoreLib.logger.info("generated power: " + this.generatedPower.getStoredPower() + " / " + this.generatedPower.getCapacity());
if (this.generatedPower.isEmpty) {
this.fuelConsumed()
}
}
if (this.generatedPower.isEmpty && !this.energyStorage.isFull && !this.getWorld().isRemote) {
this.generatedPower.setCapacity(0)
val power = this.consumeFuel()
if (power > 0) {
this.generatedPower.setCapacity(power)
this.generatedPower.setEnergyOutputRate(this.energyFillRate)
this.generatedPower.givePower(power)
}
}
//#region distribute power
if (!this.energyStorage.isEmpty && !this.world.isRemote) {
val consumers = mutableListOf<IGenericEnergyStorage>()
val powerSides = this.sideConfig.getSidesForColor(this.energyStorage.color!!)
if (powerSides.isNotEmpty()) {
val pos = this.getPos()
val facing = this.facing
for (side in powerSides) {
var oriented: EnumFacing = this.orientFacing(side)
if ((oriented != EnumFacing.DOWN) && oriented != EnumFacing.UP && (facing == EnumFacing.EAST || facing == EnumFacing.WEST)) {
oriented = oriented.opposite
}
val entity = this.getWorld().getTileEntity(pos.offset(oriented)) ?: continue
val wrapper = EnergySystemFactory.wrapTileEntity(entity, oriented.opposite) ?: continue
consumers.add(wrapper)
}
}
if (consumers.size > 0) {
var total = this.energyStorage.getEnergyOutputRate()
total = this.energyStorage.takePower(total, true)
var totalConsumed: Long = 0
var consumerCount = consumers.size
for (consumer in consumers) {
val perConsumer = total / consumerCount
consumerCount--
if (perConsumer > 0) {
val consumed = consumer.givePower(perConsumer, false)
if (consumed > 0) {
totalConsumed += consumed
}
}
}
if (totalConsumed > 0) {
this.energyStorage.takePower(totalConsumed)
}
}
}
//#endregion
}
override fun processImmediateInventories() {
super.processImmediateInventories()
for (index in 0..1) {
val stack = this.chargePadItems.getStackInSlot(index)
if (stack.isEmpty) {
continue
}
val available = this.energyStorage.takePower(this.energyStorage.getEnergyOutputRate(), true)
if (available == 0L) {
break
}
val wrapper = EnergySystemFactory.wrapItemStack(stack)
if (wrapper != null) {
val consumed = wrapper.givePower(available, false)
if (consumed > 0) {
this.energyStorage.takePower(consumed, false)
}
}
}
}
//#endregion
companion object {
protected const val SYNC_GENERATED_ENERGY = "generated_energy"
protected const val SYNC_CHARGE_PAD_ITEMS = "inv_charge_pad"
}
}
|
mit
|
8c7246f914319c0d7f23b4a7f596cb64
| 36.150407 | 159 | 0.611664 | 4.850849 | false | false | false | false |
AndroidX/androidx
|
window/window/src/androidTest/java/androidx/window/layout/WindowLayoutInfoTest.kt
|
3
|
3382
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.layout
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.window.core.Bounds
import androidx.window.layout.FoldingFeature.State.Companion.FLAT
import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED
import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
/** Tests for [WindowLayoutInfo] class. */
@SmallTest
@RunWith(AndroidJUnit4::class)
public class WindowLayoutInfoTest {
@Test
public fun testBuilder_setDisplayFeatures() {
val feature1: DisplayFeature = HardwareFoldingFeature(Bounds(1, 0, 3, 4), HINGE, FLAT)
val feature2: DisplayFeature =
HardwareFoldingFeature(Bounds(1, 0, 1, 4), HINGE, HALF_OPENED)
val displayFeatures = listOf(feature1, feature2)
val windowLayoutInfo = WindowLayoutInfo(displayFeatures)
assertEquals(displayFeatures, windowLayoutInfo.displayFeatures)
}
@Test
public fun testEquals_sameFeatures() {
val features = listOf<DisplayFeature>()
val original = WindowLayoutInfo(features)
val copy = WindowLayoutInfo(features)
assertEquals(original, copy)
}
@Test
public fun testEquals_differentFeatures() {
val originalFeatures = listOf<DisplayFeature>()
val rect = Bounds(1, 0, 1, 10)
val differentFeatures = listOf(HardwareFoldingFeature(rect, HINGE, FLAT))
val original = WindowLayoutInfo(originalFeatures)
val different = WindowLayoutInfo(differentFeatures)
assertNotEquals(original, different)
}
@Test
public fun testHashCode_matchesIfEqual() {
val firstFeatures = emptyList<DisplayFeature>()
val secondFeatures = emptyList<DisplayFeature>()
val first = WindowLayoutInfo(firstFeatures)
val second = WindowLayoutInfo(secondFeatures)
assertEquals(first, second)
assertEquals(first.hashCode().toLong(), second.hashCode().toLong())
}
@Test
public fun testHashCode_matchesIfEqualFeatures() {
val originalFeature: DisplayFeature =
HardwareFoldingFeature(Bounds(0, 0, 100, 0), HINGE, FLAT)
val matchingFeature: DisplayFeature =
HardwareFoldingFeature(Bounds(0, 0, 100, 0), HINGE, FLAT)
val firstFeatures = listOf(originalFeature)
val secondFeatures = listOf(matchingFeature)
val first = WindowLayoutInfo(firstFeatures)
val second = WindowLayoutInfo(secondFeatures)
assertEquals(first, second)
assertEquals(first.hashCode().toLong(), second.hashCode().toLong())
}
}
|
apache-2.0
|
9e7a3443694d59af37bc619c2b183781
| 38.788235 | 94 | 0.721171 | 4.607629 | false | true | false | false |
AndroidX/androidx
|
emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/ItemViewData.kt
|
3
|
1797
|
/*
* 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.emoji2.emojipicker
internal enum class ItemType {
CATEGORY_TITLE,
PLACEHOLDER_TEXT,
EMOJI,
PLACEHOLDER_EMOJI,
}
/**
* Represents an item within the body RecyclerView.
*/
internal sealed class ItemViewData(itemType: ItemType, val occupyEntireRow: Boolean = false) {
val viewType = itemType.ordinal
}
/**
* Title of each category.
*/
internal class CategoryTitle(val title: String) :
ItemViewData(ItemType.CATEGORY_TITLE, occupyEntireRow = true)
/**
* Text to display when the category contains no items.
*/
internal class PlaceholderText(val text: String) :
ItemViewData(ItemType.PLACEHOLDER_TEXT, occupyEntireRow = true)
/**
* Represents an emoji.
*/
internal class EmojiViewData(
var primary: String,
val variants: List<String>,
val updateToVariants: Boolean = true
) : ItemViewData(ItemType.EMOJI)
internal object PlaceholderEmoji : ItemViewData(ItemType.PLACEHOLDER_EMOJI)
internal object Extensions {
internal fun Int.toItemType() = ItemType.values()[this]
internal fun EmojiViewItem.toEmojiViewData(updateToVariants: Boolean = true) =
EmojiViewData(emoji, variants, updateToVariants)
}
|
apache-2.0
|
b766cf0bc305bbf0b405eccfb012fd46
| 28.459016 | 94 | 0.740122 | 4.131034 | false | false | false | false |
AndroidX/androidx
|
compose/ui/ui-text/src/desktopTest/kotlin/androidx/compose/ui/text/CacheTest.kt
|
3
|
3963
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text
import com.google.common.truth.Truth
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
private class MockedTimeProvider : ExpireAfterAccessCache.TimeProvider {
var currentTime: Long = 0
override fun getTime() = currentTime
}
private const val twoSecondsInNanos = 2_000_000_000
private const val tenMillisInNanos = 10_000_000
@RunWith(JUnit4::class)
class CacheTest {
private val time = MockedTimeProvider()
private val cache = ExpireAfterAccessCache<String, String>(
expireAfterNanos = 1_000_000_000L, // 1 second
timeProvider = time
)
@Test
fun single_key() {
cache.get("k1") { "v1" }
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k1")
Truth.assertThat(cache.accessQueue.tail!!.key)
.isEqualTo("k1")
var valueFromCache = cache.get("k1") { "v1_2" }
Truth.assertThat(valueFromCache).isEqualTo("v1")
time.currentTime += twoSecondsInNanos
valueFromCache = cache.get("k1") { "v1_3" }
Truth.assertThat(valueFromCache).isEqualTo("v1")
Truth.assertThat(cache.accessQueue.head!!.accessTime)
.isEqualTo(twoSecondsInNanos)
}
@Test
fun two_keys() {
cache.get("k1") { "v1" }
time.currentTime += tenMillisInNanos
cache.get("k2") { "v2" }
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k2")
Truth.assertThat(cache.accessQueue.tail!!.key)
.isEqualTo("k1")
time.currentTime += tenMillisInNanos
var valueFromCache = cache.get("k1") { "v1_2" }
Truth.assertThat(valueFromCache).isEqualTo("v1")
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k1")
Truth.assertThat(cache.accessQueue.tail!!.key)
.isEqualTo("k2")
// expiration
time.currentTime += twoSecondsInNanos
cache.get("k1") { "v1_3" }
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k1")
Truth.assertThat(cache.accessQueue.tail!!.key)
.isEqualTo("k1")
Truth.assertThat(cache.map.size)
.isEqualTo(1)
}
@Test
fun three_keys() {
cache.get("k1") { "v1" }
cache.get("k2") { "v2" }
cache.get("k3") { "v3" }
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k3")
Truth.assertThat(cache.accessQueue.tail!!.key)
.isEqualTo("k1")
cache.get("k2") { "v2_2" }
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k2")
Truth.assertThat(cache.accessQueue.tail!!.key)
.isEqualTo("k1")
Truth.assertThat(cache.accessQueue.tail!!.nextInAccess!!.key)
.isEqualTo("k3")
time.currentTime += twoSecondsInNanos
cache.get("k3") { "v3_3" }
Truth.assertThat(cache.accessQueue.head!!.key)
.isEqualTo("k3")
Truth.assertThat(cache.accessQueue.head!!)
.isEqualTo(cache.accessQueue.tail!!)
Truth.assertThat(cache.accessQueue.tail!!.prevInAccess).isNull()
Truth.assertThat(cache.accessQueue.tail!!.nextInAccess).isNull()
Truth.assertThat(cache.map.size)
.isEqualTo(1)
}
}
|
apache-2.0
|
b2ba2986792704efe9b15f9b26ff8399
| 29.728682 | 75 | 0.627807 | 3.803263 | false | false | false | false |
LouisCAD/Splitties
|
samples/android-app/src/main/kotlin/com/example/splitties/about/AboutUi.kt
|
1
|
2355
|
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package com.example.splitties.about
import android.content.Context
import android.util.AttributeSet
import com.example.splitties.R
import com.example.splitties.extensions.ui.addDefaultAppBar
import splitties.dimensions.dip
import splitties.views.centerText
import splitties.views.dsl.constraintlayout.*
import splitties.views.dsl.material.contentScrollingWithAppBarLParams
import splitties.views.dsl.coordinatorlayout.coordinatorLayout
import splitties.views.dsl.core.*
import splitties.views.dsl.idepreview.UiPreView
import splitties.views.textAppearance
import splitties.views.textResource
import com.google.android.material.R as MaterialR
class AboutUi(override val ctx: Context) : Ui {
private val mainContent = constraintLayout {
val headlineTv = add(textView {
textAppearance = MaterialR.style.TextAppearance_AppCompat_Headline
textResource = R.string.lib_name
centerText()
}, lParams(height = wrapContent) {
centerHorizontally(); topOfParent(margin = dip(16))
})
val authorTv = add(textView {
textAppearance = MaterialR.style.TextAppearance_AppCompat_Small
textResource = R.string.a_lib_by_louiscad
centerText()
}, lParams(height = wrapContent) {
centerHorizontally(); topToBottomOf(headlineTv, margin = dip(8))
})
add(textView {
textAppearance = MaterialR.style.TextAppearance_AppCompat_Caption
textResource = R.string.licensed_under_apache_2
centerText()
}, lParams(height = wrapContent) {
centerHorizontally(); topToBottomOf(authorTv, margin = dip(8))
})
}
override val root = coordinatorLayout {
fitsSystemWindows = true
addDefaultAppBar(ctx)
add(mainContent, contentScrollingWithAppBarLParams())
}
}
//region IDE preview
@Deprecated("For IDE preview only", level = DeprecationLevel.HIDDEN)
private class AboutUiPreview(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : UiPreView(
context = context.withTheme(R.style.AppTheme),
attrs = attrs,
defStyleAttr = defStyleAttr,
createUi = { AboutUi(it) }
)
//endregion
|
apache-2.0
|
0935a212014115a22eb745654fe59742
| 34.149254 | 109 | 0.705308 | 4.401869 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt
|
2
|
26747
|
// 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.changeSignature
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.psi.*
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.refactoring.changeSignature.*
import com.intellij.refactoring.util.CanonicalTypes
import com.intellij.usageView.UsageInfo
import com.intellij.util.VisibilityUtil
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.builtins.isNonExtensionFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.core.unquote
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallerUsage
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.keysToMap
open class KotlinChangeInfo(
val methodDescriptor: KotlinMethodDescriptor,
private var name: String = methodDescriptor.name,
var newReturnTypeInfo: KotlinTypeInfo = KotlinTypeInfo(true, methodDescriptor.baseDescriptor.returnType),
var newVisibility: DescriptorVisibility = methodDescriptor.visibility,
parameterInfos: List<KotlinParameterInfo> = methodDescriptor.parameters,
receiver: KotlinParameterInfo? = methodDescriptor.receiver,
val context: PsiElement,
primaryPropagationTargets: Collection<PsiElement> = emptyList(),
var checkUsedParameters: Boolean = false,
) : ChangeInfo, UserDataHolder by UserDataHolderBase() {
private val innerChangeInfo: MutableList<KotlinChangeInfo> = mutableListOf()
fun registerInnerChangeInfo(changeInfo: KotlinChangeInfo) {
innerChangeInfo += changeInfo
}
private class JvmOverloadSignature(
val method: PsiMethod,
val mandatoryParams: Set<KtParameter>,
val defaultValues: Set<KtExpression>
) {
fun constrainBy(other: JvmOverloadSignature): JvmOverloadSignature {
return JvmOverloadSignature(
method,
mandatoryParams.intersect(other.mandatoryParams),
defaultValues.intersect(other.defaultValues)
)
}
}
private val originalReturnTypeInfo = methodDescriptor.returnTypeInfo
private val originalReceiverTypeInfo = methodDescriptor.receiver?.originalTypeInfo
var receiverParameterInfo: KotlinParameterInfo? = receiver
set(value) {
if (value != null && value !in newParameters) {
newParameters.add(value)
}
field = value
}
private val newParameters = parameterInfos.toMutableList()
private val originalPsiMethods = method.toLightMethods()
private val originalParameters = (method as? KtFunction)?.valueParameters ?: emptyList()
private val originalSignatures = makeSignatures(originalParameters, originalPsiMethods, { it }, { it.defaultValue })
private val oldNameToParameterIndex: Map<String, Int> by lazy {
val map = HashMap<String, Int>()
val parameters = methodDescriptor.baseDescriptor.valueParameters
parameters.indices.forEach { i -> map[parameters[i].name.asString()] = i }
map
}
private val isParameterSetOrOrderChangedLazy: Boolean by lazy {
val signatureParameters = getNonReceiverParameters()
methodDescriptor.receiver != receiverParameterInfo ||
signatureParameters.size != methodDescriptor.parametersCount ||
signatureParameters.indices.any { i -> signatureParameters[i].oldIndex != i }
}
private var isPrimaryMethodUpdated: Boolean = false
private var javaChangeInfos: List<JavaChangeInfo>? = null
var originalToCurrentMethods: Map<PsiMethod, PsiMethod> = emptyMap()
private set
val parametersToRemove: BooleanArray
get() {
val originalReceiver = methodDescriptor.receiver
val hasReceiver = methodDescriptor.receiver != null
val receiverShift = if (hasReceiver) 1 else 0
val toRemove = BooleanArray(receiverShift + methodDescriptor.parametersCount) { true }
if (hasReceiver) {
toRemove[0] = receiverParameterInfo == null && hasReceiver && originalReceiver !in getNonReceiverParameters()
}
for (parameter in newParameters) {
parameter.oldIndex.takeIf { it >= 0 }?.let { oldIndex ->
toRemove[receiverShift + oldIndex] = false
}
}
return toRemove
}
fun getOldParameterIndex(oldParameterName: String): Int? = oldNameToParameterIndex[oldParameterName]
override fun isParameterTypesChanged(): Boolean = true
override fun isParameterNamesChanged(): Boolean = true
override fun isParameterSetOrOrderChanged(): Boolean = isParameterSetOrOrderChangedLazy
fun getNewParametersCount(): Int = newParameters.size
fun hasAppendedParametersOnly(): Boolean {
val oldParamCount = originalBaseFunctionDescriptor.valueParameters.size
return newParameters.asSequence().withIndex().all { (i, p) -> if (i < oldParamCount) p.oldIndex == i else p.isNewParameter }
}
override fun getNewParameters(): Array<KotlinParameterInfo> = newParameters.toTypedArray()
fun getNonReceiverParametersCount(): Int = newParameters.size - (if (receiverParameterInfo != null) 1 else 0)
fun getNonReceiverParameters(): List<KotlinParameterInfo> {
methodDescriptor.baseDeclaration.let { if (it is KtProperty || it is KtParameter) return emptyList() }
return receiverParameterInfo?.let { receiver -> newParameters.filter { it != receiver } } ?: newParameters
}
fun setNewParameter(index: Int, parameterInfo: KotlinParameterInfo) {
newParameters[index] = parameterInfo
}
@JvmOverloads
fun addParameter(parameterInfo: KotlinParameterInfo, atIndex: Int = -1) {
if (atIndex >= 0) {
newParameters.add(atIndex, parameterInfo)
} else {
newParameters.add(parameterInfo)
}
}
fun removeParameter(index: Int) {
val parameterInfo = newParameters.removeAt(index)
if (parameterInfo == receiverParameterInfo) {
receiverParameterInfo = null
}
}
fun clearParameters() {
newParameters.clear()
receiverParameterInfo = null
}
fun hasParameter(parameterInfo: KotlinParameterInfo): Boolean =
parameterInfo in newParameters
override fun isGenerateDelegate(): Boolean = false
override fun getNewName(): String = name.takeIf { it != "<no name provided>" }?.quoteIfNeeded() ?: name
fun setNewName(value: String) {
name = value
}
override fun isNameChanged(): Boolean = name != methodDescriptor.name
fun isVisibilityChanged(): Boolean = newVisibility != methodDescriptor.visibility
override fun getMethod(): PsiElement {
return methodDescriptor.method
}
override fun isReturnTypeChanged(): Boolean = !newReturnTypeInfo.isEquivalentTo(originalReturnTypeInfo)
fun isReceiverTypeChanged(): Boolean {
val receiverInfo = receiverParameterInfo ?: return originalReceiverTypeInfo != null
return originalReceiverTypeInfo == null || !receiverInfo.currentTypeInfo.isEquivalentTo(originalReceiverTypeInfo)
}
override fun getLanguage(): Language = KotlinLanguage.INSTANCE
var propagationTargetUsageInfos: List<UsageInfo> = ArrayList()
private set
var primaryPropagationTargets: Collection<PsiElement> = emptyList()
set(value) {
field = value
val result = LinkedHashSet<UsageInfo>()
fun add(element: PsiElement) {
element.unwrapped?.let {
val usageInfo = when (it) {
is KtNamedFunction, is KtConstructor<*>, is KtClassOrObject ->
KotlinCallerUsage(it as KtNamedDeclaration)
is PsiMethod ->
CallerUsageInfo(it, true, true)
else ->
return
}
result.add(usageInfo)
}
}
for (caller in value) {
add(caller)
OverridingMethodsSearch.search(caller.getRepresentativeLightMethod() ?: continue).forEach(::add)
}
propagationTargetUsageInfos = result.toList()
}
init {
this.primaryPropagationTargets = primaryPropagationTargets
}
private fun renderReturnTypeIfNeeded(): String? {
val typeInfo = newReturnTypeInfo
if (kind != Kind.FUNCTION) return null
if (typeInfo.type?.isUnit() == true) return null
return typeInfo.render()
}
fun getNewSignature(inheritedCallable: KotlinCallableDefinitionUsage<PsiElement>): String {
val buffer = StringBuilder()
val isCustomizedVisibility = newVisibility != DescriptorVisibilities.DEFAULT_VISIBILITY
if (kind == Kind.PRIMARY_CONSTRUCTOR) {
buffer.append(newName)
if (isCustomizedVisibility) {
buffer.append(' ').append(newVisibility).append(" constructor ")
}
} else {
if (!DescriptorUtils.isLocal(inheritedCallable.originalCallableDescriptor) && isCustomizedVisibility) {
buffer.append(newVisibility).append(' ')
}
buffer.append(if (kind == Kind.SECONDARY_CONSTRUCTOR) KtTokens.CONSTRUCTOR_KEYWORD else KtTokens.FUN_KEYWORD).append(' ')
if (kind == Kind.FUNCTION) {
receiverParameterInfo?.let {
val typeInfo = it.currentTypeInfo
if (typeInfo.type != null && typeInfo.type.isNonExtensionFunctionType) {
buffer.append("(${typeInfo.render()})")
} else {
buffer.append(typeInfo.render())
}
buffer.append('.')
}
buffer.append(newName)
}
}
buffer.append(getNewParametersSignature(inheritedCallable))
renderReturnTypeIfNeeded()?.let { buffer.append(": ").append(it) }
return buffer.toString()
}
fun getNewParametersSignature(inheritedCallable: KotlinCallableDefinitionUsage<*>): String {
return "(" + getNewParametersSignatureWithoutParentheses(inheritedCallable) + ")"
}
fun getNewParametersSignatureWithoutParentheses(
inheritedCallable: KotlinCallableDefinitionUsage<*>
): String {
val signatureParameters = getNonReceiverParameters()
val isLambda = inheritedCallable.declaration is KtFunctionLiteral
if (isLambda && signatureParameters.size == 1 && !signatureParameters[0].requiresExplicitType(inheritedCallable)) {
return signatureParameters[0].getDeclarationSignature(0, inheritedCallable).text
}
return signatureParameters.indices.joinToString(separator = ", ") { i ->
signatureParameters[i].getDeclarationSignature(i, inheritedCallable).text
}
}
fun renderReceiverType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String? {
val receiverTypeText = receiverParameterInfo?.currentTypeInfo?.render() ?: return null
val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return receiverTypeText
val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return receiverTypeText
val receiverType = currentBaseFunction.extensionReceiverParameter!!.type
if (receiverType.isError) return receiverTypeText
return receiverType.renderTypeWithSubstitution(typeSubstitutor, receiverTypeText, false)
}
fun renderReturnType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String {
val defaultRendering = newReturnTypeInfo.render()
val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering
val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering
val returnType = currentBaseFunction.returnType!!
if (returnType.isError) return defaultRendering
return returnType.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, false)
}
fun primaryMethodUpdated() {
isPrimaryMethodUpdated = true
javaChangeInfos = null
for (info in innerChangeInfo) {
info.primaryMethodUpdated()
}
}
private fun <Parameter> makeSignatures(
parameters: List<Parameter>,
psiMethods: List<PsiMethod>,
getPsi: (Parameter) -> KtParameter,
getDefaultValue: (Parameter) -> KtExpression?
): List<JvmOverloadSignature> {
val defaultValueCount = parameters.count { getDefaultValue(it) != null }
if (psiMethods.size != defaultValueCount + 1) return emptyList()
val mandatoryParams = parameters.toMutableList()
val defaultValues = ArrayList<KtExpression>()
return psiMethods.map { method ->
JvmOverloadSignature(method, mandatoryParams.asSequence().map(getPsi).toSet(), defaultValues.toSet()).apply {
val param = mandatoryParams.removeLast { getDefaultValue(it) != null } ?: return@apply
defaultValues.add(getDefaultValue(param)!!)
}
}
}
private fun <T> MutableList<T>.removeLast(condition: (T) -> Boolean): T? {
val index = indexOfLast(condition)
return if (index >= 0) removeAt(index) else null
}
fun getOrCreateJavaChangeInfos(): List<JavaChangeInfo>? {
fun initCurrentSignatures(currentPsiMethods: List<PsiMethod>): List<JvmOverloadSignature> {
val parameterInfoToPsi = methodDescriptor.original.parameters.zip(originalParameters).toMap()
val dummyParameter = KtPsiFactory(method).createParameter("dummy")
return makeSignatures(
parameters = newParameters,
psiMethods = currentPsiMethods,
getPsi = { parameterInfoToPsi[it] ?: dummyParameter },
getDefaultValue = { it.defaultValue },
)
}
fun matchOriginalAndCurrentMethods(currentPsiMethods: List<PsiMethod>): Map<PsiMethod, PsiMethod> {
if (!(isPrimaryMethodUpdated && originalBaseFunctionDescriptor is FunctionDescriptor && originalBaseFunctionDescriptor.findJvmOverloadsAnnotation() != null)) {
return (originalPsiMethods.zip(currentPsiMethods)).toMap()
}
if (originalPsiMethods.isEmpty() || currentPsiMethods.isEmpty()) return emptyMap()
currentPsiMethods.singleOrNull()?.let { method -> return originalPsiMethods.keysToMap { method } }
val currentSignatures = initCurrentSignatures(currentPsiMethods)
return originalSignatures.associateBy({ it.method }) { originalSignature ->
var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) }
val maxMandatoryCount = constrainedCurrentSignatures.maxOf { it.mandatoryParams.size }
constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount }
val maxDefaultCount = constrainedCurrentSignatures.maxOf { it.defaultValues.size }
constrainedCurrentSignatures.last { it.defaultValues.size == maxDefaultCount }.method
}
}
/*
* When primaryMethodUpdated is false, changes to the primary Kotlin declaration are already confirmed, but not yet applied.
* It means that originalPsiMethod has already expired, but new one can't be created until Kotlin declaration is updated
* (signified by primaryMethodUpdated being true). It means we can't know actual PsiType, visibility, etc.
* to use in JavaChangeInfo. However they are not actually used at this point since only parameter count and order matters here
* So we resort to this hack and pass around "default" type (void) and visibility (package-local)
*/
fun createJavaChangeInfo(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
newName: String,
newReturnType: PsiType?,
newParameters: Array<ParameterInfoImpl>
): JavaChangeInfo? {
if (!newName.unquote().isIdentifier()) return null
val newVisibility = if (isPrimaryMethodUpdated)
VisibilityUtil.getVisibilityModifier(currentPsiMethod.modifierList)
else
PsiModifier.PACKAGE_LOCAL
val propagationTargets = primaryPropagationTargets.asSequence()
.mapNotNull { it.getRepresentativeLightMethod() }
.toSet()
val javaChangeInfo = ChangeSignatureProcessor(
method.project,
originalPsiMethod,
false,
newVisibility,
newName,
CanonicalTypes.createTypeWrapper(newReturnType ?: PsiType.VOID),
newParameters,
arrayOf<ThrownExceptionInfo>(),
propagationTargets,
emptySet()
).changeInfo
javaChangeInfo.updateMethod(currentPsiMethod)
return javaChangeInfo
}
fun getJavaParameterInfos(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
newParameterList: List<KotlinParameterInfo>
): MutableList<ParameterInfoImpl> {
val defaultValuesToSkip = newParameterList.size - currentPsiMethod.parameterList.parametersCount
val defaultValuesToRetain = newParameterList.count { it.defaultValue != null } - defaultValuesToSkip
val oldIndices = newParameterList.map { it.oldIndex }.toIntArray()
// TODO: Ugly code, need to refactor Change Signature data model
var defaultValuesRemained = defaultValuesToRetain
for (param in newParameterList) {
if (param.isNewParameter || param.defaultValue == null || defaultValuesRemained-- > 0) continue
newParameterList.asSequence()
.withIndex()
.filter { it.value.oldIndex >= param.oldIndex }
.toList()
.forEach { oldIndices[it.index]-- }
}
defaultValuesRemained = defaultValuesToRetain
val oldParameterCount = originalPsiMethod.parameterList.parametersCount
var indexInCurrentPsiMethod = 0
return newParameterList.asSequence().withIndex().mapNotNullTo(ArrayList()) map@{ pair ->
val (i, info) = pair
if (info.defaultValue != null && defaultValuesRemained-- <= 0) return@map null
val oldIndex = oldIndices[i]
val javaOldIndex = when {
methodDescriptor.receiver == null -> oldIndex
info == methodDescriptor.receiver -> 0
oldIndex >= 0 -> oldIndex + 1
else -> -1
}
if (javaOldIndex >= oldParameterCount) return@map null
val type = if (isPrimaryMethodUpdated)
currentPsiMethod.parameterList.parameters[indexInCurrentPsiMethod++].type
else
PsiType.VOID
val defaultValue = info.defaultValueForCall ?: info.defaultValue
ParameterInfoImpl(javaOldIndex, info.name, type, defaultValue?.text ?: "")
}
}
fun createJavaChangeInfoForFunctionOrGetter(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
isGetter: Boolean
): JavaChangeInfo? {
val newParameterList = listOfNotNull(receiverParameterInfo) + getNonReceiverParameters()
val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, newParameterList).toTypedArray()
val newName = if (isGetter) JvmAbi.getterName(newName) else newName
return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, currentPsiMethod.returnType, newJavaParameters)
}
fun createJavaChangeInfoForSetter(originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod): JavaChangeInfo? {
val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, listOfNotNull(receiverParameterInfo))
val oldIndex = if (methodDescriptor.receiver != null) 1 else 0
if (isPrimaryMethodUpdated) {
val newIndex = if (receiverParameterInfo != null) 1 else 0
val setterParameter = currentPsiMethod.parameterList.parameters[newIndex]
newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type))
} else {
newJavaParameters.add(ParameterInfoImpl(oldIndex, "receiver", PsiType.VOID))
}
val newName = JvmAbi.setterName(newName)
return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, PsiType.VOID, newJavaParameters.toTypedArray())
}
if (!TargetPlatformDetector.getPlatform(method.containingFile as KtFile).isJvm()) return null
if (javaChangeInfos == null) {
val method = method
originalToCurrentMethods = matchOriginalAndCurrentMethods(method.toLightMethods())
javaChangeInfos = originalToCurrentMethods.entries.mapNotNull {
val (originalPsiMethod, currentPsiMethod) = it
when (method) {
is KtFunction, is KtClassOrObject ->
createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, false)
is KtProperty, is KtParameter -> {
val accessorName = originalPsiMethod.name
when {
JvmAbi.isGetterName(accessorName) ->
createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, true)
JvmAbi.isSetterName(accessorName) ->
createJavaChangeInfoForSetter(originalPsiMethod, currentPsiMethod)
else -> null
}
}
else -> null
}
}
}
return javaChangeInfos
}
}
val KotlinChangeInfo.originalBaseFunctionDescriptor: CallableDescriptor
get() = methodDescriptor.baseDescriptor
val KotlinChangeInfo.kind: Kind get() = methodDescriptor.kind
val KotlinChangeInfo.oldName: String?
get() = (methodDescriptor.method as? KtFunction)?.name
fun KotlinChangeInfo.getAffectedCallables(): Collection<UsageInfo> = methodDescriptor.affectedCallables + propagationTargetUsageInfos
fun ChangeInfo.toJetChangeInfo(
originalChangeSignatureDescriptor: KotlinMethodDescriptor,
resolutionFacade: ResolutionFacade
): KotlinChangeInfo {
val method = method as PsiMethod
val functionDescriptor = method.getJavaOrKotlinMemberDescriptor(resolutionFacade) as CallableDescriptor
val parameterDescriptors = functionDescriptor.valueParameters
//noinspection ConstantConditions
val originalParameterDescriptors = originalChangeSignatureDescriptor.baseDescriptor.valueParameters
val newParameters = newParameters.withIndex().map { pair ->
val (i, info) = pair
val oldIndex = info.oldIndex
val currentType = parameterDescriptors[i].type
val defaultValueText = info.defaultValue
val defaultValueExpr =
when {
info is KotlinAwareJavaParameterInfoImpl -> info.kotlinDefaultValue
language.`is`(JavaLanguage.INSTANCE) && !defaultValueText.isNullOrEmpty() -> {
PsiElementFactory.getInstance(method.project).createExpressionFromText(defaultValueText, null).j2k()
}
else -> null
}
val parameterType = if (oldIndex >= 0) originalParameterDescriptors[oldIndex].type else currentType
val originalKtParameter = originalParameterDescriptors.getOrNull(oldIndex)?.source?.getPsi() as? KtParameter
val valOrVar = originalKtParameter?.valOrVarKeyword?.toValVar() ?: KotlinValVar.None
KotlinParameterInfo(
callableDescriptor = functionDescriptor,
originalIndex = oldIndex,
name = info.name,
originalTypeInfo = KotlinTypeInfo(false, parameterType),
defaultValueForCall = defaultValueExpr,
valOrVar = valOrVar
).apply {
currentTypeInfo = KotlinTypeInfo(false, currentType)
}
}
return KotlinChangeInfo(
originalChangeSignatureDescriptor,
newName,
KotlinTypeInfo(true, functionDescriptor.returnType),
functionDescriptor.visibility,
newParameters,
null,
method
)
}
|
apache-2.0
|
426c0344cdf3d9d04d974ab49a63c98c
| 43.356551 | 171 | 0.67301 | 6.234732 | false | false | false | false |
Bluexin/mek-re
|
src/main/java/be/bluexin/mekre/containers/OperatingTEContainer.kt
|
1
|
1574
|
package be.bluexin.mekre.containers
import be.bluexin.mekre.Refs
import be.bluexin.mekre.guis.MGuiContainer
import be.bluexin.mekre.tiles.OperatingTE
import com.teamwizardry.librarianlib.common.container.ContainerBase
import com.teamwizardry.librarianlib.common.container.GuiHandler
import com.teamwizardry.librarianlib.common.container.InventoryWrapper
import com.teamwizardry.librarianlib.common.container.builtin.BaseWrappers
import net.minecraft.entity.player.EntityPlayer
/**
* Part of mek_re by Bluexin, released under GNU GPLv3.
*
* @author Bluexin
*/
class OperatingTEContainer(player: EntityPlayer, te: OperatingTE) : ContainerBase(player) {
val invPlayer = BaseWrappers.player(player)
val invBlock = OperatingTEWrapper(te)
init {
addSlots(invPlayer)
addSlots(invBlock)
transferRule().from(invPlayer.main).from(invPlayer.hotbar).deposit(invBlock.input).filter {
true // TODO: "can be processed?"
}
transferRule().from(invBlock.input).from(invBlock.output).deposit(invPlayer.main).deposit(invPlayer.hotbar)
}
companion object {
val NAME = Refs.getResourceLocation("operatingtecontainer")
init {
GuiHandler.registerBasicContainer(NAME, { player, pos, tile -> OperatingTEContainer(player, tile as OperatingTE) }, { player, container -> MGuiContainer(container) })
}
}
}
class OperatingTEWrapper(inventory: OperatingTE) : InventoryWrapper(inventory) {
val input = slots[inventory.inputRange]
val output = slots[inventory.outputRange]
}
|
gpl-3.0
|
3702727471b7bbecf8ac5d41d9bc5f48
| 33.977778 | 178 | 0.743329 | 3.88642 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/view/SimpleColoredTextIcon.kt
|
5
|
7248
|
// 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.debugger.coroutine.view
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.debugger.settings.ThreadsViewSettings
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.frame.presentation.XValuePresentation
import com.intellij.xdebugger.impl.ui.DebuggerUIUtil
import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants
import com.sun.jdi.Location
import com.sun.jdi.ReferenceType
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData
import org.jetbrains.kotlin.idea.debugger.coroutine.data.State
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
import javax.swing.Icon
class SimpleColoredTextIcon(val icon: Icon?, val hasChildren: Boolean) {
private val texts = mutableListOf<String>()
private val textKeyAttributes = mutableListOf<TextAttributesKey>()
constructor(icon: Icon?, hasChildren: Boolean, text: String) : this(icon, hasChildren) {
append(text)
}
internal fun append(value: String) {
texts.add(value)
textKeyAttributes.add(CoroutineDebuggerColors.REGULAR_ATTRIBUTES)
}
internal fun appendValue(value: String) {
texts.add(value)
textKeyAttributes.add(CoroutineDebuggerColors.VALUE_ATTRIBUTES)
}
private fun appendToComponent(component: ColoredTextContainer) {
val size: Int = texts.size
for (i in 0 until size) {
val text: String = texts[i]
val attribute: TextAttributesKey = textKeyAttributes[i]
val simpleTextAttribute = toSimpleTextAttribute(attribute)
component.append(text, simpleTextAttribute)
}
}
private fun toSimpleTextAttribute(attribute: TextAttributesKey) =
when (attribute) {
CoroutineDebuggerColors.REGULAR_ATTRIBUTES -> SimpleTextAttributes.REGULAR_ATTRIBUTES
CoroutineDebuggerColors.VALUE_ATTRIBUTES -> XDebuggerUIConstants.VALUE_NAME_ATTRIBUTES
else -> SimpleTextAttributes.REGULAR_ATTRIBUTES
}
fun forEachTextBlock(f: (Pair<String, TextAttributesKey>) -> Unit) {
for (pair in texts zip textKeyAttributes)
f(pair)
}
fun simpleString(): String {
val component = SimpleColoredComponent()
appendToComponent(component)
return component.getCharSequence(false).toString()
}
fun valuePresentation(): XValuePresentation {
return object : XValuePresentation() {
override fun isShowName() = false
override fun getSeparator() = ""
override fun renderValue(renderer: XValueTextRenderer) {
forEachTextBlock {
renderer.renderValue(it.first, it.second)
}
}
}
}
}
interface CoroutineDebuggerColors {
companion object {
val REGULAR_ATTRIBUTES: TextAttributesKey = HighlighterColors.TEXT
val VALUE_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("KOTLIN_COROUTINE_DEBUGGER_VALUE", HighlighterColors.TEXT)
}
}
fun fromState(state: State): Icon =
when (state) {
State.SUSPENDED -> AllIcons.Debugger.ThreadFrozen
State.RUNNING -> AllIcons.Debugger.ThreadRunning
State.CREATED -> AllIcons.Debugger.ThreadStates.Idle
else -> AllIcons.Debugger.ThreadStates.Daemon_sign
}
class SimpleColoredTextIconPresentationRenderer {
companion object {
val log by logger
}
private val settings: ThreadsViewSettings = ThreadsViewSettings.getInstance()
fun render(infoData: CoroutineInfoData): SimpleColoredTextIcon {
val thread = infoData.activeThread
val name = thread?.name()?.substringBefore(" @${infoData.descriptor.name}") ?: ""
val threadState = if (thread != null) DebuggerUtilsEx.getThreadStatusText(thread.status()) else ""
val icon = fromState(infoData.descriptor.state)
val label = SimpleColoredTextIcon(icon, !infoData.isCreated())
label.append("\"")
label.appendValue(infoData.descriptor.formatName())
label.append("\": ${infoData.descriptor.state}")
if (name.isNotEmpty()) {
label.append(" on thread \"")
label.appendValue(name)
label.append("\": $threadState")
}
return label
}
/**
* Taken from #StackFrameDescriptorImpl.calcRepresentation
*/
fun render(location: Location): SimpleColoredTextIcon {
val label = SimpleColoredTextIcon(null, false)
DebuggerUIUtil.getColorScheme(null)
if (location.method() != null) {
val myName = location.method().name()
val methodDisplay = if (settings.SHOW_ARGUMENTS_TYPES)
DebuggerUtilsEx.methodNameWithArguments(location.method())
else
myName
label.appendValue(methodDisplay)
}
if (settings.SHOW_LINE_NUMBER) {
label.append(":")
label.append("" + DebuggerUtilsEx.getLineNumber(location, false))
}
if (settings.SHOW_CLASS_NAME) {
val name = try {
val refType: ReferenceType = location.declaringType()
refType.name()
} catch (e: InternalError) {
e.toString()
}
if (name != null) {
label.append(", ")
val dotIndex = name.lastIndexOf('.')
if (dotIndex < 0) {
label.append(name)
} else {
label.append(name.substring(dotIndex + 1))
if (settings.SHOW_PACKAGE_NAME) {
label.append(" (${name.substring(0, dotIndex)})")
}
}
}
}
if (settings.SHOW_SOURCE_NAME) {
label.append(", ")
val sourceName = DebuggerUtilsEx.getSourceName(location) { e: Throwable? ->
log.error("Error while trying to resolve sourceName for location", e, location.toString())
"Unknown Source"
}
label.append(sourceName)
}
return label
}
fun renderCreationNode() =
SimpleColoredTextIcon(
null, true, KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace")
)
fun renderErrorNode(error: String) =
SimpleColoredTextIcon(AllIcons.Actions.Lightning, false, KotlinDebuggerCoroutinesBundle.message(error))
fun renderInfoNode(text: String) =
SimpleColoredTextIcon(AllIcons.General.Information, false, KotlinDebuggerCoroutinesBundle.message(text))
fun renderGroup(groupName: String) =
SimpleColoredTextIcon(AllIcons.Debugger.ThreadGroup, true, groupName)
}
|
apache-2.0
|
a2738acd47eb2b45aed14732e23fe975
| 36.947644 | 158 | 0.65963 | 5.089888 | false | false | false | false |
smmribeiro/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/expressions/UReturnExpression.kt
|
11
|
1281
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents a `return` expression.
*/
interface UReturnExpression : UJumpExpression {
/**
* Returns the `return` value.
*/
val returnExpression: UExpression?
override fun accept(visitor: UastVisitor) {
if (visitor.visitReturnExpression(this)) return
uAnnotations.acceptList(visitor)
returnExpression?.accept(visitor)
visitor.afterVisitReturnExpression(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R =
visitor.visitReturnExpression(this, data)
override fun asRenderString(): String = returnExpression.let { if (it == null) "return" else "return " + it.asRenderString() }
override fun asLogString(): String = log()
@JvmDefault
override val label: String?
get() = null
@JvmDefault
override val jumpTarget: UElement? get() =
generateSequence(uastParent) { it.uastParent }
.find { it is ULambdaExpression || it is UMethod }
}
|
apache-2.0
|
2a2d1b784efb405a440bc642e2f9ab26
| 30.268293 | 140 | 0.733802 | 4.284281 | false | false | false | false |
anitawoodruff/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/extensions/AlertDialog-Extensions.kt
|
1
|
761
|
package com.habitrpg.android.habitica.extensions
import android.content.DialogInterface
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
fun HabiticaAlertDialog.addOkButton(isPrimary: Boolean = true, listener: ((HabiticaAlertDialog, Int) -> Unit)? = null) {
this.addButton(R.string.ok, isPrimary, false, listener)
}
fun HabiticaAlertDialog.addCloseButton(isPrimary: Boolean = false, listener: ((DialogInterface, Int) -> Unit)? = null) {
this.addButton(R.string.close, isPrimary, false, listener)
}
fun HabiticaAlertDialog.addCancelButton(isPrimary: Boolean = false, listener: ((DialogInterface, Int) -> Unit)? = null) {
this.addButton(R.string.cancel, isPrimary, false, listener)
}
|
gpl-3.0
|
bcb4e082937819e3104b1d166aa27ccc
| 43.823529 | 121 | 0.773982 | 4.13587 | false | false | false | false |
tensorflow/examples
|
lite/examples/style_transfer/android/app/src/main/java/org/tensorflow/lite/examples/styletransfer/fragments/TransformationFragment.kt
|
1
|
9011
|
/*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* 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.tensorflow.lite.examples.styletransfer.fragments
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import org.tensorflow.lite.examples.styletransfer.MainViewModel
import org.tensorflow.lite.examples.styletransfer.R
import org.tensorflow.lite.examples.styletransfer.StyleTransferHelper
import org.tensorflow.lite.examples.styletransfer.databinding.FragmentTransformationBinding
import java.io.InputStream
class TransformationFragment : Fragment(),
StyleTransferHelper.StyleTransferListener {
private var _fragmentTransformationBinding: FragmentTransformationBinding? =
null
private val fragmentTransformationBinding get() = _fragmentTransformationBinding!!
private val viewModel: MainViewModel by activityViewModels()
private lateinit var styleTransferHelper: StyleTransferHelper
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_fragmentTransformationBinding =
FragmentTransformationBinding.inflate(inflater, container, false)
return fragmentTransformationBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
styleTransferHelper = StyleTransferHelper(
numThreads = viewModel.defaultModelNumThreads,
currentDelegate = viewModel.defaultModelDelegate,
currentModel = viewModel.defaultModel,
context = requireContext(),
styleTransferListener = this
)
// Set default value for controller view
fragmentTransformationBinding.spinnerDelegate.setSelection(
viewModel.defaultModelDelegate,
false
)
fragmentTransformationBinding.spinnerModel.setSelection(
viewModel.defaultModel,
false
)
fragmentTransformationBinding.threadsValue.text =
viewModel.defaultModelNumThreads.toString()
// Setup list style image
getListStyle().let { styles ->
with(fragmentTransformationBinding.recyclerViewStyle) {
val linearLayoutManager = LinearLayoutManager(
context,
LinearLayoutManager.HORIZONTAL, false
)
layoutManager = linearLayoutManager
val dividerItemDecoration = DividerItemDecoration(
context,
linearLayoutManager.orientation
)
dividerItemDecoration.setDrawable(
ContextCompat.getDrawable
(context, R.drawable.decoration_divider)!!
)
addItemDecoration(dividerItemDecoration)
adapter = StyleAdapter(styles) { pos ->
getBitmapFromAssets(
"thumbnails/${styles[pos].imagePath}"
)?.let {
styleTransferHelper.setStyleImage(it)
}
}.apply {
// Set default style image
setSelected(0, true)
getBitmapFromAssets("thumbnails/${styles[0].imagePath}")?.let {
styleTransferHelper.setStyleImage(it)
}
}
}
}
// Attach listeners to UI control widgets
initControllerViews()
viewModel.getInputBitmap()?.let { originalBitmap ->
// Display the original at the first time.
Glide.with(requireActivity()).load(originalBitmap).centerCrop()
.into(fragmentTransformationBinding.imgStyled)
fragmentTransformationBinding.btnTransfer.setOnClickListener {
styleTransferHelper.transfer(originalBitmap)
}
}
}
override fun onError(error: String) {
activity?.runOnUiThread {
Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show()
}
}
override fun onResult(bitmap: Bitmap, inferenceTime: Long) {
activity?.runOnUiThread {
Glide.with(requireContext()).load(bitmap).centerCrop()
.into(fragmentTransformationBinding.imgStyled)
fragmentTransformationBinding.inferenceTimeVal.text =
String.format("%d ms", inferenceTime)
}
}
private fun initControllerViews() {
// When clicked, decrease the number of threads used for transformation
fragmentTransformationBinding.threadsMinus.setOnClickListener {
if (styleTransferHelper.numThreads > 1) {
styleTransferHelper.numThreads--
updateControlsUi()
}
}
// When clicked, increase the number of threads used for transformation
fragmentTransformationBinding.threadsPlus.setOnClickListener {
if (styleTransferHelper.numThreads < 4) {
styleTransferHelper.numThreads++
updateControlsUi()
}
}
// When clicked, change the underlying hardware used for inference.
// Current options are CPU, GPU, and NNAPI
fragmentTransformationBinding.spinnerDelegate.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
styleTransferHelper.currentDelegate = position
viewModel.defaultModelDelegate = position
updateControlsUi()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
/* no op */
}
}
// When clicked, change the underlying model used for object
// transformation
fragmentTransformationBinding.spinnerModel.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
styleTransferHelper.currentModel = position
viewModel.defaultModel = position
updateControlsUi()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
/* no op */
}
}
}
// Update the values displayed in the controller view. Reset transfer.
private fun updateControlsUi() {
viewModel.defaultModelNumThreads = styleTransferHelper.numThreads
fragmentTransformationBinding.threadsValue.text =
styleTransferHelper.numThreads.toString()
// Needs to be cleared instead of reinitialized because the GPU
// delegate needs to be initialized on the thread using it when applicable
styleTransferHelper.clearStyleTransferHelper()
}
private fun getListStyle(): MutableList<StyleAdapter.Style> {
val styles = mutableListOf<StyleAdapter.Style>()
requireActivity().assets.list("thumbnails")?.forEach {
styles.add(StyleAdapter.Style(it))
}
return styles
}
private fun getBitmapFromAssets(fileName: String): Bitmap? {
val assetManager: AssetManager = requireActivity().assets
return try {
val istr: InputStream = assetManager.open(fileName)
val bitmap = BitmapFactory.decodeStream(istr)
istr.close()
bitmap
} catch (e: Exception) {
null
}
}
}
|
apache-2.0
|
996ede636696066cfd27853aede5c3b1
| 37.840517 | 91 | 0.631561 | 5.866536 | false | false | false | false |
michaelkourlas/voipms-sms-client
|
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/preferences/activities/DidsPreferencesActivity.kt
|
1
|
6715
|
/*
* VoIP.ms SMS
* Copyright (C) 2017-2019 Michael Kourlas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kourlas.voipms_sms.preferences.activities
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.runBlocking
import net.kourlas.voipms_sms.R
import net.kourlas.voipms_sms.database.Database
import net.kourlas.voipms_sms.network.NetworkManager
import net.kourlas.voipms_sms.preferences.accountConfigured
import net.kourlas.voipms_sms.preferences.fragments.DidsPreferencesFragment
import net.kourlas.voipms_sms.sms.workers.RetrieveDidsWorker
import net.kourlas.voipms_sms.utils.safeUnregisterReceiver
import net.kourlas.voipms_sms.utils.showSnackbar
/**
* Activity that houses a PreferencesFragment that displays the DID selection
* preferences.
*/
class DidsPreferencesActivity : AppCompatActivity() {
// Preferences fragment for this preferences activity
private lateinit var fragment: DidsPreferencesFragment
// Saved instance state
private var savedInstanceState: Bundle? = null
// Broadcast receivers
private val didRetrievalCompleteReceiver =
object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// Show error if one occurred
val retrievedDids = intent?.getStringArrayListExtra(
getString(
R.string.retrieve_dids_complete_dids
)
)
val error = intent?.getStringExtra(
getString(
R.string.retrieve_dids_complete_error
)
)
if (error != null) {
showSnackbar(
this@DidsPreferencesActivity,
R.id.coordinator_layout,
error
)
}
loadPreferences(retrievedDids)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.savedInstanceState = savedInstanceState
// Load activity layout
setContentView(R.layout.preferences_dids)
// Configure toolbar
setSupportActionBar(findViewById(R.id.toolbar))
supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
}
// Load info message
val textView = findViewById<TextView>(R.id.info_text_view)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.text = Html.fromHtml(
getString(R.string.preferences_dids_info), 0
)
} else {
@Suppress("DEPRECATION")
textView.text = Html.fromHtml(
getString(R.string.preferences_dids_info)
)
}
textView.movementMethod = LinkMovementMethod.getInstance()
retrieveDids()
}
override fun onResume() {
super.onResume()
// Register dynamic receivers for this fragment
registerReceiver(
didRetrievalCompleteReceiver,
IntentFilter(getString(R.string.retrieve_dids_complete_action))
)
}
override fun onPause() {
super.onPause()
// Unregister dynamic receivers for this fragment
safeUnregisterReceiver(this, didRetrievalCompleteReceiver)
}
override fun onDestroy() {
super.onDestroy()
this.savedInstanceState = null
}
/**
* Starts the [RetrieveDidsWorker], which will retrieve the DIDs to
* show in this activity.
*/
private fun retrieveDids() {
// Verify email and password are set and that Internet connection is
// available to avoid lengthy timeout
if (!accountConfigured(this)) {
loadPreferences(null)
return
}
if (!NetworkManager.getInstance().isNetworkConnectionAvailable(this)) {
showSnackbar(
this, R.id.coordinator_layout, getString(
R.string.preferences_dids_error_network
)
)
loadPreferences(null)
return
}
// Pass control to RetrieveDidsService
RetrieveDidsWorker.retrieveDids(this)
}
/**
* Creates a preference for each of the specified DIDs, which were
* retrieved from VoIP.ms, as well as DIDs from the database, and loads
* them into this activity.
*
* @param retrievedDids The retrieved DIDs to show.
*/
private fun loadPreferences(retrievedDids: ArrayList<String>?) {
// Hide progress bar
val preloadLayout = findViewById<View>(R.id.preferences_preload_layout)
val postloadLayout = findViewById<View>(
R.id.preferences_postload_layout
)
preloadLayout.visibility = View.GONE
postloadLayout.visibility = View.VISIBLE
// Load preferences fragment
val bundle = Bundle()
bundle.putStringArrayList(
getString(
R.string
.preferences_dids_fragment_retrieved_dids_key
),
retrievedDids
)
val databaseDids = runBlocking {
Database.getInstance(applicationContext)
.getDids()
}
bundle.putStringArrayList(
getString(
R.string
.preferences_dids_fragment_database_dids_key
),
ArrayList(databaseDids)
)
if (this.savedInstanceState == null) {
fragment = DidsPreferencesFragment()
fragment.arguments = bundle
supportFragmentManager.beginTransaction().replace(
R.id.preferences_fragment_layout, fragment
).commit()
}
}
}
|
apache-2.0
|
32bf007480fb67266c897342759df11d
| 32.083744 | 79 | 0.627252 | 5.197368 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideHierarchyNodeDescriptor.kt
|
1
|
6535
|
// 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.hierarchy.overrides
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.ide.hierarchy.HierarchyNodeDescriptor
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.roots.ui.util.CompositeAppearance
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Iconable
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.ui.LayeredIcon
import com.intellij.ui.RowIcon
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.util.getTypeSubstitution
import org.jetbrains.kotlin.idea.util.substitute
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.parents
import org.jetbrains.kotlin.util.findCallableMemberBySignature
import java.awt.Font
import javax.swing.Icon
class KotlinOverrideHierarchyNodeDescriptor(
parentNode: HierarchyNodeDescriptor?,
klass: PsiElement,
baseElement: PsiElement
) : HierarchyNodeDescriptor(klass.project, parentNode, klass, parentNode == null) {
private val baseElement = baseElement.createSmartPointer()
private var rawIcon: Icon? = null
private var stateIcon: Icon? = null
private fun resolveToDescriptor(psiElement: PsiElement): DeclarationDescriptor? {
return when (psiElement) {
is KtNamedDeclaration -> psiElement.unsafeResolveToDescriptor()
is PsiMember -> psiElement.getJavaMemberDescriptor()
else -> null
}
}
private fun getBaseDescriptor() = baseElement.element?.let { resolveToDescriptor(it) } as? CallableMemberDescriptor
private fun getCurrentClassDescriptor() = psiElement?.let { resolveToDescriptor(it) } as? ClassDescriptor
private fun getCurrentDescriptor(): CallableMemberDescriptor? {
val classDescriptor = getCurrentClassDescriptor() ?: return null
val baseDescriptor = getBaseDescriptor() ?: return null
val baseClassDescriptor = baseDescriptor.containingDeclaration as? ClassDescriptor ?: return null
val substitution = getTypeSubstitution(baseClassDescriptor.defaultType, classDescriptor.defaultType) ?: return null
return classDescriptor.findCallableMemberBySignature(baseDescriptor.substitute(substitution) as CallableMemberDescriptor)
}
internal fun calculateState(): Icon? {
val classDescriptor = getCurrentClassDescriptor() ?: return null
val callableDescriptor = getCurrentDescriptor() ?: return AllIcons.Hierarchy.MethodNotDefined
if (callableDescriptor.kind == CallableMemberDescriptor.Kind.DECLARATION) {
if (callableDescriptor.modality == Modality.ABSTRACT) return null
return AllIcons.Hierarchy.MethodDefined
}
val isAbstractClass = classDescriptor.modality == Modality.ABSTRACT
val hasBaseImplementation =
DescriptorUtils.getAllOverriddenDeclarations(callableDescriptor).any { it.modality != Modality.ABSTRACT }
return if (isAbstractClass || hasBaseImplementation) AllIcons.Hierarchy.MethodNotDefined else AllIcons.Hierarchy.ShouldDefineMethod
}
override fun update(): Boolean {
var flags = Iconable.ICON_FLAG_VISIBILITY
if (isMarkReadOnly) {
flags = flags or Iconable.ICON_FLAG_READ_STATUS
}
var changes = super.update()
val classPsi = psiElement
val classDescriptor = getCurrentClassDescriptor()
if (classPsi == null || classDescriptor == null) {
val invalidPrefix = IdeBundle.message("node.hierarchy.invalid")
if (!myHighlightedText.text.startsWith(invalidPrefix)) {
myHighlightedText.beginning.addText(invalidPrefix, getInvalidPrefixAttributes())
}
return true
}
val newRawIcon = classPsi.getIcon(flags)
val newStateIcon = calculateState()
if (changes || newRawIcon !== rawIcon || newStateIcon !== stateIcon) {
changes = true
rawIcon = newRawIcon
stateIcon = newStateIcon
var newIcon = rawIcon
if (myIsBase) {
val icon = LayeredIcon(2)
icon.setIcon(newIcon, 0)
icon.setIcon(AllIcons.Actions.Forward, 1, -AllIcons.Actions.Forward.iconWidth / 2, 0)
newIcon = icon
}
if (stateIcon != null) {
newIcon = RowIcon(stateIcon, newIcon)
}
icon = newIcon
}
val oldText = myHighlightedText
myHighlightedText = CompositeAppearance()
var classNameAttributes: TextAttributes? = null
if (myColor != null) {
classNameAttributes = TextAttributes(myColor, null, null, null, Font.PLAIN)
}
with(myHighlightedText.ending) {
@NlsSafe val classDescriptorAsString = classDescriptor.name.asString()
addText(classDescriptorAsString, classNameAttributes)
classDescriptor.parents.forEach { parentDescriptor ->
when (parentDescriptor) {
is MemberDescriptor -> {
addText(KotlinBundle.message("hierarchy.text.in", parentDescriptor.name.asString()), classNameAttributes)
if (parentDescriptor is FunctionDescriptor) {
addText("()", classNameAttributes)
}
}
is PackageFragmentDescriptor -> {
@NlsSafe val parentDescriptorAsString = parentDescriptor.fqName.asString()
addText(" ($parentDescriptorAsString)", getPackageNameAttributes())
return@forEach
}
}
}
}
myName = myHighlightedText.text
if (!Comparing.equal(myHighlightedText, oldText)) {
changes = true
}
return changes
}
}
|
apache-2.0
|
ffdc17f0e1a1ebf694e9ec97445418a2
| 41.167742 | 158 | 0.685692 | 5.464047 | false | false | false | false |
leafclick/intellij-community
|
plugins/stats-collector/src/com/intellij/stats/personalization/session/CompletionSelectionTrackerImpl.kt
|
1
|
1647
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.personalization.session
import com.intellij.openapi.diagnostic.logger
class CompletionSelectionTrackerImpl : CompletionSelectionTracker {
private val periodTracker = PeriodTracker()
private companion object {
val LOG = logger<CompletionSelectionTrackerImpl>()
}
override fun getTotalTimeInSelection(): Long = periodTracker.totalTime(currentSelectionTime())
override fun getTimesInSelection(): Int = periodTracker.count(currentSelectionTime())
override fun getAverageTimeInSelection(): Double = periodTracker.average(currentSelectionTime())
override fun getMaxTimeInSelection(): Long? = periodTracker.maxDuration(currentSelectionTime())
override fun getMinTimeInSelection(): Long? = periodTracker.minDuration(currentSelectionTime())
private var selectionStartedTimestamp: Long = -1
fun itemSelected() {
LOG.assertTrue(selectionStartedTimestamp == -1L, "Element already selected")
selectionStartedTimestamp = System.currentTimeMillis()
}
fun itemUnselected() {
val timestamp = selectionStartedTimestamp
if (timestamp != -1L) {
periodTracker.addDuration(System.currentTimeMillis() - timestamp)
selectionStartedTimestamp = -1
}
else {
LOG.error("Element should be selected")
}
}
private fun currentSelectionTime(): Long? {
val selectionStarted = selectionStartedTimestamp
if (selectionStarted != -1L) {
return System.currentTimeMillis() - selectionStarted
}
return null
}
}
|
apache-2.0
|
b8968577d1b3260b0827fcb258cd5dba
| 36.454545 | 140 | 0.758349 | 4.829912 | false | false | false | false |
code-helix/slatekit
|
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Database.kt
|
1
|
5116
|
/**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.db.Db
import slatekit.common.data.DbConString
//</doc:import_required>
//<doc:import_examples>
import slatekit.results.Try
import slatekit.results.Success
import slatekit.examples.common.User
import slatekit.meta.models.ModelMapper
import slatekit.orm.OrmMapper
import slatekit.orm.databases.vendors.MySqlConverter
//</doc:import_examples>
class Example_Database : Command("db") {
override fun execute(request: CommandRequest): Try<Any> {
//<doc:examples>
// NOTES:
// 1. The Db.kt simply uses JDBC
// 2. There is a separate Connectionsons.kt component that
// loads, stores, and manages named database connections.
// Refer to that example for more info.
// CASE 1: Create DB connection.
val con = DbConString(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost/default",
"root",
"abcdefghi"
)
// CASE 2. Initialize the DB with the connection string.
// NOTE: This defaults the db to mysql. The first line is same
// as db = Db(con, source: MySqlBuilder())
// In the future, we can more easily support mutliple databases
// using this approach.
val db = Db(con)
// CASE 3: Open the database
db.open()
// CASE 4: Get scalar values
val total1 = db.getScalarString ("select test_string from db_tests where id = 1", null)
val total2 = db.getScalarBool ("select test_bool from db_tests where id = 1", null)
val total3 = db.getScalarShort ("select test_short from db_tests where id = 1", null)
val total4 = db.getScalarInt ("select test_int from db_tests where id = 1", null)
val total5 = db.getScalarLong ("select test_long from db_tests where id = 1", null)
val total6 = db.getScalarDouble ("select test_double from db_tests where id = 1", null)
val total7 = db.getScalarLocalDate ("select test_ldate from db_tests where id = 1", null)
val total8 = db.getScalarLocalTime ("select test_ltime from db_tests where id = 1", null)
val total9 = db.getScalarLocalDateTime("select test_ldtime from db_tests where id = 1", null)
// CASE 5: Execute a sql insert
val id1 = db.insert("insert into `city`(`name`) values( 'ny' )")
// CASE 6: Execute a sql insert using parameters
val id2 = db.insert("insert into `city`(`name`) values( ? )", listOf("ny"))
// CASE 7: Execute a sql update
val count7 = db.update("update `city` set `alias` = 'nyc' where id = 2")
// CASE 8: Execute a sql udpate using parameters
val count8 = db.update("update `city` set `alias` = 'nyc' where id = ?", listOf(id2))
// CASE 9: Deletes are same as updates
val count9a = db.update("delete from `city` where id = 2")
val count9b = db.update("delete from `city` where id = ?", listOf(2))
// ===============================================================
// STORED PROCS
// ===============================================================
// CASE 10: Call a stored proc that updates data
val count10 = db.callUpdate("dbtests_activate_by_id", listOf(id2))
// CASE 11: Call a stored proc that fetches data
val count11 = db.callQuery("dbtests_max_by_id",
callback = { rs -> rs.getString(0) }, inputs = listOf(id2))
// ===============================================================
// MODELS / MAPPERS
// ===============================================================
// CASE 12: Map a record to an model using the mapper component
// The mapper will load a schema from the User class by checking
// for "Field" annotations
val userModelSchema = ModelMapper.loadSchema(User::class)
val mapper = OrmMapper<Long, User>(userModelSchema, db, MySqlConverter(), Long::class, User::class)
val item1 = db.mapOne<User>("select * from `user` where id = ?", listOf(1)) { mapper.decode(it, null) }
println(item1)
// CASE 13: Map multiple records
val items = db.mapAll<User>("select * from `user` where id < ?", listOf(5)) { mapper.decode(it, null) }
println(items)
// CASE 14: Create the table using the model
// Be careful with this, ensure you are using a connection string
// with limited permissions
//createTable(db, userModelSchema)
// CASE 15: Drop a table
// Be careful with this, ensure you are using a connection string
// with limited permissions.
//</doc:examples>
return Success("")
}
}
|
apache-2.0
|
72689b2cbfcf65e3b241a01a63b48da8
| 40.258065 | 112 | 0.591087 | 4.102646 | false | true | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-db/src/main/kotlin/slatekit/db/DbUtils.kt
|
1
|
11151
|
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.db
import slatekit.common.DateTime
import slatekit.common.data.DbCon
import java.sql.*
import org.threeten.bp.*
import slatekit.common.DateTimes
import slatekit.common.EnumLike
import slatekit.common.data.DataType
import slatekit.common.data.Value
import slatekit.common.ext.local
import slatekit.common.ids.ULID
import slatekit.common.ids.UPID
import java.util.*
object DbUtils {
val jdbcTypes = mapOf<DataType, Int>(
DataType.DTBool to java.sql.Types.BOOLEAN,
DataType.DTChar to java.sql.Types.CHAR,
DataType.DTString to java.sql.Types.VARCHAR,
DataType.DTText to java.sql.Types.LONGNVARCHAR,
DataType.DTShort to java.sql.Types.SMALLINT,
DataType.DTInt to java.sql.Types.INTEGER,
DataType.DTLong to java.sql.Types.BIGINT,
DataType.DTFloat to java.sql.Types.FLOAT,
DataType.DTDouble to java.sql.Types.DOUBLE,
DataType.DTDecimal to java.sql.Types.DECIMAL,
DataType.DTLocalDate to java.sql.Types.DATE,
DataType.DTLocalTime to java.sql.Types.TIME,
DataType.DTLocalDateTime to java.sql.Types.TIMESTAMP,
DataType.DTZonedDateTime to java.sql.Types.TIMESTAMP,
DataType.DTDateTime to java.sql.Types.TIMESTAMP,
DataType.DTInstant to java.sql.Types.TIMESTAMP,
DataType.DTEnum to java.sql.Types.INTEGER,
DataType.DTUUID to java.sql.Types.VARCHAR,
DataType.DTULID to java.sql.Types.VARCHAR,
DataType.DTUPID to java.sql.Types.VARCHAR
)
/**
* gets a new jdbc connection via Driver manager
*
* @return
*/
fun connect(con: DbCon, settings: DbSettings): Connection {
val con = if (con.driver == "com.mysql.jdbc.Driver")
DriverManager.getConnection(con.url, con.user, con.pswd)
else
DriverManager.getConnection(con.url)
con.autoCommit = settings.autoCommit
return con
}
/**
* Execution template providing connection with error-handling and connection closing
*
* @param con : The connection string
* @param callback : The callback to call for when the connection is ready
* @param error : The callback to call for when an error occurrs
*/
fun <T> executeCon(con: DbCon, settings: DbSettings, callback: (Connection) -> T, error: (Exception) -> Unit): T? {
val conn = connect(con, settings)
val result =
try {
conn.use { c ->
callback(c)
}
} catch (ex: Exception) {
error(ex)
null
}
return result
}
/**
* Execution template providing connection, statement with error-handling and connection closing
*
* @param con : The connection string
* @param callback : The callback to call for when the connection is ready
* @param error : The callback to call for when an error occurrs
*/
fun executeStmt(
con: DbCon,
settings: DbSettings,
callback: (Connection, Statement) -> Unit,
error: (Exception) -> Unit
) {
val conn = connect(con, settings)
try {
conn.use { c ->
val stmt = c.createStatement()
stmt.use { s ->
callback(c, s)
}
}
} catch (ex: Exception) {
error(ex)
}
}
/**
* Execution template providing connection, prepared statement with error-handling & conn closing
*
* @param con : The connection string
* @param sql : The sql text or stored proc name.
* @param callback : The callback to call for when the connection is ready
* @param error : The callback to call for when an error occurrs
*/
fun <T> executePrep(
con: DbCon,
settings: DbSettings,
sql: String,
callback: (Connection, PreparedStatement) -> T?,
error: (Exception) -> Unit
): T? {
val conn = connect(con, settings)
val result =
try {
conn.use { c ->
val stmt = c.prepareStatement(sql)
stmt.use { s ->
val r = callback(c, s)
r
}
}
} catch (ex: Exception) {
error(ex)
null
}
return result
}
/**
* Execution template providing connection, prepared statement with error-handling & conn closing
*
* @param con : The connection string
* @param sql : The sql text or stored proc name.
* @param callback : The callback to call for when the connection is ready
* @param error : The callback to call for when an error occurrs
*/
fun <T> executeCall(
con: DbCon,
settings: DbSettings,
sql: String,
callback: (Connection, PreparedStatement) -> T?,
error: (Exception) -> Unit
): T? {
val conn = connect(con, settings)
val result =
try {
conn.use { c ->
val stmt = c.prepareCall(sql)
stmt.use { s ->
val r = callback(c, s)
r
}
}
} catch (ex: Exception) {
error(ex)
null
}
return result
}
/**
* convenience function to fill prepared statement with parameters
*
* @param stmt
* @param inputs
*/
fun fillArgs(stmt: PreparedStatement, inputs: List<Value>?, error: (Exception) -> Unit) {
inputs?.forEachIndexed { index, arg ->
val pos = index + 1
try {
when (arg.value) {
null -> {
val type = jdbcTypes[arg.tpe]
stmt.setNull(pos, type ?: java.sql.Types.INTEGER)
}
else -> {
when (arg.tpe) {
DataType.DTString -> stmt.setString(pos, arg.value.toString())
DataType.DTBool -> stmt.setBoolean(pos, arg.value as Boolean)
DataType.DTShort -> stmt.setShort(pos, arg.value as Short)
DataType.DTInt -> stmt.setInt(pos, arg.value as Int)
DataType.DTLong -> stmt.setLong(pos, arg.value as Long)
DataType.DTFloat -> stmt.setFloat(pos, arg.value as Float)
DataType.DTDouble -> stmt.setDouble(pos, arg.value as Double)
DataType.DTEnum -> stmt.setInt(pos, toEnumValue(arg.value!!))
DataType.DTLocalDate -> stmt.setDate(pos, java.sql.Date.valueOf((arg.value as LocalDate).toJava8LocalDate()))
DataType.DTLocalTime -> stmt.setTime(pos, java.sql.Time.valueOf((arg.value as LocalTime).toJava8LocalTime()))
DataType.DTLocalDateTime -> stmt.setTimestamp(pos, java.sql.Timestamp.valueOf((arg.value as LocalDateTime).toJava8LocalDateTime()))
DataType.DTZonedDateTime -> stmt.setTimestamp(pos, java.sql.Timestamp.valueOf(((arg.value as ZonedDateTime).toJava8ZonedDateTime()).toLocalDateTime()))
DataType.DTInstant -> stmt.setTimestamp(pos, java.sql.Timestamp.valueOf((LocalDateTime.ofInstant(arg.value as Instant, ZoneId.systemDefault()).toJava8LocalDateTime())))
DataType.DTDateTime -> stmt.setTimestamp(pos, java.sql.Timestamp.valueOf(((arg.value as DateTime).local()).toJava8LocalDateTime()))
DataType.DTUUID -> stmt.setString(pos, (arg.value as UUID).toString())
DataType.DTULID -> stmt.setString(pos, (arg.value as ULID).value)
DataType.DTUPID -> stmt.setString(pos, (arg.value as UPID).value)
else -> stmt.setString(pos, arg.value.toString())
}
}
}
}
catch(ex:Exception) {
error(ex)
}
}
}
fun toEnumValue(value:Any):Int {
return when(value) {
is Int -> value
is EnumLike -> value.value
is Enum<*> -> value.ordinal
is String -> value.toInt()
else -> value.toString().toInt()
}
}
@Suppress("UNCHECKED_CAST")
fun <T> getScalar(rs: ResultSet, typ: DataType): T? {
val pos = 1
return if (typ == DataType.DTString ) rs.getString(pos) as T
else if (typ == DataType.DTBool ) rs.getBoolean(pos) as T
else if (typ == DataType.DTShort ) rs.getShort(pos) as T
else if (typ == DataType.DTInt ) rs.getInt(pos) as T
else if (typ == DataType.DTLong ) rs.getLong(pos) as T
else if (typ == DataType.DTFloat ) rs.getFloat(pos) as T
else if (typ == DataType.DTDouble ) rs.getDouble(pos) as T
else if (typ == DataType.DTLocalDate ) DateTimeUtils.toLocalDate(rs.getDate(pos)) as T
else if (typ == DataType.DTLocalTime ) DateTimeUtils.toLocalTime(rs.getTime(pos)) as T
else if (typ == DataType.DTLocalDateTime) DateTimeUtils.toLocalDateTime(rs.getTimestamp(pos)) as T
else if (typ == DataType.DTZonedDateTime) DateTimes.of(rs.getTimestamp(pos)) as T
else if (typ == DataType.DTDateTime ) DateTimes.of(rs.getTimestamp(pos)) as T
else if (typ == DataType.DTInstant ) DateTimeUtils.toInstant(rs.getTimestamp(pos)) as T
else null
}
private fun LocalDate.toJava8LocalDate(): java.time.LocalDate {
return java.time.LocalDate.of(this.year, this.month.value, this.dayOfMonth)
}
private fun LocalTime.toJava8LocalTime(): java.time.LocalTime {
return java.time.LocalTime.of(this.hour, this.minute, this.second, this.nano)
}
private fun LocalDateTime.toJava8LocalDateTime(): java.time.LocalDateTime {
return java.time.LocalDateTime.of(this.year, this.month.value, this.dayOfMonth,
this.hour, this.minute, this.second, this.nano)
}
private fun ZonedDateTime.toJava8ZonedDateTime(): java.time.ZonedDateTime {
return java.time.ZonedDateTime.of(this.year, this.month.value, this.dayOfMonth,
this.hour, this.minute, this.second, this.nano, java.time.ZoneId.of(this.zone.id))
}
private fun Instant.toJava8Instant(): java.time.Instant {
return java.time.Instant.ofEpochMilli(this.toEpochMilli())
}
}
|
apache-2.0
|
ac33d913a841a05b9152fa65a67f7e24
| 39.111511 | 196 | 0.572863 | 4.400552 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPreconversionPullUpHelper.kt
|
2
|
7949
|
// 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.pullUp
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.encapsulateFields.*
import com.intellij.refactoring.memberPullUp.JavaPullUpHelper
import com.intellij.refactoring.memberPullUp.PullUpData
import com.intellij.refactoring.memberPullUp.PullUpHelper
import com.intellij.refactoring.util.DocCommentPolicy
import com.intellij.refactoring.util.RefactoringUtil
import com.intellij.refactoring.util.classMembers.MemberInfo
import com.intellij.util.VisibilityUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.j2k.j2kText
import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
class JavaToKotlinPreconversionPullUpHelper(
private val data: PullUpData,
private val dummyTargetClass: PsiClass,
private val javaHelper: JavaPullUpHelper
) : PullUpHelper<MemberInfo> by javaHelper {
private val membersToDummyDeclarations = HashMap<PsiMember, KtElement>()
private val encapsulateFieldsDescriptor = object : EncapsulateFieldsDescriptor {
override fun getSelectedFields(): Array<out FieldDescriptor>? = arrayOf()
override fun isToEncapsulateGet() = true
override fun isToEncapsulateSet() = true
override fun isToUseAccessorsWhenAccessible() = true
override fun getFieldsVisibility() = null
override fun getAccessorsVisibility() = PsiModifier.PUBLIC
override fun getTargetClass() = dummyTargetClass
override fun getJavadocPolicy() = DocCommentPolicy.ASIS
}
private val fieldsToUsages = HashMap<PsiField, List<EncapsulateFieldUsageInfo>>()
private val dummyAccessorByName = HashMap<String, PsiMethod>()
private val jvmStaticAnnotation = KtPsiFactory(data.sourceClass.project).createAnnotationEntry("@kotlin.jvm.JvmStatic")
companion object {
private var PsiMember.originalMember: PsiMember? by CopyablePsiUserDataProperty(Key.create("ORIGINAL_MEMBER"))
}
private fun collectFieldReferencesToEncapsulate(member: PsiField) {
val helper = EncapsulateFieldHelper.getHelper(member.language) ?: return
val fieldName = member.name
val getterName = JvmAbi.getterName(fieldName)
val setterName = JvmAbi.setterName(fieldName)
val getter = helper.generateMethodPrototype(member, getterName, true)
val setter = helper.generateMethodPrototype(member, setterName, false)
val fieldDescriptor = FieldDescriptorImpl(member, getterName, setterName, getter, setter)
getter?.let { dummyAccessorByName[getterName] = dummyTargetClass.add(it) as PsiMethod }
setter?.let { dummyAccessorByName[setterName] = dummyTargetClass.add(it) as PsiMethod }
fieldsToUsages[member] =
ReferencesSearch.search(member).mapNotNull { helper.createUsage(encapsulateFieldsDescriptor, fieldDescriptor, it) }
}
override fun move(info: MemberInfo, substitutor: PsiSubstitutor) {
val member = info.member
val movingSuperInterface = member is PsiClass && info.overrides == false
if (!movingSuperInterface) {
member.originalMember = member
}
if (info.isStatic) {
info.isToAbstract = false
}
if (member is PsiField && !info.isStatic) {
collectFieldReferencesToEncapsulate(member)
}
val superInterfaceCount = getCurrentSuperInterfaceCount()
val adjustedSubstitutor = substitutor.substitutionMap.entries.fold(substitutor) { subst, (typeParameter, type) ->
if (type == null) {
val substitutedUpperBound = substitutor.substitute(PsiIntersectionType.createIntersection(*typeParameter.superTypes))
subst.put(typeParameter, substitutedUpperBound)
} else
subst
}
javaHelper.move(info, adjustedSubstitutor)
if (info.isStatic) {
member.removeOverrideModifier()
}
val targetClass = data.targetClass.unwrapped as KtClass
if (member.hasModifierProperty(PsiModifier.ABSTRACT) && !movingSuperInterface) targetClass.makeAbstract()
val psiFactory = KtPsiFactory(member.project)
if (movingSuperInterface) {
if (getCurrentSuperInterfaceCount() == superInterfaceCount) return
val typeText = RefactoringUtil.findReferenceToClass(dummyTargetClass.implementsList, member as PsiClass)?.j2kText() ?: return
targetClass.addSuperTypeListEntry(psiFactory.createSuperTypeEntry(typeText))
return
}
val memberOwner = when {
member.hasModifierProperty(PsiModifier.STATIC) && member !is PsiClass -> targetClass.getOrCreateCompanionObject()
else -> targetClass
}
val dummyDeclaration: KtNamedDeclaration = when (member) {
is PsiField -> psiFactory.createProperty("val foo = 0")
is PsiMethod -> psiFactory.createFunction("fun foo() = 0")
is PsiClass -> psiFactory.createClass("class Foo")
else -> return
}
// postProcessMember() call order is unstable so in order to stabilize resulting member order we add dummies to target class
// and replace them after postprocessing
membersToDummyDeclarations[member] = addMemberToTarget(dummyDeclaration, memberOwner)
}
private fun getCurrentSuperInterfaceCount() = dummyTargetClass.implementsList?.referenceElements?.size ?: 0
override fun postProcessMember(member: PsiMember) {
javaHelper.postProcessMember(member)
val originalMember = member.originalMember ?: return
originalMember.originalMember = null
val targetClass = data.targetClass.unwrapped as? KtClass ?: return
val convertedDeclaration = member.j2k() ?: return
if (member is PsiField || member is PsiMethod) {
val visibilityModifier = VisibilityUtil.getVisibilityModifier(member.modifierList)
if (visibilityModifier == PsiModifier.PROTECTED || visibilityModifier == PsiModifier.PACKAGE_LOCAL) {
convertedDeclaration.setVisibility(KtTokens.PUBLIC_KEYWORD)
}
}
val newDeclaration = membersToDummyDeclarations[originalMember]?.replace(convertedDeclaration) as KtNamedDeclaration
if (targetClass.isInterface()) {
newDeclaration.removeModifier(KtTokens.ABSTRACT_KEYWORD)
}
if (member.hasModifierProperty(PsiModifier.STATIC) && newDeclaration is KtNamedFunction) {
newDeclaration.addAnnotationWithSpace(jvmStaticAnnotation).addToShorteningWaitSet()
}
if (originalMember is PsiField) {
val usages = fieldsToUsages[originalMember] ?: return
for (usage in usages) {
val fieldDescriptor = usage.fieldDescriptor
val targetLightClass = (usage.reference?.resolve() as? PsiField)?.containingClass ?: return
val getter = targetLightClass.findMethodBySignature(fieldDescriptor.getterPrototype, false)
val setter = targetLightClass.findMethodBySignature(fieldDescriptor.setterPrototype, false)
EncapsulateFieldHelper.getHelper(usage.element!!.language)?.processUsage(usage, encapsulateFieldsDescriptor, setter, getter)
}
}
}
}
|
apache-2.0
|
675209351b754d7046f74c9f6093a4ac
| 47.47561 | 158 | 0.722732 | 5.309953 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/slicer/AbstractSlicerNullnessGroupingTest.kt
|
2
|
1188
|
// 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.slicer
import com.intellij.slicer.SliceRootNode
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
abstract class AbstractSlicerNullnessGroupingTest : AbstractSlicerTest() {
override fun doTest(path: String, sliceProvider: KotlinSliceProvider, rootNode: SliceRootNode) {
val treeStructure = TestSliceTreeStructure(rootNode)
val analyzer = sliceProvider.nullnessAnalyzer
val nullnessByNode = HackedSliceNullnessAnalyzerBase.createMap()
val nullness = analyzer.calcNullableLeaves(rootNode, treeStructure, nullnessByNode)
val newRootNode = analyzer.createNewTree(nullness, rootNode, nullnessByNode)
val renderedForest = buildString {
for (groupRootNode in newRootNode.children) {
append(buildTreeRepresentation(groupRootNode))
append("\n")
}
}
KotlinTestUtils.assertEqualsToFile(File(path.replace(".kt", ".nullnessGroups.txt")), renderedForest)
}
}
|
apache-2.0
|
ecadc0590ac486f9b5f3cd5a6b5a7740
| 48.5 | 158 | 0.734848 | 4.622568 | false | true | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantNullableReturnTypeInspection.kt
|
1
|
6885
|
// 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.isOverridable
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.isEffectivelyActual
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.jvm.annotations.TRANSIENT_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
class RedundantNullableReturnTypeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitProperty(property: KtProperty) {
if (property.isVar) return
check(property)
}
private fun check(declaration: KtCallableDeclaration) {
val typeReference = declaration.typeReference ?: return
val typeElement = typeReference.typeElement as? KtNullableType ?: return
if (typeElement.innerType == null) return
val questionMark = typeElement.questionMarkNode as? LeafPsiElement ?: return
if (declaration.isOverridable() || declaration.isExpectDeclaration() || declaration.isEffectivelyActual()) return
val (body, targetDeclaration) = when (declaration) {
is KtNamedFunction -> {
val body = declaration.bodyExpression
if (body != null) body to declaration else null
}
is KtProperty -> {
val initializer = declaration.initializer
val getter = declaration.accessors.singleOrNull { it.isGetter }
val getterBody = getter?.bodyExpression
when {
initializer != null -> initializer to declaration
getterBody != null -> getterBody to getter
else -> null
}
}
else -> null
} ?: return
val context = body.analyze()
val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, targetDeclaration] ?: return
if (declarationDescriptor.hasJvmTransientAnnotation()) return
val actualReturnTypes = body.actualReturnTypes(context, declarationDescriptor)
if (actualReturnTypes.isEmpty() || actualReturnTypes.any { it.isNullable() }) return
val declarationName = declaration.nameAsSafeName.asString()
val description = if (declaration is KtProperty) {
KotlinBundle.message("0.is.always.non.null.type", declarationName)
} else {
KotlinBundle.message("0.always.returns.non.null.type", declarationName)
}
holder.registerProblem(
typeReference,
questionMark.textRangeIn(typeReference),
description,
MakeNotNullableFix()
)
}
}
private fun DeclarationDescriptor.hasJvmTransientAnnotation() =
(this as? PropertyDescriptor)?.backingField?.annotations?.findAnnotation(TRANSIENT_ANNOTATION_FQ_NAME) != null
@OptIn(FrontendInternals::class)
private fun KtExpression.actualReturnTypes(context: BindingContext, declarationDescriptor: DeclarationDescriptor): List<KotlinType> {
val dataFlowValueFactory = getResolutionFacade().frontendService<DataFlowValueFactory>()
val moduleDescriptor = findModuleDescriptor()
val languageVersionSettings = languageVersionSettings
val returnTypes = collectDescendantsOfType<KtReturnExpression> {
it.getTargetFunctionDescriptor(context) == declarationDescriptor
}.flatMap {
it.returnedExpression.types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings)
}
return if (this is KtBlockExpression) {
returnTypes
} else {
returnTypes + types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings)
}
}
private fun KtExpression?.types(
context: BindingContext,
dataFlowValueFactory: DataFlowValueFactory,
moduleDescriptor: ModuleDescriptor,
languageVersionSettings: LanguageVersionSettings
): List<KotlinType> {
if (this == null) return emptyList()
val type = context.getType(this) ?: return emptyList()
val dataFlowInfo = context[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return emptyList()
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, moduleDescriptor)
val stableTypes = dataFlowInfo.getStableTypes(dataFlowValue, languageVersionSettings)
return if (stableTypes.isNotEmpty()) stableTypes.toList() else listOf(type)
}
private class MakeNotNullableFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("make.not.nullable")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val typeReference = descriptor.psiElement as? KtTypeReference ?: return
val typeElement = typeReference.typeElement as? KtNullableType ?: return
val innerType = typeElement.innerType ?: return
typeElement.replace(innerType)
}
}
}
|
apache-2.0
|
39b1039ffa4460eca8caafb83f5b4651
| 48.532374 | 158 | 0.706899 | 5.742285 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/stories/settings/select/BaseStoryRecipientSelectionViewModel.kt
|
1
|
2855
|
package org.thoughtcrime.securesms.stories.settings.select
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.kotlin.subscribeBy
import io.reactivex.rxjava3.subjects.PublishSubject
import org.thoughtcrime.securesms.database.model.DistributionListId
import org.thoughtcrime.securesms.database.model.DistributionListPrivacyMode
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.livedata.Store
class BaseStoryRecipientSelectionViewModel(
private val distributionListId: DistributionListId?,
private val repository: BaseStoryRecipientSelectionRepository
) : ViewModel() {
private val store = Store(BaseStoryRecipientSelectionState(distributionListId))
private val subject = PublishSubject.create<Action>()
private val disposable = CompositeDisposable()
var actionObservable: Observable<Action> = subject
var state: LiveData<BaseStoryRecipientSelectionState> = store.stateLiveData
init {
if (distributionListId != null) {
disposable += repository.getRecord(distributionListId)
.subscribe { record ->
val startingSelection = if (record.privacyMode == DistributionListPrivacyMode.ALL_EXCEPT) record.rawMembers else record.members
store.update { it.copy(privateStory = record, selection = it.selection + startingSelection) }
}
}
}
override fun onCleared() {
disposable.clear()
}
fun toggleSelectAll() {
disposable += repository.getAllSignalContacts().subscribeBy { allSignalRecipients ->
store.update { it.copy(selection = allSignalRecipients) }
}
}
fun addRecipient(recipientId: RecipientId) {
store.update { it.copy(selection = it.selection + recipientId) }
}
fun removeRecipient(recipientId: RecipientId) {
store.update { it.copy(selection = it.selection - recipientId) }
}
fun onAction() {
if (distributionListId != null) {
repository.updateDistributionListMembership(store.state.privateStory!!, store.state.selection)
subject.onNext(Action.ExitFlow)
} else {
subject.onNext(Action.GoToNextScreen(store.state.selection))
}
}
sealed class Action {
data class GoToNextScreen(val recipients: Set<RecipientId>) : Action()
object ExitFlow : Action()
}
class Factory(
private val distributionListId: DistributionListId?,
private val repository: BaseStoryRecipientSelectionRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(BaseStoryRecipientSelectionViewModel(distributionListId, repository)) as T
}
}
}
|
gpl-3.0
|
1897d1eb5a58c88ed36336d460fcc3f0
| 36.077922 | 137 | 0.767426 | 4.70346 | false | false | false | false |
brianwernick/ExoMedia
|
library/src/main/kotlin/com/devbrackets/android/exomedia/ui/animation/BottomViewHideShowAnimation.kt
|
1
|
2432
|
package com.devbrackets.android.exomedia.ui.animation
import android.content.Context
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.TranslateAnimation
/**
* An animation used to slide [com.devbrackets.android.exomedia.ui.widget.DefaultVideoControls]
* in and out from the bottom of the screen when changing visibilities.
*/
class BottomViewHideShowAnimation(private val animationView: View, private val toVisible: Boolean, duration: Long) : AnimationSet(false) {
init {
//Creates the Alpha animation for the transition
val startAlpha = (if (toVisible) 0 else 1).toFloat()
val endAlpha = (if (toVisible) 1 else 0).toFloat()
val alphaAnimation = AlphaAnimation(startAlpha, endAlpha)
alphaAnimation.duration = duration
//Creates the Translate animation for the transition
val startY = if (toVisible) getHideShowDelta(animationView) else 0
val endY = if (toVisible) 0 else getHideShowDelta(animationView)
val translateAnimation = TranslateAnimation(0f, 0f, startY.toFloat(), endY.toFloat())
translateAnimation.interpolator = if (toVisible) LinearOutSlowInInterpolator() else FastOutLinearInInterpolator()
translateAnimation.duration = duration
//Adds the animations to the set
addAnimation(alphaAnimation)
addAnimation(translateAnimation)
setAnimationListener(Listener())
}
private fun getHideShowDelta(view: View): Int {
val displayMetrics = DisplayMetrics()
val display = (view.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
display.getMetrics(displayMetrics)
val screenHeight = displayMetrics.heightPixels
return screenHeight - view.top
}
private inner class Listener : AnimationListener {
override fun onAnimationStart(animation: Animation) {
animationView.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animation) {
animationView.visibility = if (toVisible) View.VISIBLE else View.GONE
}
override fun onAnimationRepeat(animation: Animation) {
//Purposefully left blank
}
}
}
|
apache-2.0
|
06bbcba850856f17642670f881a1794c
| 35.298507 | 138 | 0.775905 | 4.75 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/search/EmojiSearchFragment.kt
|
2
|
3567
|
package org.thoughtcrime.securesms.keyboard.emoji.search
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.KeyboardAwareLinearLayout
import org.thoughtcrime.securesms.components.emoji.EmojiEventListener
import org.thoughtcrime.securesms.components.emoji.EmojiPageView
import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter
import org.thoughtcrime.securesms.keyboard.emoji.KeyboardPageSearchView
import org.thoughtcrime.securesms.util.ThemedFragment.themedInflate
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.fragments.requireListener
class EmojiSearchFragment : Fragment(), EmojiPageViewGridAdapter.VariationSelectorListener {
private lateinit var viewModel: EmojiSearchViewModel
private lateinit var callback: Callback
override fun onAttach(context: Context) {
super.onAttach(context)
callback = requireListener()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return themedInflate(R.layout.emoji_search_fragment, inflater, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val repository = EmojiSearchRepository(requireContext())
val factory = EmojiSearchViewModel.Factory(repository)
viewModel = ViewModelProvider(this, factory)[EmojiSearchViewModel::class.java]
val keyboardAwareLinearLayout: KeyboardAwareLinearLayout = view.findViewById(R.id.kb_aware_layout)
val eventListener: EmojiEventListener = requireListener()
val searchBar: KeyboardPageSearchView = view.findViewById(R.id.emoji_search_view)
val resultsContainer: FrameLayout = view.findViewById(R.id.emoji_search_results_container)
val noResults: TextView = view.findViewById(R.id.emoji_search_empty)
val emojiPageView = EmojiPageView(
requireContext(),
eventListener,
this,
true,
LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false),
R.layout.emoji_display_item_list,
R.layout.emoji_text_display_item_list
)
resultsContainer.addView(emojiPageView)
searchBar.presentForEmojiSearch()
searchBar.callbacks = SearchCallbacks()
viewModel.emojiList.observe(viewLifecycleOwner) { results ->
emojiPageView.setList(results.emojiList, null)
if (results.emojiList.isNotEmpty() || results.isRecents) {
emojiPageView.visibility = View.VISIBLE
noResults.visibility = View.GONE
} else {
emojiPageView.visibility = View.INVISIBLE
noResults.visibility = View.VISIBLE
}
}
view.post {
keyboardAwareLinearLayout.addOnKeyboardHiddenListener {
callback.closeEmojiSearch()
}
}
}
private inner class SearchCallbacks : KeyboardPageSearchView.Callbacks {
override fun onNavigationClicked() {
ViewUtil.hideKeyboard(requireContext(), requireView())
}
override fun onQueryChanged(query: String) {
viewModel.onQueryChanged(query)
}
}
interface Callback {
fun closeEmojiSearch()
}
override fun onVariationSelectorStateChanged(open: Boolean) = Unit
}
|
gpl-3.0
|
3e6447eb3f547c7c10c19d15d9a5faa2
| 35.030303 | 114 | 0.779086 | 4.886301 | false | false | false | false |
google-developer-training/android-basics-kotlin-lunch-tray-app
|
app/src/main/java/com/example/lunchtray/ui/order/SideMenuFragment.kt
|
1
|
3051
|
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lunchtray.ui.order
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.lunchtray.databinding.FragmentSideMenuBinding
import com.example.lunchtray.model.OrderViewModel
/**
* [SideMenuFragment] allows people to add a side to the order or cancel the order.
*/
class SideMenuFragment : Fragment() {
// Binding object instance corresponding to the fragment_start_order.xml layout
// This property is non-null between the onCreateView() and onDestroyView() lifecycle callbacks,
// when the view hierarchy is attached to the fragment.
private var _binding: FragmentSideMenuBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
// Use the 'by activityViewModels()' Kotlin property delegate from the fragment-ktx artifact
private val sharedViewModel: OrderViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSideMenuBinding.inflate(inflater, container, false)
val root = binding.root
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
lifecycleOwner = viewLifecycleOwner
viewModel = sharedViewModel
// TODO: initialize the SideMenuFragment variables
}
}
/**
* Navigate to the accompaniments menu fragment
*/
fun goToNextScreen() {
// TODO: Navigate to the AccompanimentMenuFragment
}
/**
* Cancel the order and start over.
*/
fun cancelOrder() {
// TODO: Reset order in view model
// TODO: Navigate back to the [StartFragment] to start over
}
/**
* This fragment lifecycle method is called when the view hierarchy associated with the fragment
* is being removed. As a result, clear out the binding object.
*/
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
apache-2.0
|
a8ccc9cff8037172fbe650a04c6a9188
| 34.068966 | 100 | 0.706326 | 4.850556 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/processings/ConvertToDataClassProcessing.kt
|
1
|
7878
|
// 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.nj2k.postProcessing.processings
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.intentions.addUseSiteTarget
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.escaped
import org.jetbrains.kotlin.nj2k.postProcessing.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.asAssignment
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierTypeOrDefault
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ConvertToDataClassProcessing : ElementsBasedPostProcessing() {
private fun KtCallableDeclaration.rename(newName: String) {
val factory = KtPsiFactory(this)
val escapedName = newName.escaped()
ReferencesSearch.search(this, LocalSearchScope(containingKtFile)).forEach {
it.element.replace(factory.createExpression(escapedName))
}
setName(escapedName)
}
private fun collectInitializations(klass: KtClass): List<Initialization<*>> {
val parametersUsed = mutableSetOf<KtParameter>()
val propertyUsed = mutableSetOf<KtProperty>()
@Suppress("UNCHECKED_CAST") return klass.getAnonymousInitializers()
.singleOrNull()
?.body?.safeAs<KtBlockExpression>()
?.statements
?.asSequence()
?.map { statement ->
val assignment = statement.asAssignment() ?: return@map null
val property = assignment.left
?.unpackedReferenceToProperty()
?.takeIf { property ->
property.containingClass() == klass
&& property.initializer == null
&& property !in propertyUsed
}
?: return@map null
propertyUsed += property
when (val rightSide = assignment.right) {
is KtReferenceExpression -> {
val parameter = rightSide
.resolve()
?.safeAs<KtParameter>()
?.takeIf { parameter ->
parameter.containingClass() == klass
&& !parameter.hasValOrVar()
&& parameter !in parametersUsed
} ?: return@map null
val propertyType = property.type() ?: return@map null
val parameterType = parameter.type() ?: return@map null
if (!KotlinTypeChecker.DEFAULT.equalTypes(propertyType, parameterType)) return@map null
parametersUsed += parameter
ConstructorParameterInitialization(property, parameter, assignment)
}
is KtConstantExpression, is KtStringTemplateExpression -> {
LiteralInitialization(property, rightSide, assignment)
}
else -> null
}
}?.takeWhile { it != null }
.orEmpty()
.toList() as List<Initialization<*>>
}
override fun runProcessing(elements: List<PsiElement>, converterContext: NewJ2kConverterContext) {
for (klass in elements.descendantsOfType<KtClass>()) {
convertClass(klass)
}
}
private fun ConstructorParameterInitialization.mergePropertyAndConstructorParameter() {
val (property, constructorParameter, _) = this
val factory = KtPsiFactory(property)
constructorParameter.addBefore(property.valOrVarKeyword, constructorParameter.nameIdentifier!!)
constructorParameter.addAfter(factory.createWhiteSpace(), constructorParameter.valOrVarKeyword!!)
constructorParameter.rename(property.name!!)
val propertyCommentSaver = CommentSaver(property, saveLineBreaks = true)
constructorParameter.setVisibility(property.visibilityModifierTypeOrDefault())
for (annotationEntry in constructorParameter.annotationEntries) {
if (annotationEntry.useSiteTarget == null) {
annotationEntry.addUseSiteTarget(AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER, property.project)
}
}
for (annotationEntry in property.annotationEntries) {
constructorParameter.addAnnotationEntry(annotationEntry).also { entry ->
if (entry.useSiteTarget == null) {
entry.addUseSiteTarget(AnnotationUseSiteTarget.FIELD, property.project)
}
}
}
val typeReference = property.typeReference
if (typeReference != null) {
for (annotationEntry in typeReference.annotationEntries) {
constructorParameter.typeReference?.addAnnotationEntry(annotationEntry)
}
}
property.delete()
propertyCommentSaver.restore(constructorParameter, forceAdjustIndent = false)
}
private fun KtClass.removeEmptyInitBlocks() {
for (initBlock in getAnonymousInitializers()) {
if ((initBlock.body as KtBlockExpression).statements.isEmpty()) {
val commentSaver = CommentSaver(initBlock)
initBlock.delete()
primaryConstructor?.let { commentSaver.restore(it) }
}
}
}
private fun convertClass(klass: KtClass) {
val initialisations = runReadAction { collectInitializations(klass) }
if (initialisations.isEmpty()) return
runUndoTransparentActionInEdt(inWriteAction = true) {
for (initialization in initialisations) {
val statementCommentSaver = CommentSaver(initialization.statement, saveLineBreaks = true)
val restoreStatementCommentsTarget: KtExpression
when (initialization) {
is ConstructorParameterInitialization -> {
initialization.mergePropertyAndConstructorParameter()
restoreStatementCommentsTarget = initialization.initializer
}
is LiteralInitialization -> {
val (property, initializer, _) = initialization
property.initializer = initializer
restoreStatementCommentsTarget = property
}
}
initialization.statement.delete()
statementCommentSaver.restore(restoreStatementCommentsTarget, forceAdjustIndent = false)
}
klass.removeEmptyInitBlocks()
}
}
}
private sealed class Initialization<I : KtElement> {
abstract val property: KtProperty
abstract val initializer: I
abstract val statement: KtBinaryExpression
}
private data class ConstructorParameterInitialization(
override val property: KtProperty,
override val initializer: KtParameter,
override val statement: KtBinaryExpression
) : Initialization<KtParameter>()
private data class LiteralInitialization(
override val property: KtProperty,
override val initializer: KtExpression,
override val statement: KtBinaryExpression
) : Initialization<KtExpression>()
|
apache-2.0
|
d112dcb121435ae189f668598d9397c6
| 44.802326 | 120 | 0.637725 | 6.145086 | false | false | false | false |
stefanmedack/cccTV
|
app/src/main/java/de/stefanmedack/ccctv/ui/cards/StreamCardPresenter.kt
|
1
|
2622
|
package de.stefanmedack.ccctv.ui.cards
import android.support.v17.leanback.widget.ImageCardView
import android.support.v17.leanback.widget.Presenter
import android.support.v4.content.ContextCompat
import android.support.v7.view.ContextThemeWrapper
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import de.stefanmedack.ccctv.R
import info.metadude.java.library.brockman.models.Stream
import kotlin.properties.Delegates
class StreamCardPresenter(val thumbPictureUrl: String) : Presenter() {
private var selectedBackgroundColor: Int by Delegates.notNull()
private var defaultBackgroundColor: Int by Delegates.notNull()
override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder {
defaultBackgroundColor = ContextCompat.getColor(parent.context, R.color.teal_900)
selectedBackgroundColor = ContextCompat.getColor(parent.context, R.color.amber_800)
val cardView = object : ImageCardView(ContextThemeWrapper(parent.context, R.style.EventCardStyle)) {
override fun setSelected(selected: Boolean) {
updateCardBackgroundColor(this, selected)
super.setSelected(selected)
}
}
cardView.isFocusable = true
cardView.isFocusableInTouchMode = true
updateCardBackgroundColor(cardView, false)
return Presenter.ViewHolder(cardView)
}
override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) {
if (item is Stream) {
(viewHolder.view as ImageCardView).let {
it.titleText = item.display
it.contentText = item.slug
Glide.with(viewHolder.view)
.load(thumbPictureUrl)
.apply(RequestOptions()
.error(R.drawable.voctocat)
.centerCrop()
)
.into(it.mainImageView)
}
}
}
override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) {
(viewHolder.view as ImageCardView).let {
it.badgeImage = null
it.mainImage = null
}
}
private fun updateCardBackgroundColor(view: ImageCardView, selected: Boolean) {
val color = if (selected) selectedBackgroundColor else defaultBackgroundColor
// both background colors should be set because the view's background is temporarily visible during animations.
view.setBackgroundColor(color)
view.setInfoAreaBackgroundColor(color)
}
}
|
apache-2.0
|
8ea6881441d57698a4a9e696365d9377
| 39.353846 | 119 | 0.673532 | 5.161417 | false | false | false | false |
SDS-Studios/ScoreKeeper
|
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Activity/NewGameActivity.kt
|
1
|
2973
|
package io.github.sdsstudios.ScoreKeeper.Activity
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.design.widget.TabLayout
import io.github.sdsstudios.ScoreKeeper.Adapters.SelectPlayersAdapter
import io.github.sdsstudios.ScoreKeeper.Fragment.CreatePlayerFragment
import io.github.sdsstudios.ScoreKeeper.Fragment.NewGameOptionFragment
import io.github.sdsstudios.ScoreKeeper.Fragment.OptionFragment
import io.github.sdsstudios.ScoreKeeper.Fragment.SelectPlayersFragment
import io.github.sdsstudios.ScoreKeeper.R
import io.github.sdsstudios.ScoreKeeper.ViewModels.MutableGameViewModel
import kotlinx.android.synthetic.main.activity_tabs_with_fab.*
import kotlinx.android.synthetic.main.app_bar_tabs.*
/**
* Created by sethsch1 on 04/11/17.
*/
class NewGameActivity : OptionActivity(toolbarTitle = R.string.title_new_game) {
companion object {
const val PLAYER_LIST_TAB = 0
const val OPTION_TAB = 1
}
private lateinit var mGameViewModel: MutableGameViewModel
private val mSelectedPlayerIds
get() = (fragments[PLAYER_LIST_TAB].adapter as SelectPlayersAdapter).selectedPlayerIds
override val optionFragment
get() = fragments[OPTION_TAB] as OptionFragment<*, *, *>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mGameViewModel = ViewModelProviders.of(this).get(MutableGameViewModel::class.java)
fab.setOnClickListener {
when (tabLayout.selectedTabPosition) {
PLAYER_LIST_TAB -> CreatePlayerFragment.showDialog(supportFragmentManager)
OPTION_TAB ->
if (!anyErrorsInOptions()) {
if (!sharedPreferences.getBoolean(KEY_PROMPT_FOR_REVIEW, false)) {
sharedPreferences.edit()
.putBoolean(KEY_PROMPT_FOR_REVIEW, true)
.apply()
}
startGame()
}
}
}
}
override fun onTabSelected(tab: TabLayout.Tab?) {
when (tab!!.position) {
PLAYER_LIST_TAB ->
fab.setImageDrawable(resources.getDrawable(R.drawable.ic_add_white_24dp))
OPTION_TAB ->
fab.setImageDrawable(resources.getDrawable(R.drawable.ic_check_white_24dp))
}
super.onTabSelected(tab)
}
override fun createFragments() = mutableListOf(
SelectPlayersFragment(),
NewGameOptionFragment()
)
override fun createTabTitles(): MutableList<String> = mutableListOf(
getString(R.string.title_players),
getString(R.string.title_options)
)
private fun startGame() {
mGameViewModel.saveToDb()
mGameViewModel.createSets(mSelectedPlayerIds)
openGameActivity(mGameViewModel.game.id)
finish()
}
}
|
gpl-3.0
|
714e83da1537fb35ed63324e3666e8f3
| 33.183908 | 94 | 0.661285 | 4.857843 | false | false | false | false |
deviant-studio/bindingtools
|
lib/src/main/java/ds/bindingtools/ArgsBindings.kt
|
1
|
5146
|
package ds.bindingtools
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import java.io.Serializable
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
/**
* Nullable version
*/
inline fun <reified T : Any?> Activity.arg(): ReadOnlyProperty<Activity, T?> = ActivityArgsDelegate(null, T::class)
inline fun <reified T : Any?> Activity.arg(default: T): ReadOnlyProperty<Activity, T> = ActivityArgsDelegate(default, T::class)
/**
* Nullable version
*/
inline fun <reified T : Any?> Fragment.arg(): ReadOnlyProperty<Fragment, T?> = FragmentArgsDelegate(null, T::class)
inline fun <reified T : Any?> Fragment.arg(default: T): ReadOnlyProperty<Fragment, T> = FragmentArgsDelegate(default, T::class)
inline fun <reified T : Activity> Context.startActivity(b: Bundle? = null, flags: Int = 0) {
val i = Intent(this, T::class.java).addFlags(flags)
if (b != null)
i.putExtras(b)
startActivity(i)
}
inline fun <reified T : Activity> Activity.startActivityForResult(b: Bundle? = null, requestCode: Int, flags: Int = 0) {
val i = Intent(this, T::class.java).addFlags(flags)
if (b != null)
i.putExtras(b)
startActivityForResult(i, requestCode)
}
inline fun <reified T : Activity> Context.startActivity(flags: Int = 0, noinline f: BundleBuilder.() -> Unit) {
val b = bundle(f)
startActivity<T>(b, flags)
}
inline fun <reified T : Activity> Activity.startActivityForResult(requestCode: Int, flags: Int = 0, noinline f: BundleBuilder.() -> Unit) {
val b = bundle(f)
startActivityForResult<T>(b, requestCode, flags)
}
inline fun <reified T : Fragment> FragmentActivity.replaceFragment(@IdRes layoutId: Int, args: Bundle? = null) {
val fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, T::class.java.name)
fragment.arguments = args
//val fragment = Fragment.instantiate(this, T::class.java.name, args)
supportFragmentManager
.beginTransaction()
.replace(layoutId, fragment)
.commitNow()
}
inline fun <reified T : Fragment> FragmentActivity.replaceFragment(@IdRes layoutId: Int, f: BundleBuilder.(T) -> Unit) {
val fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, T::class.java.name) as T
//val fragment = Fragment.instantiate(this, T::class.java.name) as T
val builder = BundleBuilder()
f(builder, fragment)
fragment.arguments = builder.build()
supportFragmentManager
.beginTransaction()
.replace(layoutId, fragment)
.commitNow()
}
@Suppress("unchecked_cast")
class ActivityArgsDelegate<out T : Any?>(private val default: T, private val cls: KClass<*>) : ReadOnlyProperty<Activity, T> {
override fun getValue(thisRef: Activity, property: KProperty<*>): T = thisRef
.intent
?.extras
?.let { extras -> parseExtras(property.name, extras, cls, default) }
?: default
}
class FragmentArgsDelegate<out T : Any?>(private val default: T, private val cls: KClass<*>) : ReadOnlyProperty<Fragment, T> {
override fun getValue(thisRef: Fragment, property: KProperty<*>): T = thisRef
.arguments
?.let { args -> parseExtras(property.name, args, cls, default) }
?: default
}
@Suppress("unchecked_cast")
private fun <T : Any?> parseExtras(key: String, extras: Bundle, cls: KClass<*>, default: T): T = with(extras) {
when (cls) {
String::class -> getString(key, default as String?) as T
java.lang.Integer::class -> (if (default == null) getInt(key) else getInt(key, default as Int)) as T
java.lang.Boolean::class -> (if (default == null) getBoolean(key) else getBoolean(key, default as Boolean)) as T
java.lang.Float::class -> (if (default == null) getFloat(key) else getFloat(key, default as Float)) as T
java.lang.Long::class -> (if (default == null) getLong(key) else getLong(key, default as Long)) as T
java.lang.Double::class -> (if (default == null) getDouble(key) else getDouble(key, default as Double)) as T
CharSequence::class -> (if (default == null) getCharSequence(key) else getCharSequence(key, default as CharSequence)) as T
Char::class -> (if (default == null) getChar(key) else getChar(key, default as Char)) as T
IntArray::class -> getIntArray(key) as T
BooleanArray::class -> getBooleanArray(key) as T
FloatArray::class -> getFloatArray(key) as T
LongArray::class -> getLongArray(key) as T
DoubleArray::class -> getDoubleArray(key) as T
Parcelable::class -> getParcelable<Parcelable>(key) as T
Serializable::class -> getSerializable(key) as T
ArrayList::class -> getStringArrayList(key) as T
Array<String>::class -> getStringArray(key) as T
else -> error("Class ${cls.javaObjectType.simpleName} doesn't supported")
}
}
|
apache-2.0
|
71896d3b693215af89788e8a9d2e4a2f
| 42.243697 | 139 | 0.684998 | 4.064771 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/OverridesCompletion.kt
|
1
|
9597
|
// 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.completion
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.icons.AllIcons
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.ui.RowIcon
import org.jetbrains.kotlin.backend.common.descriptors.isSuspend
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.completion.handlers.indexOfSkippingSpace
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.core.moveCaretIntoGeneratedElement
import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMembersHandler
import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class OverridesCompletion(
private val collector: LookupElementsCollector,
private val lookupElementFactory: BasicLookupElementFactory
) {
private val PRESENTATION_RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
modifiers = emptySet()
includeAdditionalModifiers = false
}
fun complete(position: PsiElement, declaration: KtCallableDeclaration?) {
val isConstructorParameter = position.getNonStrictParentOfType<KtPrimaryConstructor>() != null
val classOrObject = position.getNonStrictParentOfType<KtClassOrObject>() ?: return
val members = OverrideMembersHandler(isConstructorParameter).collectMembersToGenerate(classOrObject)
for (memberObject in members) {
val descriptor = memberObject.descriptor
if (declaration != null && !canOverride(descriptor, declaration)) continue
if (isConstructorParameter && descriptor !is PropertyDescriptor) continue
var lookupElement = lookupElementFactory.createLookupElement(descriptor)
var text = "override " + PRESENTATION_RENDERER.render(descriptor)
if (descriptor is FunctionDescriptor) {
text += " {...}"
}
val baseClass = descriptor.containingDeclaration as ClassDescriptor
val baseClassName = baseClass.name.asString()
val baseIcon = (lookupElement.`object` as DeclarationLookupObject).getIcon(0)
val isImplement = descriptor.modality == Modality.ABSTRACT
val additionalIcon = if (isImplement)
AllIcons.Gutter.ImplementingMethod
else
AllIcons.Gutter.OverridingMethod
val icon = RowIcon(baseIcon, additionalIcon)
val baseClassDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(position.project, baseClass)
val baseClassIcon = KotlinDescriptorIconProvider.getIcon(baseClass, baseClassDeclaration, 0)
lookupElement = object : LookupElementDecorator<LookupElement>(lookupElement) {
override fun getLookupString() =
if (declaration == null) "override" else delegate.lookupString // don't use "override" as lookup string when already in the name of declaration
override fun getAllLookupStrings() = setOf(lookupString, delegate.lookupString)
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.itemText = text
presentation.isItemTextBold = isImplement
presentation.icon = icon
presentation.clearTail()
presentation.setTypeText(baseClassName, baseClassIcon)
}
override fun getDelegateInsertHandler(): InsertHandler<LookupElement> = InsertHandler { context, _ ->
val dummyMemberHead = when {
declaration != null -> ""
isConstructorParameter -> "override val "
else -> "override fun "
}
val dummyMemberTail = when {
isConstructorParameter || declaration is KtProperty -> "dummy: Dummy ,@"
else -> "dummy() {}"
}
val dummyMemberText = dummyMemberHead + dummyMemberTail
val override = KtTokens.OVERRIDE_KEYWORD.value
tailrec fun calcStartOffset(startOffset: Int, diff: Int = 0): Int {
return when {
context.document.text[startOffset - 1].isWhitespace() -> calcStartOffset(startOffset - 1, diff + 1)
context.document.text.substring(startOffset - override.length, startOffset) == override -> {
startOffset - override.length
}
else -> diff + startOffset
}
}
val startOffset = calcStartOffset(context.startOffset)
val tailOffset = context.tailOffset
context.document.replaceString(startOffset, tailOffset, dummyMemberText)
val psiDocumentManager = PsiDocumentManager.getInstance(context.project)
psiDocumentManager.commitDocument(context.document)
val dummyMember = context.file.findElementAt(startOffset)!!.getStrictParentOfType<KtNamedDeclaration>()!!
// keep original modifiers
val psiFactory = KtPsiFactory(context.project)
val modifierList = psiFactory.createModifierList(dummyMember.modifierList!!.text)
fun isCommentOrWhiteSpace(e: PsiElement) = e is PsiComment || e is PsiWhiteSpace
fun createCommentOrWhiteSpace(e: PsiElement) =
if (e is PsiComment) psiFactory.createComment(e.text) else psiFactory.createWhiteSpace(e.text)
val dummyMemberChildren = dummyMember.allChildren
val headComments = dummyMemberChildren.takeWhile(::isCommentOrWhiteSpace).map(::createCommentOrWhiteSpace).toList()
val tailComments =
dummyMemberChildren.toList().takeLastWhile(::isCommentOrWhiteSpace).map(::createCommentOrWhiteSpace)
val prototype = memberObject.generateMember(classOrObject, false)
prototype.modifierList!!.replace(modifierList)
val insertedMember = dummyMember.replaced(prototype)
if (memberObject.descriptor.isSuspend) insertedMember.addModifier(KtTokens.SUSPEND_KEYWORD)
val insertedMemberParent = insertedMember.parent
headComments.forEach { insertedMemberParent.addBefore(it, insertedMember) }
tailComments.reversed().forEach { insertedMemberParent.addAfter(it, insertedMember) }
ShortenReferences.DEFAULT.process(insertedMember)
if (isConstructorParameter) {
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
val offset = insertedMember.endOffset
val chars = context.document.charsSequence
val commaOffset = chars.indexOfSkippingSpace(',', offset)!!
val atCharOffset = chars.indexOfSkippingSpace('@', commaOffset + 1)!!
context.document.deleteString(offset, atCharOffset + 1)
context.editor.moveCaret(offset)
} else {
moveCaretIntoGeneratedElement(context.editor, insertedMember)
}
}
}
lookupElement.assignPriority(if (isImplement) ItemPriority.IMPLEMENT else ItemPriority.OVERRIDE)
collector.addElement(lookupElement)
}
}
private fun canOverride(descriptorToOverride: CallableMemberDescriptor, declaration: KtCallableDeclaration): Boolean {
when (declaration) {
is KtFunction -> return descriptorToOverride is FunctionDescriptor
is KtValVarKeywordOwner -> {
if (descriptorToOverride !is PropertyDescriptor) return false
return if (declaration.valOrVarKeyword?.node?.elementType == KtTokens.VAL_KEYWORD) {
!descriptorToOverride.isVar
} else {
true // var can override either var or val
}
}
else -> return false
}
}
}
|
apache-2.0
|
382c9003ef8ac4a70daa615d3acb6ad2
| 50.326203 | 163 | 0.657185 | 5.994379 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/stats-collector/src/com/intellij/stats/completion/tracker/CompletionActionsTracker.kt
|
12
|
4952
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.completion.tracker
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.completion.ml.experiment.ExperimentInfo
import com.intellij.completion.ml.storage.LookupStorage
import com.intellij.completion.ml.util.prefix
class CompletionActionsTracker(private val lookup: LookupImpl,
private val lookupStorage: LookupStorage,
private val logger: CompletionLogger,
private val experimentInfo: ExperimentInfo)
: CompletionActionsListener {
private var completionStarted = false
private var selectedByDotTyping = false
private var prefixLength = 0
private val deferredLog = DeferredLog()
private fun isCompletionActive(): Boolean {
return completionStarted && !lookup.isLookupDisposed
|| ApplicationManager.getApplication().isUnitTestMode
}
override fun lookupCanceled(event: LookupEvent) {
if (!completionStarted) return
val timestamp = System.currentTimeMillis()
deferredLog.log()
val currentItem = lookup.currentItem
val performance = lookupStorage.performanceTracker.measurements()
if (isSelectedByTyping(currentItem) || selectedByDotTyping) {
logger.itemSelectedByTyping(lookup, performance, timestamp)
}
else {
logger.completionCancelled(event.isCanceledExplicitly, performance, timestamp)
}
}
override fun currentItemChanged(event: LookupEvent) {
if (completionStarted) {
return
}
val timestamp = System.currentTimeMillis()
completionStarted = true
prefixLength = lookup.prefix().length
deferredLog.defer {
logger.completionStarted(lookup, prefixLength, experimentInfo.inExperiment, experimentInfo.version, timestamp)
}
}
override fun itemSelected(event: LookupEvent) {
if (!completionStarted) return
val timestamp = System.currentTimeMillis()
deferredLog.log()
val performance = lookupStorage.performanceTracker.measurements()
if (isSelectedByTyping(lookup.currentItem)) {
logger.itemSelectedByTyping(lookup, performance, timestamp)
}
else {
logger.itemSelectedCompletionFinished(lookup, event.completionChar, performance, timestamp)
}
}
override fun beforeDownPressed() {
deferredLog.log()
}
override fun downPressed() {
if (!isCompletionActive()) return
val timestamp = System.currentTimeMillis()
deferredLog.log()
deferredLog.defer {
logger.downPressed(lookup, timestamp)
}
}
override fun beforeUpPressed() {
deferredLog.log()
}
override fun upPressed() {
if (!isCompletionActive()) return
val timestamp = System.currentTimeMillis()
deferredLog.log()
deferredLog.defer {
logger.upPressed(lookup, timestamp)
}
}
override fun beforeBackspacePressed() {
if (!isCompletionActive()) return
deferredLog.log()
}
override fun afterBackspacePressed() {
if (!isCompletionActive()) return
val timestamp = System.currentTimeMillis()
prefixLength--
deferredLog.log()
deferredLog.defer {
logger.afterBackspacePressed(lookup, prefixLength, timestamp)
}
}
override fun beforeCharTyped(c: Char) {
if (!isCompletionActive()) return
val timestamp = System.currentTimeMillis()
deferredLog.log()
if (c == '.') {
val item = lookup.currentItem
if (item == null) {
logger.customMessage("Before typed $c lookup.currentItem is null; lookup size: ${lookup.items.size}", timestamp)
return
}
val text = lookup.itemPattern(item)
if (item.lookupString == text) {
selectedByDotTyping = true
}
}
}
override fun afterAppend(c: Char) {
if (!isCompletionActive() || !c.isJavaIdentifierPart()) return
val timestamp = System.currentTimeMillis()
prefixLength++
deferredLog.log()
deferredLog.defer {
logger.afterCharTyped(c, lookup, prefixLength, timestamp)
}
}
private fun isSelectedByTyping(item: LookupElement?): Boolean {
if (item != null) {
val pattern = lookup.itemPattern(item)
return item.lookupString == pattern
}
return false
}
}
|
apache-2.0
|
b96ad967f9d0fa719cfc721601ee6be9
| 30.948387 | 140 | 0.641963 | 5.179916 | false | false | false | false |
zielu/GitToolBox
|
src/main/kotlin/zielu/gittoolbox/ui/actions/OpenBranchIssueActionGroup.kt
|
1
|
1691
|
package zielu.gittoolbox.ui.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.IssueNavigationConfiguration
import com.intellij.openapi.vfs.VirtualFile
import zielu.gittoolbox.cache.PerRepoInfoCache
import zielu.gittoolbox.cache.VirtualFileRepoCache
internal class OpenBranchIssueActionGroup : GitToolboxActionGroup() {
override fun getChildren(e: AnActionEvent?): Array<out AnAction> {
val children = super.getChildren(e).toMutableList()
children.addAll(e?.let { getActions(it) } ?: emptyList())
return children.toTypedArray()
}
private fun getActions(e: AnActionEvent): List<AnAction> {
return e.project?.let { prj ->
val selected = e.getData(CommonDataKeys.VIRTUAL_FILE)
selected?.let { file ->
getLinkActions(prj, file)
}
} ?: emptyList()
}
private fun getLinkActions(project: Project, file: VirtualFile): List<AnAction> {
return VirtualFileRepoCache.getInstance(project).findRepoForFileOrDir(file).map { repo ->
val repoInfo = PerRepoInfoCache.getInstance(project).getInfo(repo)
repoInfo.status.localBranch()?.let { branch ->
val issueNavigation = IssueNavigationConfiguration.getInstance(project)
val branchName = branch.name
val links = issueNavigation.findIssueLinks(branchName)
links.map { match ->
val text = match.range.substring(branchName)
OpenBranchIssueAction(text, match.targetUrl)
}
} ?: emptyList()
}.orElseGet { emptyList() }
}
}
|
apache-2.0
|
1a6dd5810488a39d2d3288ef7cf0e9ab
| 39.261905 | 93 | 0.736251 | 4.461741 | false | false | false | false |
morizooo/conference2017-android
|
app/src/main/kotlin/io/builderscon/conference2017/viewmodel/SessionViewModel.kt
|
1
|
3816
|
package io.builderscon.conference2017.viewmodel
import android.content.Intent
import android.databinding.BaseObservable
import android.support.annotation.DrawableRes
import android.view.View
import io.builderscon.client.model.Session
import io.builderscon.conference2017.R
import io.builderscon.conference2017.extension.getHourMinute
import io.builderscon.conference2017.extension.getLongFormatDate
import io.builderscon.conference2017.extension.needsAdjustColSpan
import io.builderscon.conference2017.view.activity.SessionDetailActivity
import java.util.*
class SessionViewModel(private val session: Session?) : BaseObservable() {
private var shortStime = ""
private var title = ""
internal var roomName = ""
private var minutes = ""
private var avatarURL = ""
internal var rowSpan = 1
private var colSpan = 1
private var titleMaxLines = 5
@DrawableRes
private var backgroundResId: Int = 0
private var isClickable = true
init {
session?.let {
this.shortStime = it.startsOn.getHourMinute()
this.title = it.title
this.avatarURL = it.speaker.avatarURL
this.roomName = it.room.name
this.minutes = "(" + it.duration / 60 + " 分)"
if (it.startsOn.needsAdjustColSpan()) this.colSpan = 2
decideRowSpan(it)
}
}
private fun decideRowSpan(session: Session) {
if (session.duration / 60 > 30) {
this.rowSpan = this.rowSpan * 2
this.titleMaxLines = this.titleMaxLines * 2
}
}
fun getStime(): Date? {
return session?.startsOn
}
fun showSessionDetail(view: View) {
val intent = Intent(view.context, SessionDetailActivity::class.java)
session?.let {
intent.putExtra("abstract", session.abstract)
intent.putExtra("avatarURL", session.speaker.avatarURL)
intent.putExtra("speakerName", session.speaker.nickname)
intent.putExtra("title", session.title)
intent.putExtra("start", session.startsOn.getLongFormatDate())
intent.putExtra("minutes", (session.duration / 60).toString() + "分")
intent.putExtra("roomName", roomName)
intent.putExtra("materialLevel", getLevelTag(session.materialLevel.toString()))
}
view.context.startActivity(intent)
}
// TODO Refactor
private fun getLevelTag(level: String): String {
if (level == "INTERMEDIATE") return "中級者"
if (level == "ADVANCED") return "上級者"
return "初級者"
}
fun getShortStime(): String {
return shortStime
}
fun getTitle(): String {
return title
}
fun getMinutes(): String {
return minutes
}
fun getRowSpan(): Int {
return rowSpan
}
fun getColSpan(): Int {
return colSpan
}
fun getBackgroundResId(): Int {
return backgroundResId
}
fun isClickable(): Boolean {
return isClickable
}
fun getTitleMaxLines(): Int {
return titleMaxLines
}
fun getAvatarURL(): String {
return avatarURL
}
companion object SessionViewModel {
fun createEmpty(rowSpan: Int): io.builderscon.conference2017.viewmodel.SessionViewModel {
return createEmpty(rowSpan, 1)
}
fun createEmpty(rowSpan: Int, colSpan: Int): io.builderscon.conference2017.viewmodel.SessionViewModel {
val empty = SessionViewModel(null)
return empty.apply {
empty.rowSpan = rowSpan
empty.colSpan = colSpan
isClickable = false
avatarURL = ""
backgroundResId = R.drawable.bg_empty_session
}
}
}
}
|
apache-2.0
|
b987821358326ec1dee64704ad06f9d6
| 26.294964 | 111 | 0.630206 | 4.560096 | false | false | false | false |
CosmoRing/PokemonGoBot
|
src/main/kotlin/ink/abb/pogo/scraper/tasks/Export.kt
|
1
|
11568
|
/**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.tasks
import POGOProtos.Enums.PokemonIdOuterClass
import POGOProtos.Enums.PokemonMoveOuterClass
import com.pokegoapi.api.player.PlayerProfile
import com.pokegoapi.api.pokemon.Pokemon
import com.pokegoapi.api.pokemon.PokemonMetaRegistry
import com.pokegoapi.api.pokemon.PokemonMoveMetaRegistry
import com.pokegoapi.google.common.geometry.S2CellId
import com.pokegoapi.google.common.geometry.S2LatLng
import ink.abb.pogo.scraper.Bot
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.Task
import ink.abb.pogo.scraper.util.Log
import ink.abb.pogo.scraper.util.cachedInventories
import ink.abb.pogo.scraper.util.inventory.size
import ink.abb.pogo.scraper.util.io.CSVWriter
import ink.abb.pogo.scraper.util.io.JSONWriter
import ink.abb.pogo.scraper.util.pokemon.getIv
import ink.abb.pogo.scraper.util.pokemon.getIvPercentage
import java.text.SimpleDateFormat
import java.util.*
class Export : Task {
override fun run(bot: Bot, ctx: Context, settings: Settings) {
val compareName = Comparator<Pokemon> { a, b ->
a.pokemonId.name.compareTo(b.pokemonId.name)
}
val compareIv = Comparator<Pokemon> { a, b ->
// compare b to a to get it descending
if (settings.sortByIv) {
b.getIv().compareTo(a.getIv())
} else {
b.cp.compareTo(a.cp)
}
}
try {
val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// Output player information
val profile: Map<String, String> = mapOf(
Pair("Name", ctx.profile.playerData.username),
Pair("Team", ctx.profile.playerData.team.name),
Pair("Pokecoin", "${ctx.profile.currencies.get(PlayerProfile.Currency.POKECOIN)}"),
Pair("Stardust", "${ctx.profile.currencies.get(PlayerProfile.Currency.STARDUST)}"),
Pair("Level", "${ctx.profile.stats.level}"),
Pair("Experience", "${ctx.profile.stats.experience}"),
Pair("Previous Level Experience", "${ctx.profile.stats.prevLevelXp}"),
Pair("Next Level Experience", "${ctx.profile.stats.nextLevelXp}"),
Pair("Km walked", ds("${ctx.profile.stats.kmWalked}", settings)),
Pair("Pokemons Encountered", "${ctx.profile.stats.pokemonsEncountered}"),
Pair("Pokemons Captured", "${ctx.profile.stats.pokemonsCaptured}"),
Pair("Unique Pokedex Entries", "${ctx.profile.stats.uniquePokedexEntries}"),
Pair("Evolutions", "${ctx.profile.stats.evolutions}"),
Pair("Pokestop Visits", "${ctx.profile.stats.pokeStopVisits}"),
Pair("Pokeballs Thrown", "${ctx.profile.stats.pokeballsThrown}"),
Pair("Eggs Hatched", "${ctx.profile.stats.eggsHatched}"),
Pair("Battle Attack Won", "${ctx.profile.stats.battleAttackWon}"),
Pair("Battle Attack Total", "${ctx.profile.stats.battleAttackTotal}"),
Pair("Battle Defended Won", "${ctx.profile.stats.battleDefendedWon}"),
Pair("Battle Training Won", "${ctx.profile.stats.battleTrainingTotal}"),
Pair("Battle Training Total", "${ctx.profile.stats.battleTrainingTotal}"),
Pair("Prestige Raised Total", "${ctx.profile.stats.prestigeRaisedTotal}"),
Pair("Prestige Dropped Total", "${ctx.profile.stats.prestigeDroppedTotal}"),
Pair("Pokemon Deployed", "${ctx.profile.stats.pokemonDeployed}"),
Pair("Pokebank Size", "${ctx.api.cachedInventories.pokebank.pokemons.size + ctx.api.cachedInventories.hatchery.eggs.size}"),
Pair("Maximum Pokebank Storage", "${ctx.profile.playerData.maxPokemonStorage}"),
Pair("Inventory Size", "${ctx.api.cachedInventories.itemBag.size()}"),
Pair("Maximum Inventory Storage", "${ctx.profile.playerData.maxItemStorage}"),
Pair("Last Update", dateFormatter.format(Date())),
Pair("Location Latitude", ds("${ctx.lat.get()}", settings)),
Pair("Location Longitude", ds("${ctx.lng.get()}", settings))
)
// Output Eggs
val eggs = ArrayList<Map<String, String>>()
for (egg in ctx.api.cachedInventories.hatchery.eggs)
{
val latLng = S2LatLng(S2CellId(egg.capturedCellId).toPoint())
eggs.add(mapOf(
Pair("Walked [km]", ds("${egg.eggKmWalked}", settings)),
Pair("Target [km]", ds("${egg.eggKmWalkedTarget}", settings)),
Pair("Incubated?", "${egg.isIncubate}"),
Pair("Found", dateFormatter.format(Date(egg.creationTimeMs))),
Pair("Location Latitude", ds("${latLng.latDegrees()}", settings)),
Pair("Location Longitude", ds("${latLng.lngDegrees()}", settings))
))
}
// Output Items
val items = ArrayList<Map<String, String>>()
for (item in ctx.api.cachedInventories.itemBag.items) {
items.add(mapOf(
Pair("Item", item.itemId.name),
Pair("Count", "${item.count}")
))
}
// Output Pokebank
val pokemons = ArrayList<Map<String, String>>()
ctx.api.cachedInventories.pokebank.pokemons.sortedWith(compareName.thenComparing(compareIv)).map {
val latLng = S2LatLng(S2CellId(it.capturedS2CellId).toPoint())
val pmeta = PokemonMetaRegistry.getMeta(PokemonIdOuterClass.PokemonId.forNumber(it.pokemonId.number))
val pmmeta1 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(it.move1.number))
val pmmeta2 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(it.move2.number))
mapOf(
Pair("Number", "${it.pokemonId.number}"),
Pair("Name", it.pokemonId.name),
Pair("Nickname", it.nickname),
Pair("Favorite?", "${it.isFavorite}"),
Pair("CP", "${it.cp}"),
Pair("IV [%]", "${it.getIvPercentage()}"),
Pair("Stamina (HP)", "${it.stamina}"),
Pair("Max Stamina (HP)", "${it.maxStamina}"),
Pair("Class", pmeta.pokemonClass.name),
Pair("Type", formatType(pmeta.type1.name, pmeta.type2.name)),
Pair("Move 1", it.move1.name),
Pair("Move 1 Type", pmmeta1.type.name),
Pair("Move 1 Power", "${pmmeta1.power}"),
Pair("Move 1 Accuracy", "${pmmeta1.accuracy}"),
Pair("Move 1 Crit Chance", ds("${pmmeta1.critChance}", settings)),
Pair("Move 1 Time", "${pmmeta1.time}"),
Pair("Move 1 Energy", "${pmmeta1.energy}"),
Pair("Move 2", it.move2.name),
Pair("Move 2 Type", pmmeta2.type.name),
Pair("Move 2 Power", "${pmmeta2.power}"),
Pair("Move 2 Accuracy", "${pmmeta2.accuracy}"),
Pair("Move 2 Crit Chance", ds("${pmmeta2.critChance}", settings)),
Pair("Move 2 Time", "${pmmeta2.time}"),
Pair("Move 2 Energy", "${pmmeta2.energy}"),
Pair("iStamina", "${it.individualStamina}"),
Pair("iAttack", "${it.individualAttack}"),
Pair("iDefense", "${it.individualDefense}"),
Pair("cpMultiplier", ds("${it.cpMultiplier}", settings)),
Pair("Height [m]", ds("${it.heightM}", settings)),
Pair("Weight [kg]", ds("${it.weightKg}", settings)),
Pair("Candy", "${it.candy}"),
Pair("Candies to evolve", "${it.candiesToEvolve}"),
Pair("Candy costs for powerup", "${it.candyCostsForPowerup}"),
Pair("Stardust costs for powerup", "${it.stardustCostsForPowerup}"),
Pair("Found", dateFormatter.format(Date(it.creationTimeMs))),
Pair("Found Latitude", ds("${latLng.latDegrees()}", settings)),
Pair("Found Longitude", ds("${latLng.lngDegrees()}", settings)),
Pair("Base Capture Rate", ds("${it.baseCaptureRate}", settings)),
Pair("Base Flee Rate", ds("${it.baseFleeRate}", settings)),
Pair("Battles Attacked", "${it.battlesAttacked}"),
Pair("Battles Defended", "${it.battlesDefended}"),
Pair("Injured?", "${it.isInjured}"),
Pair("Fainted?", "${it.isFainted}"),
Pair("Level", ds("${it.level}", settings)),
Pair("CP after powerup", "${it.cpAfterPowerup}"),
Pair("Max CP", "${it.maxCp}"),
Pair("ID", "${it.id}")
)
}.forEach { pokemons.add(it) }
when (settings.export) {
"CSV" -> {
val filename = "export_" + settings.name + ".csv"
val writer = CSVWriter(filename)
writer.write(profile, eggs, items, pokemons)
Log.normal("Wrote export $filename.")
}
"DSV" -> {
val filename = "export_" + settings.name + ".csv"
val writer = CSVWriter(filename, ";")
writer.write(profile, eggs, items, pokemons)
Log.normal("Wrote export $filename.")
}
"JSON" -> {
val filename = "export_" + settings.name + ".json"
val writer = JSONWriter(filename)
writer.write(profile, eggs, items, pokemons)
Log.normal("Wrote export $filename.")
}
else -> {
Log.red("Invalid export configuration!")
}
}
} catch (e: Exception) {
Log.red("Error writing export: " + e.message)
}
}
// Detect if the "float" fields need to be forced to use "," instead of "." (DSV export)
private fun ds(string: String, settings: Settings): String {
var result = string
if (settings.export.equals("DSV")) {
result = result.replace(".", ",")
}
return result
}
// Don't concat 2nd pokemon type "NONE"
private fun formatType(type1: String, type2: String): String {
if (type2.equals("NONE")) return type1
return type1 + "/" + type2
}
}
|
gpl-3.0
|
f2b9847db8be122b43cab2e8e4493055
| 52.313364 | 144 | 0.537344 | 4.630905 | false | false | false | false |
softappeal/yass
|
kotlin/yass/main/ch/softappeal/yass/serialize/Writer.kt
|
1
|
2967
|
package ch.softappeal.yass.serialize
import java.io.*
import java.nio.*
import java.nio.charset.*
abstract class Writer {
@Throws(Exception::class)
abstract fun writeByte(value: Byte)
@Throws(Exception::class)
abstract fun writeBytes(buffer: ByteArray, offset: Int, length: Int)
fun writeBytes(buffer: ByteArray) =
writeBytes(buffer, 0, buffer.size)
fun writeShort(value: Short) {
writeByte((value.toInt() shr 8).toByte())
writeByte((value.toInt() shr 0).toByte())
}
fun writeInt(value: Int) {
writeByte((value shr 24).toByte())
writeByte((value shr 16).toByte())
writeByte((value shr 8).toByte())
writeByte((value shr 0).toByte())
}
fun writeLong(value: Long) {
writeByte((value shr 56).toByte())
writeByte((value shr 48).toByte())
writeByte((value shr 40).toByte())
writeByte((value shr 32).toByte())
writeByte((value shr 24).toByte())
writeByte((value shr 16).toByte())
writeByte((value shr 8).toByte())
writeByte((value shr 0).toByte())
}
fun writeChar(value: Char) {
writeByte((value.toInt() shr 8).toByte())
writeByte((value.toInt() shr 0).toByte())
}
fun writeFloat(value: Float) =
writeInt(java.lang.Float.floatToRawIntBits(value))
fun writeDouble(value: Double) =
writeLong(java.lang.Double.doubleToRawLongBits(value))
fun writeVarInt(v: Int) {
var value = v
while (true) {
if ((value and 0b0111_1111.inv()) == 0) {
writeByte(value.toByte())
return
}
writeByte(((value and 0b0111_1111) or 0b1000_0000).toByte())
value = value ushr 7
}
}
fun writeZigZagInt(value: Int) =
writeVarInt((value shl 1) xor (value shr 31))
fun writeVarLong(v: Long) {
var value = v
while (true) {
if ((value and 0b0111_1111.inv()) == 0L) {
writeByte(value.toByte())
return
}
writeByte(((value and 0b0111_1111) or 0b1000_0000).toByte())
value = value ushr 7
}
}
fun writeZigZagLong(value: Long) =
writeVarLong((value shl 1) xor (value shr 63))
fun stream() = object : OutputStream() {
override fun write(i: Int) = writeByte(i.toByte())
override fun write(b: ByteArray, off: Int, len: Int) = writeBytes(b, off, len)
}
}
fun writer(out: OutputStream) = object : Writer() {
override fun writeByte(value: Byte) = out.write(value.toInt())
override fun writeBytes(buffer: ByteArray, offset: Int, length: Int) = out.write(buffer, offset, length)
}
class ByteBufferOutputStream(size: Int) : ByteArrayOutputStream(size) {
fun toByteBuffer(): ByteBuffer = ByteBuffer.wrap(buf, 0, count)
}
fun utf8toBytes(value: String): ByteArray =
value.toByteArray(StandardCharsets.UTF_8)
|
bsd-3-clause
|
a75d4a4734412fe309c7e513b3268d4b
| 29.587629 | 108 | 0.599933 | 3.993271 | false | false | false | false |
duftler/clouddriver
|
cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/config/SqlCacheConfiguration.kt
|
1
|
7854
|
package com.netflix.spinnaker.config
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.discovery.EurekaClient
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.cats.agent.AgentScheduler
import com.netflix.spinnaker.cats.agent.ExecutionInstrumentation
import com.netflix.spinnaker.cats.cache.NamedCacheFactory
import com.netflix.spinnaker.cats.cluster.AgentIntervalProvider
import com.netflix.spinnaker.cats.cluster.DefaultNodeStatusProvider
import com.netflix.spinnaker.cats.cluster.NodeStatusProvider
import com.netflix.spinnaker.cats.module.CatsModule
import com.netflix.spinnaker.cats.provider.Provider
import com.netflix.spinnaker.cats.provider.ProviderRegistry
import com.netflix.spinnaker.clouddriver.sql.SqlAgent
import com.netflix.spinnaker.cats.sql.SqlProviderRegistry
import com.netflix.spinnaker.cats.sql.cache.SpectatorSqlCacheMetrics
import com.netflix.spinnaker.cats.sql.cache.SqlUnknownAgentCleanupAgent
import com.netflix.spinnaker.cats.sql.cache.SqlCacheMetrics
import com.netflix.spinnaker.cats.sql.cache.SqlCleanupStaleOnDemandCachesAgent
import com.netflix.spinnaker.cats.sql.cache.SqlNamedCacheFactory
import com.netflix.spinnaker.cats.sql.cache.SqlNames
import com.netflix.spinnaker.cats.sql.cache.SqlTableMetricsAgent
import com.netflix.spinnaker.clouddriver.cache.CustomSchedulableAgentIntervalProvider
import com.netflix.spinnaker.clouddriver.cache.EurekaStatusNodeStatusProvider
import com.netflix.spinnaker.clouddriver.sql.SqlProvider
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.kork.sql.config.DefaultSqlConfiguration
import com.netflix.spinnaker.kork.sql.config.SqlProperties
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.slf4j.MDCContext
import org.jooq.DSLContext
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.ObjectProvider
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import java.time.Clock
import java.time.Duration
import java.util.Optional
import kotlin.contracts.ExperimentalContracts
const val coroutineThreadPrefix = "catsSql"
@ExperimentalContracts
@Configuration
@ConditionalOnProperty("sql.cache.enabled")
@Import(DefaultSqlConfiguration::class)
@EnableConfigurationProperties(SqlAgentProperties::class, SqlConstraints::class)
@ComponentScan("com.netflix.spinnaker.cats.sql.controllers")
class SqlCacheConfiguration {
companion object {
private val log = LoggerFactory.getLogger(SqlCacheConfiguration::class.java)
}
@Bean
fun sqlCacheMetrics(registry: Registry): SqlCacheMetrics {
return SpectatorSqlCacheMetrics(registry)
}
@Bean
fun catsModule(
providers: List<Provider>,
executionInstrumentation: List<ExecutionInstrumentation>,
cacheFactory: NamedCacheFactory,
agentScheduler: AgentScheduler<*>
): CatsModule {
return CatsModule.Builder()
.providerRegistry(SqlProviderRegistry(providers, cacheFactory))
.cacheFactory(cacheFactory)
.scheduler(agentScheduler)
.instrumentation(executionInstrumentation)
.build(providers)
}
/**
* sql.cache.async.poolSize: If set to a positive integer, a fixed thread pool of this size is created
* as part of a coroutineContext. If sql.cache.maxQueryConcurrency is also >1 (default value: 4),
* sql queries to fetch > 2 * sql.cache.readBatchSize cache keys will be made asynchronously in batches of
* maxQueryConcurrency size.
*
* sql.tableNamespace: Name spaces data tables, as well as the agent lock table if using the SqlAgentScheduler.
* Table namespacing allows flipping to new/empty data tables within the same master if necessary to rebuild
* the cache from scratch, such as after disabling caching agents for an account/region.
*/
@ObsoleteCoroutinesApi
@Bean
fun cacheFactory(
jooq: DSLContext,
clock: Clock,
sqlProperties: SqlProperties,
cacheMetrics: SqlCacheMetrics,
dynamicConfigService: DynamicConfigService,
sqlConstraints: SqlConstraints,
@Value("\${sql.cache.async-pool-size:0}") poolSize: Int,
@Value("\${sql.table-namespace:#{null}}") tableNamespace: String?
): NamedCacheFactory {
if (tableNamespace != null && !tableNamespace.matches("""^\w+$""".toRegex())) {
throw IllegalArgumentException("tableNamespace can only contain characters [a-z, A-Z, 0-9, _]")
}
/**
* newFixedThreadPoolContext was marked obsolete in Oct 2018, to be reimplemented as a new
* concurrency limiting threaded context factory with reduced context switch overhead. As of
* Feb 2019, the new implementation is unreleased. See: https://github.com/Kotlin/kotlinx.coroutines/issues/261
*
* TODO: switch to newFixedThreadPoolContext's replacement when ready
*/
val dispatcher = if (poolSize < 1) {
null
} else {
newFixedThreadPoolContext(nThreads = poolSize, name = coroutineThreadPrefix) + MDCContext()
}
if (dispatcher != null) {
log.info("Configured coroutine context with newFixedThreadPoolContext of $poolSize threads")
}
return SqlNamedCacheFactory(
jooq,
ObjectMapper(),
dispatcher,
clock,
sqlProperties.retries,
tableNamespace,
cacheMetrics,
dynamicConfigService,
sqlConstraints
)
}
@Bean
fun agentIntervalProvider(sqlAgentProperties: SqlAgentProperties): AgentIntervalProvider {
return CustomSchedulableAgentIntervalProvider(
Duration.ofSeconds(sqlAgentProperties.poll.intervalSeconds).toMillis(),
Duration.ofSeconds(sqlAgentProperties.poll.errorIntervalSeconds).toMillis(),
Duration.ofSeconds(sqlAgentProperties.poll.timeoutSeconds).toMillis()
)
}
@Bean
@ConditionalOnExpression("\${sql.read-only:false} == false")
fun sqlTableMetricsAgent(
jooq: DSLContext,
registry: Registry,
clock: Clock,
@Value("\${sql.table-namespace:#{null}}") namespace: String?
): SqlTableMetricsAgent =
SqlTableMetricsAgent(jooq, registry, clock, namespace)
@Bean
@ConditionalOnExpression("\${sql.read-only:false} == false")
fun sqlCleanupStaleOnDemandCachesAgent(
applicationContext: ApplicationContext,
registry: Registry,
clock: Clock
): SqlCleanupStaleOnDemandCachesAgent =
SqlCleanupStaleOnDemandCachesAgent(applicationContext, registry, clock)
@Bean
@ConditionalOnExpression("!\${sql.read-only:false} && \${sql.unknown-agent-cleanup-agent.enabled:false}")
fun sqlUnknownAgentCleanupAgent(
providerRegistry: ObjectProvider<ProviderRegistry>,
jooq: DSLContext,
registry: Registry,
sqlConstraints: SqlConstraints,
@Value("\${sql.table-namespace:#{null}}") tableNamespace: String?
): SqlUnknownAgentCleanupAgent =
SqlUnknownAgentCleanupAgent(providerRegistry, jooq, registry, SqlNames(tableNamespace, sqlConstraints))
@Bean
@ConditionalOnExpression("\${sql.read-only:false} == false")
fun sqlAgentProvider(agents: List<SqlAgent>): SqlProvider =
SqlProvider(agents.toMutableList())
@Bean
fun nodeStatusProvider(eurekaClient: Optional<EurekaClient>): NodeStatusProvider {
return if (eurekaClient.isPresent) {
EurekaStatusNodeStatusProvider(eurekaClient.get())
} else {
DefaultNodeStatusProvider()
}
}
}
|
apache-2.0
|
ac598b03f5b1fcf695da642130a1f70e
| 39.90625 | 115 | 0.785205 | 4.424789 | false | true | false | false |
DR-YangLong/spring-boot-kotlin-demo
|
src/main/kotlin/site/yanglong/promotion/model/Roles.kt
|
1
|
1258
|
package site.yanglong.promotion.model
import java.io.Serializable
import com.baomidou.mybatisplus.enums.IdType
import com.baomidou.mybatisplus.annotations.TableId
import com.baomidou.mybatisplus.activerecord.Model
import com.baomidou.mybatisplus.annotations.TableField
import com.baomidou.mybatisplus.annotations.TableLogic
/**
*
*
*
*
*
* @author Dr.YangLong
* @since 2017-11-01
*/
class Roles : Model<Roles>() {
/**
* 角色id
*/
@TableId(value = "id", type = IdType.AUTO)
var id: Long? = null
/**
* 角色字符串标识
*/
var identify: String? = null
/**
* 名称
*/
var name: String? = null
/**
* 备注说明
*/
var remark: String? = null
/**
* 是否启用
*/
@TableField
@TableLogic
var enable: String? = null
override fun pkVal(): Serializable? {
return this.id
}
override fun toString(): String {
return "Roles{" +
", id=" + id +
", identify=" + identify +
", name=" + name +
", remark=" + remark +
", enable=" + enable +
"}"
}
companion object {
private val serialVersionUID = 1L
}
}
|
apache-2.0
|
04f52cee63db53c44d546f085d40c20e
| 18.0625 | 54 | 0.543443 | 3.910256 | false | false | false | false |
vjache/klips
|
src/main/java/org/klips/engine/rete/builder/optimizer/Rename.kt
|
1
|
1508
|
package org.klips.engine.rete.builder.optimizer
import org.klips.dsl.Facet
import org.klips.engine.Binding
import org.klips.engine.SimpleBinding
import org.klips.engine.rete.ProxyNode
class Rename : Tree {
override val reteNode: ProxyNode
override val signature: Signature
override val junctLeafsMap: Map<Facet.FacetRef<*>, Set<Leaf>>
get() {
return tree.junctLeafsMap.mapKeys {
val facet = reteNode.renamingBinding[it.key]
facet as Facet.FacetRef<*>
}
}
var tree: Tree
constructor(pnode: ProxyNode) {
this.reteNode = pnode
tree = makeTree(pnode.node)
signature = Signature(
1 + tree.signature.nonLeafCount,
1 + tree.signature.deep)
}
constructor(reteNode: ProxyNode, signature: Signature, tree: Tree){
this.reteNode = reteNode
this.signature = signature
this.tree = tree
}
override fun clone() = Rename(reteNode, signature, tree)
override fun bind_(t: Tree): Binding? {
if (t !is Rename)
return null
if (signature != t.signature)
return null
if (junctLeafs != t.junctLeafs)
return null
return tree.bind(t.tree)?.let{ binding ->
val data = binding.map {
Pair(reteNode.renamingBinding[it.key]!!,
t.reteNode.renamingBinding[it.value]!!)
}
SimpleBinding(data)
}
}
}
|
apache-2.0
|
6fc9f4fc1502666589af3229edff4a41
| 23.737705 | 71 | 0.589523 | 4.188889 | false | false | false | false |
AK-47-D/cms
|
src/main/kotlin/com/ak47/cms/cms/service/CrawImageService.kt
|
1
|
4914
|
package com.ak47.cms.cms.service
import com.ak47.cms.cms.api.CrawlerWebClient
import com.ak47.cms.cms.api.GankApiBuilder
import com.ak47.cms.cms.api.ImageSearchApiBuilder
import com.ak47.cms.cms.dao.ImageRepository
import com.ak47.cms.cms.dao.SearchKeyWordRepository
import com.ak47.cms.cms.entity.Image
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import org.jsoup.Jsoup
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*
@Service
class CrawImageService {
val logger = LoggerFactory.getLogger(CrawImageService::class.java)
val crawlerWebClient = CrawlerWebClient.instanceCrawlerClient()
@Autowired lateinit var imageRepository: ImageRepository
@Autowired lateinit var searchKeyWordRepository: SearchKeyWordRepository
fun doBaiduImageCrawJob() = runBlocking {
val list = searchKeyWordRepository.findAll()
for (i in 1..1000) {
list.forEach {
launch(CommonPool) {
saveBaiduImage(it.keyWord, i)
}
}
}
}
fun doGankImageCrawJob() = runBlocking {
for (page in 1..6) {
launch(CommonPool) {
saveGankImage(page)
}
}
}
fun doCrawHuaBanImages() {
val boardsUrls = getBoards()
launch(CommonPool) {
boardsUrls.forEach {
saveHuaBanImages(it)
}
}
}
private fun getBoards(): MutableSet<String> {
val boardsUrl = "https://huaban.com/boards/favorite/beauty/"
val boardsUrls = mutableSetOf("http://huaban.com/favorite/beauty/", "http://huaban.com/boards/17375733/")
crawlerWebClient.getPage(boardsUrl).asText()
val boardsPageHtml = crawlerWebClient.getPage(boardsUrl).asXml()
val document = Jsoup.parse(boardsPageHtml)
println("document = ${document}")
println("document = ${document.childNodeSize()}")
// document.getElementsByClassName('Board wfc ')[0].getAttribute('data-id')
// "30377705"
document.getElementsByClass("Board wfc wft").forEach {
val data_id = it.attr("data-id")
println("data_id = ${data_id}")
boardsUrls.add("http://huaban.com/boards/${data_id}")
}
println("boardsUrls = ${boardsUrls}")
return boardsUrls
}
private fun saveHuaBanImages(beautyUrl: String) {
val beautyPageHtml = crawlerWebClient.getPage(beautyUrl).asXml()
val document = Jsoup.parse(beautyPageHtml)
// println(document)
// document.getElementsByClassName('img x layer-view loaded')[1].children[1].src
document.getElementsByClass("img x layer-view loaded").forEach {
var url = "http:" + it.child(1).attr("src")
url = url.replace("/fw/480", "/fw/1080")
println("花瓣 url = ${url}")
if (imageRepository.countByUrl(url) == 0) {
val image = Image()
image.category = "花瓣 ${SimpleDateFormat("yyyy-MM-dd").format(Date())}"
image.url = url
image.sourceType = 2
image.imageBlob = getByteArray(url)
logger.info("image = ${image}")
imageRepository.save(image)
}
}
}
private fun saveGankImage(page: Int) {
val api = GankApiBuilder.build(page)
JsonResultProcessor.getGankImageUrls(api).forEach {
val url = it
if (imageRepository.countByUrl(url) == 0) {
val image = Image()
image.category = "干货集中营福利 ${SimpleDateFormat("yyyy-MM-dd").format(Date())}"
image.url = url
image.sourceType = 1
image.imageBlob = getByteArray(url)
logger.info("image = ${image}")
imageRepository.save(image)
}
}
}
private fun saveBaiduImage(word: String, i: Int) {
val api = ImageSearchApiBuilder.build(word, i)
JsonResultProcessor.getBaiduImageCategoryAndUrlList(api).forEach {
val category = it.category
val url = it.url
if (imageRepository.countByUrl(url) == 0) {
val image = Image()
image.category = category
image.url = url
image.sourceType = 0
//image.imageBlob = getByteArray(url)
logger.info("image = ${image}")
imageRepository.save(image)
}
}
}
private fun getByteArray(url: String): ByteArray {
val urlObj = URL(url)
return urlObj.readBytes()
}
}
|
apache-2.0
|
328643ac5def2e716836960d4972eb41
| 33.695035 | 113 | 0.604661 | 4.199142 | false | false | false | false |
UweTrottmann/SeriesGuide
|
app/src/main/java/com/battlelancer/seriesguide/sync/SgSyncService.kt
|
1
|
836
|
package com.battlelancer.seriesguide.sync
import android.app.Service
import android.content.Intent
import android.os.IBinder
import timber.log.Timber
/**
* A [Service] that returns an IBinder [SgSyncAdapter], allowing the sync adapter
* framework to call onPerformSync().
*/
class SgSyncService : Service() {
override fun onCreate() {
Timber.d("Creating sync service")
synchronized(syncAdapterLock) {
if (syncAdapter == null) {
syncAdapter = SgSyncAdapter(applicationContext)
}
}
}
override fun onBind(intent: Intent): IBinder? {
Timber.d("Binding sync adapter")
return syncAdapter?.syncAdapterBinder
}
companion object {
private val syncAdapterLock = Any()
private var syncAdapter: SgSyncAdapter? = null
}
}
|
apache-2.0
|
6f51d9f33699eb398491b65b00b65235
| 25.15625 | 81 | 0.660287 | 4.568306 | false | false | false | false |
AlmasB/FXGL
|
fxgl-core/src/main/kotlin/com/almasb/fxgl/core/util/PauseMenuBGGen.kt
|
1
|
2714
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.core.util
//
import java.io.ByteArrayOutputStream
import java.util.*
import java.util.zip.InflaterInputStream
//
//import javafx.embed.swing.SwingFXUtils
//import javafx.scene.SnapshotParameters
//import javafx.scene.effect.DropShadow
//import javafx.scene.paint.Color
//import javafx.scene.shape.Polygon
//import javafx.scene.shape.StrokeType
//import java.nio.file.Files
//import java.nio.file.Paths
//import javax.imageio.ImageIO
//
object PauseMenuBGGen {
private const val GEN_KEY = "eNqdlAsOgCAMQx/3v7RGwRTdp5EQs0CZY20ZwxicE564hF5jgJUWM1uLakuzCuqvF8AoSmKOGBbtoesLtNGAhAp8FUTcouKI7E0G0RLmnDsK2ypd36qVqKBM3dXkdzBc/g0RmLlu2WLay/LK58fBQkhv76E/vSDvSSTfQBXwVXFql39O9c6odhOvbhEJawJLriww5J0In6ibtvWgQkb6tXgA+4UEzw=="
fun generate(): ByteArray {
val bytes = Base64.getDecoder().decode(GEN_KEY)
val baos = ByteArrayOutputStream()
InflaterInputStream(bytes.inputStream()).use {
it.copyTo(baos)
}
return baos.toByteArray()
}
}
///**
// *
// *
// * @author Almas Baimagambetov ([email protected])
// */
//fun main(args: Array<String>) {
// val dx = 20.0
// val dy = 15.0
// val width = 250.0
// val height = 400.0
//
// val outer = Polygon(
// 0.0, dx,
// dx, 0.0,
// width * 2 / 3, 0.0,
// width * 2 / 3, 2 * dy,
// width * 2 / 3 + 3 * dx, 2 * dy,
// width * 2 / 3 + 3 * dx, 0.0,
// width - dx, 0.0,
// width, dx,
// width, height - dy,
// width - dy, height,
// dy, height,
// 0.0, height - dy,
// 0.0, height / 3 + 4 * dy,
// dx, height / 3 + 5 * dy,
// dx, height / 3 + 3 * dy,
// 0.0, height / 3 + 2 * dy,
// 0.0, height / 3,
// dx, height / 3 + dy,
// dx, height / 3 - dy,
// 0.0, height / 3 - 2 * dy
// )
//
// outer.fill = Color.BLACK
// outer.stroke = Color.AQUA
// outer.strokeWidth = 6.0
// outer.strokeType = StrokeType.CENTERED
// outer.effect = DropShadow(15.0, Color.BLACK)
//
// val params = SnapshotParameters()
// params.fill = Color.TRANSPARENT
//
// // draw into image to speed up rendering
// val image = outer.snapshot(params, null)
//
// val img = SwingFXUtils.fromFXImage(image, null)
//
// try {
// Files.newOutputStream(Paths.get("pause_menu_bg.png")).use {
// ImageIO.write(img, "png", it)
// }
// } catch (e: Exception) {
// println("failed $e")
// }
//}
|
mit
|
6a42e799bd05bbcf3e4ed0b7f7bb3bfe
| 27.882979 | 258 | 0.577377 | 2.95321 | false | false | false | false |
joseph-roque/BowlingCompanion
|
app/src/main/java/ca/josephroque/bowlingcompanion/common/ScrollableTextDialog.kt
|
1
|
2755
|
package ca.josephroque.bowlingcompanion.common
import android.app.Dialog
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.v4.app.DialogFragment
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.Window
import android.view.View
import android.view.ViewGroup
import ca.josephroque.bowlingcompanion.R
import kotlinx.android.synthetic.main.dialog_scrollable_text.toolbar_scrollable as scrollableToolbar
import kotlinx.android.synthetic.main.dialog_scrollable_text.tv_scrollable as scrollableTextView
import kotlinx.android.synthetic.main.dialog_scrollable_text.view.*
/**
* Copyright (C) 2018 Joseph Roque
*
* Presents scrollable text.
*/
class ScrollableTextDialog : DialogFragment() {
companion object {
@Suppress("unused")
private const val TAG = "ScrollableTextDialog"
private const val ARG_TITLE = "${TAG}_title"
private const val ARG_TEXT = "${TAG}_text"
fun newInstance(@StringRes title: Int, text: CharSequence): ScrollableTextDialog {
val fragment = ScrollableTextDialog()
val args = Bundle().apply {
putInt(ARG_TITLE, title)
putCharSequence(ARG_TEXT, text)
}
fragment.arguments = args
return fragment
}
}
private var title: Int = 0
private var text: CharSequence? = null
// MARK: Lifecycle functions
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
arguments?.let {
title = it.getInt(ARG_TITLE)
text = it.getCharSequence(ARG_TEXT)
}
val rootView = inflater.inflate(R.layout.dialog_scrollable_text, container, false)
val activity = activity as? AppCompatActivity
activity?.setSupportActionBar(rootView.toolbar_scrollable)
activity?.supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_dismiss)
}
setHasOptionsMenu(true)
return rootView
}
override fun onStart() {
super.onStart()
scrollableToolbar.setTitle(title)
scrollableTextView.text = text
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
activity?.supportFragmentManager?.popBackStack()
dismiss()
return true
}
}
|
mit
|
491b2da6d6379bb831c0803438799c6e
| 30.306818 | 116 | 0.690381 | 4.937276 | false | false | false | false |
Cardstock/Cardstock
|
src/main/kotlin/xyz/cardstock/cardstock/configuration/Configuration.kt
|
1
|
3107
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package xyz.cardstock.cardstock.configuration
import com.google.common.collect.Lists
import org.json.JSONObject
import xyz.cardstock.cardstock.extensions.jsonobject.getWithDefaults
import xyz.cardstock.cardstock.extensions.jsonobject.optWithDefaults
import java.nio.file.Files
import java.nio.file.Path
import java.util.Collections
/**
* The file-based configuration for this bot.
*/
open class Configuration(path: Path) {
/**
* The actual JSON object that was read from the file.
*/
protected val json: JSONObject = JSONObject(Files.readAllLines(path, Charsets.UTF_8).joinToString("\n"))
/**
* The mutable list of servers specified in the `servers` JSON object.
*/
protected val _servers = Lists.newArrayList<Server>()
/**
* Servers read from the `servers` JSON object in the configuration.
*/
val servers: List<Server>
get() = Collections.unmodifiableList(this._servers)
init {
val defaults = this.json.optJSONObject("defaults") ?: JSONObject()
val listedServers = this.json.optJSONArray("servers")
check(listedServers != null && listedServers.length() > 0) { "At least one server must be defined" }
this._servers.addAll(
listedServers
.map {
if (it !is JSONObject) {
throw IllegalStateException("Invalid server defined. Servers must be JSON objects.")
}
// Cast is not useless. At least, IDEA gets all confused without it
@Suppress("USELESS_CAST")
return@map it as JSONObject
}
.map {
val host = it.getWithDefaults("host", defaults) { key, json -> json.optString(key, null) }
val port = it.getWithDefaults("port", defaults) { key, json -> json.opt(key) as Int? }
val secure = it.getWithDefaults("secure", defaults) { key, json -> json.opt(key) as Boolean? }
val nickname = it.getWithDefaults("nick", defaults) { key, json -> json.optString(key, null) }
val prefix = it.getWithDefaults("prefix", defaults) { key, json -> json.optString(key, null)?.let { it[0] } }
val user = it.optWithDefaults("user", defaults) { key, json -> json.optString(key, null) }
val realName = it.optWithDefaults("realName", defaults) { key, json -> json.optString(key, null) }
val password = it.optWithDefaults("password", defaults) { key, json -> json.optString(key, null) }
val channels = it.optWithDefaults("channels", defaults) { key, json -> json.optJSONArray("channels")?.map { it.toString() } }
return@map Server(host, port, secure, nickname, prefix, user, realName, password, channels)
}
)
}
}
|
mpl-2.0
|
37ad3c42f1e0b50fcb971a3f9e5b6412
| 47.546875 | 145 | 0.613453 | 4.382228 | false | true | false | false |
klose911/klose911.github.io
|
src/kotlin/src/tutorial/coroutine/concurrency/CounterActor.kt
|
1
|
1123
|
package tutorial.coroutine.concurrency
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.actor
// 计数器 Actor 的各种类型
sealed class CounterMsg
object IncCounter : CounterMsg()
// 递增计数器的单向消息
class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // 携带回复的请求
// 这个函数启动一个新的计数器 actor
fun CoroutineScope.counterActor() = actor<CounterMsg> {
var counter = 0 // actor 状态
for (msg in channel) {
// 即将到来消息的迭代器
when (msg) {
is IncCounter -> counter++
is GetCounter -> msg.response.complete(counter)
}
}
}
fun main(): Unit = runBlocking {
val counter = counterActor() // 创建该 actor
withContext(Dispatchers.Default) {
massiveRun {
counter.send(IncCounter)
}
}
// 发送一条消息以用来从一个 actor 中获取计数值
val response = CompletableDeferred<Int>()
counter.send(GetCounter(response))
println("Counter = ${response.await()}")
counter.close() // 关闭该actor
}
|
bsd-2-clause
|
f949ef8706853e2ce54e159bcd5135aa
| 24.657895 | 82 | 0.658462 | 3.571429 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/views/DailyView.kt
|
1
|
11172
|
package net.perfectdreams.loritta.morenitta.website.views
import net.perfectdreams.loritta.common.locale.BaseLocale
import kotlinx.html.DIV
import kotlinx.html.a
import kotlinx.html.b
import kotlinx.html.div
import kotlinx.html.h1
import kotlinx.html.i
import kotlinx.html.id
import kotlinx.html.img
import kotlinx.html.p
import kotlinx.html.script
import kotlinx.html.style
import kotlinx.html.unsafe
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.website.utils.NitroPayAdGenerator
import net.perfectdreams.loritta.morenitta.sweetmorenitta.utils.adWrapper
import net.perfectdreams.loritta.morenitta.sweetmorenitta.utils.generateNitroPayAdOrSponsor
import net.perfectdreams.loritta.morenitta.sweetmorenitta.utils.generateNitroPayVideoAd
class DailyView(
loritta: LorittaBot,
locale: BaseLocale,
path: String
) : NavbarView(
loritta,
locale,
path
) {
override fun getTitle() = "Daily"
override fun DIV.generateContent() {
style {
unsafe {
raw("""
.scene {
width: 100px;
height: 100px;
margin: 75px;
perspective: 1000px;
perspective-origin: 50% -400%;
transition: 1s;
filter: drop-shadow(12px 12px 25px rgba(0,0,0,0.5));
margin-left: auto;
margin-right: auto;
}
.scene:hover {
transform: scale(1.1);
transition: 1s;
}
.cube {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
transform: translateZ(-100px);
transition: transform 1s;
animation-name: rotate-cube;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
.cube img {
max-width: 100px;
max-height: 100px;
}
.cube__face {
position: absolute;
width: 100px;
height: 100px;
// border: 2px solid black;
font-size: 40px;
font-weight: bold;
color: white;
text-align: center;
}
.cube__face--front { background: hsla( 0, 100%, 50%, 0.7); }
.cube__face--right { background: hsla( 60, 100%, 50%, 0.7); }
.cube__face--back { background: hsla(120, 100%, 50%, 0.7); }
.cube__face--left { background: hsla(180, 100%, 50%, 0.7); }
.cube__face--top { background: hsla(240, 100%, 50%, 0.7); }
.cube__face--bottom { background: hsla(300, 100%, 50%, 0.7); }
.cube__face--front { transform: rotateY( 0deg) translateZ(50px); }
.cube__face--right { transform: rotateY( 90deg) translateZ(50px); }
.cube__face--back { transform: rotateY(180deg) translateZ(50px); }
.cube__face--left { transform: rotateY(-90deg) translateZ(50px); }
.cube__face--top { transform: rotateX( 90deg) translateZ(50px); }
.cube__face--lace1 { transform: rotateX( 0deg) rotateY(45deg) translateY(-50px) translateZ(0px); }
.cube__face--lace2 { transform: rotateX( 0deg) rotateY(-45deg) translateY(-50px) translateZ(0px); }
.cube__face--bottom { transform: rotateX(-90deg) translateZ(50px); }
label { margin-right: 10px; }
/* The animation code */
@keyframes rotate-cube {
0% {transform: rotateY(0deg); }
50% {transform: rotateY(180deg); }
100% {transform: rotateY(360deg); }
}
""")
}
}
div(classes = "odd-wrapper") {
style = "text-align: center;"
adWrapper {
generateNitroPayAdOrSponsor(
loritta,
0,
"daily-top1",
NitroPayAdGenerator.ALL_SIZES
)
generateNitroPayAdOrSponsor(
loritta,
1,
"daily-top2",
NitroPayAdGenerator.ALL_SIZES_EXCEPT_PHONES
)
}
div(classes = "media") {
div(classes = "media-body") {
p {
style = "color: #f04747;"
b {
+ "Atenção: "
}
+ "Compra e venda de sonhos com terceiros não são responsabilidade da equipe da Loritta! Se você for roubado (scamming), nós não iremos recuperar seus sonhos e se você reclamar com a equipe da Loritta você será banido, pois resolver problemas de roubos fora da Loritta não é nosso trabalho. Se você comprar/vender sonhos ou outros produtos com valores monetários (por exemplo: Discord Nitro) com terceiros, você e o seu comprador/vendedor correm risco de serem banidos caso sejam denunciados para a equipe. Muitos \"vendedores\" usam cartões clonados para vender tais produtos, logo você está correndo risco de estar cometendo um ato ilegal ao comprar com terceiros. Dar sonhos como recompensa por entrarem em um servidor também é proibido e é contra os termos de uso do Discord."
+ " "
+ "Leia mais sobre as regras da Loritta "
a(href = "/guidelines") {
+ "clicando aqui"
}
+ "."
}
p {
style = "color: #f04747;"
+ "Se você deseja comprar sonhos de uma forma segura que ainda por cima ajuda a Loritta ficar online, visite a nossa loja de sonhos "
a(href = "/user/@me/dashboard/bundles") {
+ "clicando aqui"
}
+ "!"
}
}
}
div(classes = "media") {
div(classes = "media-body") {
h1 {
+ "Prêmio Diário"
}
div {
id = "daily-prewrapper"
div {
id = "daily-wrapper"
div(classes = "scene") {
div(classes = "cube") {
div(classes = "cube__face cube__face--front") {
style = "width: 100%; height: 100%;"
img(src = "/assets/img/daily/present_side.png") {}
}
div(classes = "cube__face cube__face--back") {
style = "width: 100%; height: 100%;"
img(src = "/assets/img/daily/present_side.png") {}
}
div(classes = "cube__face cube__face--right") {
style = "width: 100%; height: 100%;"
img(src = "/assets/img/daily/present_side.png") {}
}
div(classes = "cube__face cube__face--left") {
style = "width: 100%; height: 100%;"
img(src = "/assets/img/daily/present_side.png") {}
}
div(classes = "cube__face cube__face--top") {
style = "width: 100%; height: 100%;"
img(src = "/assets/img/daily/present_top.png") {}
}
div(classes = "cube__face cube__face--lace1") {
style = "width: 100%; height: 25%"
img(src = "/assets/img/daily/present_lace.png") {}
}
div(classes = "cube__face cube__face--lace2") {
style = "width: 100%; height: 25%"
img(src = "/assets/img/daily/present_lace.png") {}
}
}
}
p {
+ "Pegue o seu prêmio diário para conseguir sonhos!"
}
div {
id = "daily-captcha"
style = "display: inline-block;"
}
div {
div(classes = "button-discord pure-button daily-reward-button button-discord-disabled") {
style = "font-size: 1.25em; transition: 0.3s;"
i(classes = "fas fa-gift") {}
+ " Pegar Prêmio"
}
}
}
div(classes = "daily-notification flavourText") {
style = "color: #f04747;"
}
}
}
}
adWrapper {
generateNitroPayAdOrSponsor(
loritta,
2,
"daily-bottom1",
NitroPayAdGenerator.ALL_SIZES
)
generateNitroPayAdOrSponsor(
loritta,
3,
"daily-bottom2",
NitroPayAdGenerator.ALL_SIZES_EXCEPT_PHONES
)
}
generateNitroPayVideoAd("daily-bottom3-video")
}
div(classes = "even-wrapper wobbly-bg") {
div(classes = "media") {
div(classes = "media-body") {
h1 {
+ "Mas... o que são sonhos?"
}
p {
+ "Sonhos são a moeda que você pode utilizar na Loritta. Você pode usar sonhos para apostar na Lorifa, comprar novos designs para o perfil, casar, comprar raspadinhas e muito mais!"
}
p {
+ "Para apostar na rifa, use `+rifa`!"
}
p {
+ "Você pode casar com a pessoa que você tanto ama com `+casar`!"
}
p {
+ "Envie sonhos para seus amigos e amigas com `+pay`!"
}
p {
+ "Você pode comprar novos designs para o seu perfil no `+profile shop`!"
}
}
div(classes = "media-figure") {
img(src = "https://loritta.website/assets/img/loritta_money_discord.png") {}
}
}
}
script {
unsafe {
raw("""
function recaptchaCallback(response) {
this['spicy-morenitta'].net.perfectdreams.spicymorenitta.routes.DailyRoute.Companion.recaptchaCallback(response)
}""")
}
}
}
}
|
agpl-3.0
|
c863dec358c70fcd860bcfda1f8bb16d
| 37.410345 | 804 | 0.455827 | 4.464128 | false | false | false | false |
wakingrufus/mastodon-jfx
|
src/main/kotlin/com/github/wakingrufus/mastodon/client/GetAccessToken.kt
|
1
|
999
|
package com.github.wakingrufus.mastodon.client
import com.github.wakingrufus.mastodon.data.OAuthModel
import com.sys1yagi.mastodon4j.MastodonClient
import com.sys1yagi.mastodon4j.api.entity.auth.AccessToken
import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException
import com.sys1yagi.mastodon4j.api.method.Apps
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
fun getAccessToken(mastodonClient: MastodonClient, clientId: String, clientSecret: String, authCode: String): AccessToken {
val apps = Apps(mastodonClient)
try {
return apps.getAccessToken(clientId = clientId, clientSecret = clientSecret, code = authCode).execute()
} catch (e: Mastodon4jRequestException) {
logger.error("error getting access token: " + e.localizedMessage, e)
throw e
}
}
fun getAccessToken(oAuth : OAuthModel): AccessToken =
getAccessToken(oAuth.client,oAuth.appRegistration.clientId, oAuth.appRegistration.clientSecret, oAuth.token!!)
|
mit
|
1ccdfe202bf9b8b6831ffc6f4d744484
| 44.454545 | 123 | 0.783784 | 3.98008 | false | false | false | false |
chrsep/Kingfish
|
app/src/main/java/com/directdev/portal/models/ExamModel.kt
|
1
|
1049
|
package com.directdev.portal.models
import com.squareup.moshi.Json
import io.realm.RealmObject
open class ExamModel(
@Json(name = "CLASS_SECTION")
open var classId: String = "N/A", //"LB02"
@Json(name = "COURSE_TITLE_LONG")
open var courseName: String = "N/A", //"Character Building: Agama"
@Json(name = "ChairNumber")
open var chairNumber: String = "N/A", //"2"
@Json(name = "DESCR")
open var examType: String = "N/A", //"Final Exam"
@Json(name = "Duration")
open var duration: String = "N/A", //"90"
@Json(name = "ExamDate")
open var date: String = "N/A", //"2016-02-05"
@Json(name = "ExamShift")
open var shift: String = "N/A", //"08:00 - 09:30"
@Json(name = "KDMTK")
open var courseId: String = "N/A", //"CHAR6015"
@Json(name = "ROOM")
open var room: String = "N/A", //"ASA1601"
@Json(name = "elig")
open var eligibility: String = "N/A" //"Eligible"
) : RealmObject() {
}
|
gpl-3.0
|
bb9326c2240d4973bc295c0af06975ed
| 26.631579 | 74 | 0.547188 | 3.278125 | false | false | false | false |
christophpickl/gadsu
|
src/main/kotlin/at/cpickl/gadsu/client/view/detail/tab_assist.kt
|
1
|
3598
|
package at.cpickl.gadsu.client.view.detail
import at.cpickl.gadsu.global.UserEvent
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.CurrentClient
import at.cpickl.gadsu.client.forClient
import at.cpickl.gadsu.service.CurrentEvent
import at.cpickl.gadsu.service.Logged
import at.cpickl.gadsu.tcm.patho.SyndromeGuesser
import at.cpickl.gadsu.tcm.patho.SyndromeReport
import at.cpickl.gadsu.treatment.TreatmentService
import at.cpickl.gadsu.view.ViewNames
import at.cpickl.gadsu.view.components.EventButton
import at.cpickl.gadsu.view.components.inputs.HtmlEditorPane
import at.cpickl.gadsu.view.language.Labels
import at.cpickl.gadsu.view.swing.noBorder
import at.cpickl.gadsu.view.swing.scrolled
import at.cpickl.gadsu.view.swing.transparent
import com.google.common.eventbus.EventBus
import com.google.common.eventbus.Subscribe
import com.google.inject.Inject
import java.awt.GridBagConstraints
// future:
// - analyze treatment data
// - maybe some stats (not really assisting, but general info)
object RecalculateAssistentEvent : UserEvent()
class ClientTabAssist @Inject constructor(
bus: EventBus
) : DefaultClientTab(
tabTitle = Labels.Tabs.ClientAssist,
type = ClientTabType.ASSIST
) {
private val textOutput = HtmlEditorPane()
init {
c.fill = GridBagConstraints.BOTH
c.weightx = 1.0
c.weighty = 1.0
add(textOutput.scrolled().transparent().noBorder().apply { viewport.transparent() }, c)
c.gridy++
c.anchor = GridBagConstraints.EAST
c.fill = GridBagConstraints.NONE
c.weightx = 0.0
c.weighty = 0.0
add(EventButton("Neu berechnen", ViewNames.Assistent.ButtonRecalculate, { RecalculateAssistentEvent }, bus), c)
}
fun updateReport(client: Client, report: SyndromeReport) {
textOutput.text = """
|<h1>Assistenz-Bericht für ${client.preferredName}</h1>
|<h2>Klienten Symptome</h2>
|<p>${
if (client.cprops.isEmpty()) "<i>Keine eingetragen.</i>"
else client.cprops.map { it.clientValue.map { it.label }.sorted().joinToString() }.joinToString()
}</p>
|
|<h2>Vermutete Disharmoniemuster:</h2>
|${report.asHtml}
""".trimMargin()
}
override fun isModified(client: Client) = false
override fun updateFields(client: Client) {}
}
@Logged
open class AssistentController @Inject constructor(
private val currentClient: CurrentClient,
private val view: ClientTabAssist,
private val treatmentService: TreatmentService
) {
private val guesser = SyndromeGuesser()
private var recentReport: SyndromeReport? = null
@Subscribe open fun onRecalculateAssistentEvent(event: RecalculateAssistentEvent) {
recalculateAndUpdateView()
}
@Subscribe open fun onClientTabSelected(event: ClientTabSelected) {
if (event.tab.type == ClientTabType.ASSIST && recentReport == null) {
recalculateAndUpdateView()
}
}
@Subscribe open fun onCurrentEvent(event: CurrentEvent) {
event.forClient { recalculateAndUpdateView() }
}
private fun recalculateAndUpdateView() {
val client = currentClient.data
if (!client.yetPersisted) {
view.updateReport(client, SyndromeReport.empty)
recentReport = null
return
}
val treatments = treatmentService.findAllFor(client)
recentReport = guesser.guess(client, treatments)
view.updateReport(client, recentReport!!)
}
}
|
apache-2.0
|
a3dbc9acabb9222b392c6d974e053807
| 31.709091 | 119 | 0.694553 | 3.949506 | false | false | false | false |
jitsi/jitsi-videobridge
|
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/StreamInformation.kt
|
1
|
8368
|
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.util
import org.jitsi.nlj.format.PayloadType
import org.jitsi.nlj.format.supportsPli
import org.jitsi.nlj.format.supportsRemb
import org.jitsi.nlj.format.supportsTcc
import org.jitsi.nlj.rtp.RtpExtension
import org.jitsi.nlj.rtp.RtpExtensionType
import org.jitsi.nlj.rtp.SsrcAssociationType
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.transform.NodeStatsProducer
import org.jitsi.utils.MediaType
import java.util.Collections
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
/**
* A handler installed on a specific [RtpExtensionType] to be notified
* when that type is mapped to an id. A null id value indicates the
* extension mapping has been removed
*/
typealias RtpExtensionHandler = (Int?) -> Unit
typealias RtpPayloadTypesChangedHandler = (Map<Byte, PayloadType>) -> Unit
/**
* Makes information about stream metadata (RTP extensions, payload types,
* etc.) available and allows interested parties to add handlers for when certain
* information is available.
*/
interface ReadOnlyStreamInformationStore : NodeStatsProducer {
val rtpExtensions: List<RtpExtension>
fun onRtpExtensionMapping(rtpExtensionType: RtpExtensionType, handler: RtpExtensionHandler)
val rtpPayloadTypes: Map<Byte, PayloadType>
fun onRtpPayloadTypesChanged(handler: RtpPayloadTypesChangedHandler)
fun getLocalPrimarySsrc(secondarySsrc: Long): Long?
fun getRemoteSecondarySsrc(primarySsrc: Long, associationType: SsrcAssociationType): Long?
/**
* All signaled receive SSRCs
*/
val receiveSsrcs: Set<Long>
/**
* A list of all primary media (audio and video) SSRCs for which the
* endpoint associated with this stream information store sends video
* (does not include things like RTX)
*/
val primaryMediaSsrcs: Set<Long>
val supportsPli: Boolean
val supportsFir: Boolean
val supportsRemb: Boolean
val supportsTcc: Boolean
}
/**
* A writable stream information store
*/
interface StreamInformationStore : ReadOnlyStreamInformationStore {
fun addRtpExtensionMapping(rtpExtension: RtpExtension)
fun clearRtpExtensions()
fun addRtpPayloadType(payloadType: PayloadType)
fun clearRtpPayloadTypes()
fun addSsrcAssociation(ssrcAssociation: SsrcAssociation)
fun addReceiveSsrc(ssrc: Long, mediaType: MediaType)
fun removeReceiveSsrc(ssrc: Long)
}
class StreamInformationStoreImpl : StreamInformationStore {
private val extensionsLock = Any()
private val extensionHandlers =
mutableMapOf<RtpExtensionType, MutableList<RtpExtensionHandler>>()
private val _rtpExtensions: MutableList<RtpExtension> = CopyOnWriteArrayList()
override val rtpExtensions: List<RtpExtension>
get() = _rtpExtensions
private val payloadTypesLock = Any()
private val payloadTypeHandlers = mutableListOf<RtpPayloadTypesChangedHandler>()
private val _rtpPayloadTypes: MutableMap<Byte, PayloadType> = ConcurrentHashMap()
override val rtpPayloadTypes: Map<Byte, PayloadType> = Collections.unmodifiableMap(_rtpPayloadTypes)
private val localSsrcAssociations = SsrcAssociationStore("Local SSRC Associations")
private val remoteSsrcAssociations = SsrcAssociationStore("Remote SSRC Associations")
private val receiveSsrcStore = ReceiveSsrcStore(localSsrcAssociations)
override val receiveSsrcs: Set<Long>
get() = receiveSsrcStore.receiveSsrcs
override val primaryMediaSsrcs: Set<Long>
get() = receiveSsrcStore.primaryMediaSsrcs
// Support for FIR, PLI, REMB and TCC is declared per-payload type, but currently our code is not payload-type
// aware. So until this changes we will just check if any of the PTs supports the relevant feedback.
// We always assume support for FIR.
override var supportsFir: Boolean = true
private set
override var supportsPli: Boolean = false
private set
override var supportsRemb: Boolean = false
private set
override var supportsTcc: Boolean = false
private set
override fun addRtpExtensionMapping(rtpExtension: RtpExtension) {
synchronized(extensionsLock) {
_rtpExtensions.add(rtpExtension)
extensionHandlers.get(rtpExtension.type)?.forEach { it(rtpExtension.id.toInt()) }
}
}
override fun clearRtpExtensions() {
synchronized(extensionsLock) {
_rtpExtensions.clear()
extensionHandlers.values.forEach { handlers -> handlers.forEach { it(null) } }
}
}
override fun onRtpExtensionMapping(rtpExtensionType: RtpExtensionType, handler: RtpExtensionHandler) {
synchronized(extensionsLock) {
extensionHandlers.getOrPut(rtpExtensionType, { mutableListOf() }).add(handler)
_rtpExtensions.find { it.type == rtpExtensionType }?.let { handler(it.id.toInt()) }
}
}
override fun addRtpPayloadType(payloadType: PayloadType) {
synchronized(payloadTypesLock) {
_rtpPayloadTypes[payloadType.pt] = payloadType
supportsPli = rtpPayloadTypes.values.find { it.rtcpFeedbackSet.supportsPli() } != null
supportsRemb = rtpPayloadTypes.values.find { it.rtcpFeedbackSet.supportsRemb() } != null
supportsTcc = rtpPayloadTypes.values.find { it.rtcpFeedbackSet.supportsTcc() } != null
payloadTypeHandlers.forEach { it(_rtpPayloadTypes) }
}
}
override fun clearRtpPayloadTypes() {
synchronized(payloadTypesLock) {
_rtpPayloadTypes.clear()
supportsPli = false
supportsRemb = false
supportsTcc = false
payloadTypeHandlers.forEach { it(_rtpPayloadTypes) }
}
}
override fun onRtpPayloadTypesChanged(handler: RtpPayloadTypesChangedHandler) {
synchronized(payloadTypesLock) {
payloadTypeHandlers.add(handler)
handler(_rtpPayloadTypes)
}
}
// NOTE(brian): Currently, we only have a use case to do a mapping of
// secondary -> primary for local SSRCs and primary -> secondary for
// remote SSRCs
override fun getLocalPrimarySsrc(secondarySsrc: Long): Long? =
localSsrcAssociations.getPrimarySsrc(secondarySsrc)
override fun getRemoteSecondarySsrc(primarySsrc: Long, associationType: SsrcAssociationType): Long? =
remoteSsrcAssociations.getSecondarySsrc(primarySsrc, associationType)
override fun addSsrcAssociation(ssrcAssociation: SsrcAssociation) {
when (ssrcAssociation) {
is LocalSsrcAssociation -> localSsrcAssociations.addAssociation(ssrcAssociation)
is RemoteSsrcAssociation -> remoteSsrcAssociations.addAssociation(ssrcAssociation)
}
}
override fun addReceiveSsrc(ssrc: Long, mediaType: MediaType) =
receiveSsrcStore.addReceiveSsrc(ssrc, mediaType)
override fun removeReceiveSsrc(ssrc: Long) =
receiveSsrcStore.removeReceiveSsrc(ssrc)
override fun getNodeStats(): NodeStatsBlock = NodeStatsBlock("Stream Information Store").apply {
addBlock(
NodeStatsBlock("RTP Extensions").apply {
rtpExtensions.forEach { addString(it.id.toString(), it.type.toString()) }
}
)
addBlock(
NodeStatsBlock("RTP Payload Types").apply {
rtpPayloadTypes.forEach { addString(it.key.toString(), it.value.toString()) }
}
)
addBlock(localSsrcAssociations.getNodeStats())
addBlock(remoteSsrcAssociations.getNodeStats())
addBlock(receiveSsrcStore.getNodeStats())
addBoolean("supports_pli", supportsPli)
addBoolean("supports_fir", supportsFir)
}
}
|
apache-2.0
|
63a29f3c1c5fd34aa1675968db96891d
| 37.92093 | 114 | 0.719646 | 4.533044 | false | false | false | false |
jaychang0917/SimpleApiClient
|
library/src/main/java/com/jaychang/sac/SimpleExtension.kt
|
1
|
8775
|
@file:JvmName("SimpleApiClientEx")
package com.jaychang.sac
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleOwner
import com.jaychang.sac.util.Utils
import com.trello.rxlifecycle2.android.lifecycle.kotlin.bindToLifecycle
import com.trello.rxlifecycle2.android.lifecycle.kotlin.bindUntilEvent
import io.reactivex.*
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Action
import io.reactivex.functions.BiFunction
import io.reactivex.functions.Consumer
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.reactivestreams.Publisher
import java.io.File
import java.util.concurrent.TimeUnit
fun <T, R> Observable<T>.then(mapper: (T) -> ObservableSource<R>): Observable<R> {
return flatMap(mapper)
}
fun <T, R> Flowable<T>.then(mapper: (T) -> Publisher<R>): Flowable<R> {
return flatMap(mapper)
}
fun <T, R> Single<T>.then(mapper: (T) -> SingleSource<R>): Single<R> {
return flatMap(mapper)
}
fun <T, R> Maybe<T>.then(mapper: (T) -> MaybeSource<R>): Maybe<R> {
return flatMap(mapper)
}
fun <T> Observable<T>.thenAll(vararg calls: ObservableSource<*>): Observable<Array<Any>> {
return flatMap {
Observable.zip(calls.asIterable(), { objects -> objects })
}
}
fun <T> Flowable<T>.thenAll(vararg calls: Publisher<*>): Flowable<Array<Any>> {
return flatMap {
Flowable.zip(calls.asIterable(), { objects -> objects })
}
}
fun <T> Single<T>.thenAll(vararg calls: SingleSource<*>): Single<Array<Any>> {
return flatMap {
Single.zip(calls.asIterable(), { objects -> objects })
}
}
fun <T> Maybe<T>.thenAll(vararg calls: MaybeSource<*>): Maybe<Array<Any>> {
return flatMap {
Maybe.zip(calls.asIterable(), { objects -> objects })
}
}
fun <T> Observable<T>.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Observable<T> {
return retryWhen { error ->
error
.zipWith(Observable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Observable.error(pair.first)
} else {
Observable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
}
}
}
}
fun <T> Flowable<T>.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Flowable<T> {
return retryWhen { error ->
error
.zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Flowable.error(pair.first)
} else {
Flowable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
}
}
}
}
fun <T> Single<T>.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Single<T> {
return retryWhen { error ->
error
.zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Flowable.error(pair.first)
} else {
Flowable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
}
}
}
}
fun <T> Maybe<T>.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Maybe<T> {
return retryWhen { error ->
error
.zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Flowable.error(pair.first)
} else {
Flowable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
}
}
}
}
fun <T> Observable<T>.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Observable<T> {
return retryWhen { error ->
error
.zipWith(Observable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Observable.error(pair.first)
} else {
Observable.timer(delaySeconds, TimeUnit.SECONDS)
}
}
}
}
fun <T> Flowable<T>.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Flowable<T> {
return retryWhen { error ->
error
.zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Flowable.error(pair.first)
} else {
Flowable.timer(delaySeconds, TimeUnit.SECONDS)
}
}
}
}
fun <T> Single<T>.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Single<T> {
return retryWhen { error ->
error
.zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Flowable.error(pair.first)
} else {
Flowable.timer(delaySeconds, TimeUnit.SECONDS)
}
}
}
}
fun <T> Maybe<T>.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Maybe<T> {
return retryWhen { error ->
error
.zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
.flatMap { pair ->
if (pair.second == maxRetryCount + 1) {
Flowable.error(pair.first)
} else {
Flowable.timer(delaySeconds, TimeUnit.SECONDS)
}
}
}
}
fun <T> Observable<T>.autoCancel(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Observable<T> {
return if (untilEvent != null) {
bindUntilEvent(lifecycleOwner, untilEvent)
} else {
bindToLifecycle(lifecycleOwner)
}
}
fun <T> Flowable<T>.autoCancel(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Flowable<T> {
return if (untilEvent != null) {
bindUntilEvent(lifecycleOwner, untilEvent)
} else {
bindToLifecycle(lifecycleOwner)
}
}
fun <T> Single<T>.autoDispose(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Single<T> {
return if (untilEvent != null) {
bindUntilEvent(lifecycleOwner, untilEvent)
} else {
bindToLifecycle(lifecycleOwner)
}
}
fun <T> Maybe<T>.autoDispose(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Maybe<T> {
return if (untilEvent != null) {
bindUntilEvent(lifecycleOwner, untilEvent)
} else {
bindToLifecycle(lifecycleOwner)
}
}
fun Completable.autoDispose(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Completable {
return if (untilEvent != null) {
bindUntilEvent(lifecycleOwner, untilEvent)
} else {
bindToLifecycle(lifecycleOwner)
}
}
fun <T> Observable<T>.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return doOnSubscribe { onStart() }.doFinally { onEnd() }
.subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
}
fun <T> Flowable<T>.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return doOnSubscribe { onStart() }.doFinally { onEnd() }
.subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
}
fun <T> Single<T>.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return doOnSubscribe { onStart() }.doFinally { onEnd() }
.subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
}
fun <T> Maybe<T>.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return doOnSubscribe { onStart() }.doFinally { onEnd() }
.subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
}
fun Completable.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: () -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return doOnSubscribe { onStart() }.doFinally { onEnd() }
.subscribe(Action { onSuccess() }, ErrorConsumer(onError))
}
fun File.toMultipartBodyPart(paramName: String, mimeType: String = Utils.getMimeType(this)) {
MultipartBody.Part.createFormData(paramName, name, RequestBody.create(MediaType.parse(mimeType), this))
}
|
apache-2.0
|
075fc9878c6eb166c18c4f761bbb293c
| 34.674797 | 157 | 0.660855 | 3.795415 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleSolarMirror.kt
|
2
|
2723
|
package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.misc.add
import com.cout970.magneticraft.misc.getBlockPos
import com.cout970.magneticraft.misc.newNbt
import com.cout970.magneticraft.misc.tileentity.getModule
import com.cout970.magneticraft.misc.tileentity.shouldTick
import com.cout970.magneticraft.misc.vector.plus
import com.cout970.magneticraft.misc.vector.toBlockPos
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.BlockPos
class ModuleSolarMirror(
val facingGetter: () -> EnumFacing,
val active: () -> Boolean,
override val name: String = "module_solar_mirror"
) : IModule {
override lateinit var container: IModuleContainer
companion object {
// Only send heat every 20 ticks to reduce lag
const val TICKS_BETWEEN_OPERATIONS = 20
}
var solarTowerPos: BlockPos? = null
var solarTowerTilePos: BlockPos? = null
val mirrorPos: BlockPos get() = pos + facingGetter().toBlockPos()
// rendering data
var angleX = 0f
var angleY = 0f
var deltaTime = System.currentTimeMillis()
override fun update() {
if (world.isClient) return
if (!world.isDaytime || !active()) return
if (container.shouldTick(TICKS_BETWEEN_OPERATIONS)) {
solarTowerTilePos?.let { pos ->
val mod = world.getModule<ModuleSolarTower>(pos)
if (mod == null || !mod.active()) {
clearTargetTower()
} else {
mod.applyHeat(Config.solarMirrorHeatProduction.toFloat() * TICKS_BETWEEN_OPERATIONS)
}
}
}
}
fun setTargetTower(center: BlockPos, tilePos: BlockPos) {
solarTowerPos = center
solarTowerTilePos = tilePos
container.sendUpdateToNearPlayers()
}
fun clearTargetTower() {
solarTowerTilePos = null
solarTowerPos = null
container.sendUpdateToNearPlayers()
}
override fun deserializeNBT(nbt: NBTTagCompound) {
solarTowerPos = if (nbt.hasKey("towerPos")) nbt.getBlockPos("towerPos") else null
solarTowerTilePos = if (nbt.hasKey("towerTilePos")) nbt.getBlockPos("towerTilePos") else null
}
override fun serializeNBT(): NBTTagCompound {
return newNbt {
solarTowerPos?.let { add("towerPos", it) }
solarTowerTilePos?.let { add("towerTilePos", it) }
}
}
}
|
gpl-2.0
|
d537695fbac56275aee4456ff03d92d3
| 33.05 | 104 | 0.683805 | 4.182796 | false | false | false | false |
f-droid/fdroidclient
|
libs/index/src/androidMain/kotlin/org/fdroid/LocaleChooser.kt
|
1
|
1871
|
package org.fdroid
import androidx.core.os.LocaleListCompat
import org.fdroid.index.v2.LocalizedFileListV2
import org.fdroid.index.v2.LocalizedFileV2
import org.fdroid.index.v2.LocalizedTextV2
public object LocaleChooser {
/**
* Gets the best localization for the given [localeList]
* from collections like [LocalizedTextV2], [LocalizedFileV2], or [LocalizedFileListV2].
*/
public fun <T> Map<String, T>?.getBestLocale(localeList: LocaleListCompat): T? {
if (isNullOrEmpty()) return null
val firstMatch = localeList.getFirstMatch(keys.toTypedArray()) ?: return null
val tag = firstMatch.toLanguageTag()
// try first matched tag first (usually has region tag, e.g. de-DE)
return get(tag) ?: run {
// split away stuff like script and try language and region only
val langCountryTag = "${firstMatch.language}-${firstMatch.country}"
getOrStartsWith(langCountryTag) ?: run {
// split away region tag and try language only
val langTag = firstMatch.language
// try language, then English and then just take the first of the list
getOrStartsWith(langTag) ?: get("en-US") ?: get("en") ?: values.first()
}
}
}
/**
* Returns the value from the map with the given key or if that key is not contained in the map,
* tries the first map key that starts with the given key.
* If nothing matches, null is returned.
*
* This is useful when looking for a language tag like `fr_CH` and falling back to `fr`
* in a map that has `fr_FR` as a key.
*/
private fun <T> Map<String, T>.getOrStartsWith(s: String): T? = get(s) ?: run {
entries.forEach { (key, value) ->
if (key.startsWith(s)) return value
}
return null
}
}
|
gpl-3.0
|
b7c810299567733c616184131144f789
| 39.673913 | 100 | 0.63442 | 4.185682 | false | false | false | false |
robinverduijn/gradle
|
subprojects/instant-execution/src/test/kotlin/org/gradle/instantexecution/serialization/codecs/UserTypesCodecTest.kt
|
1
|
9755
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization.codecs
import com.nhaarman.mockitokotlin2.mock
import org.gradle.api.Project
import org.gradle.cache.internal.TestCrossBuildInMemoryCacheFactory
import org.gradle.instantexecution.extensions.uncheckedCast
import org.gradle.instantexecution.runToCompletion
import org.gradle.instantexecution.serialization.DefaultReadContext
import org.gradle.instantexecution.serialization.DefaultWriteContext
import org.gradle.instantexecution.serialization.IsolateOwner
import org.gradle.instantexecution.serialization.MutableIsolateContext
import org.gradle.instantexecution.serialization.PropertyProblem
import org.gradle.instantexecution.serialization.beans.BeanConstructors
import org.gradle.instantexecution.serialization.withIsolate
import org.gradle.internal.io.NullOutputStream
import org.gradle.internal.serialize.Encoder
import org.gradle.internal.serialize.kryo.KryoBackedDecoder
import org.gradle.internal.serialize.kryo.KryoBackedEncoder
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.sameInstance
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.OutputStream
import java.io.Serializable
class UserTypesCodecTest {
@Test
fun `can handle deeply nested graphs`() {
val deepGraph = Peano.fromInt(1024)
val read = roundtrip(deepGraph)
assertThat(
read.toInt(),
equalTo(deepGraph.toInt())
)
}
@Test
fun `can handle mix of Serializable and plain beans`() {
val bean = Pair(42, "42")
/**
* A [Serializable] object that holds a reference to a plain bean.
**/
val serializable = SerializableWriteObjectBean(bean)
/**
* A plain bean that holds a reference to a serializable object
* sharing a reference to another plain bean.
**/
val beanGraph = Pair(serializable, bean)
val decodedGraph = roundtrip(beanGraph)
val (decodedSerializable, decodedBean) = decodedGraph
assertThat(
"defaultWriteObject / defaultReadObject handles non-transient fields",
decodedSerializable.value,
equalTo(serializable.value)
)
assertThat(
decodedSerializable.transientInt,
equalTo(SerializableWriteObjectBean.EXPECTED_INT)
)
assertThat(
decodedSerializable.transientString,
equalTo(SerializableWriteObjectBean.EXPECTED_STRING)
)
assertThat(
"preserves identities across protocols",
decodedSerializable.value,
sameInstance<Any>(decodedBean)
)
}
@Test
fun `can handle Serializable writeReplace readResolve`() {
assertThat(
roundtrip(SerializableWriteReplaceBean()).value,
equalTo<Any>("42")
)
}
@Test
fun `preserves identity of Serializable objects`() {
val writeReplaceBean = SerializableWriteReplaceBean()
val writeObjectBean = SerializableWriteObjectBean(Pair(writeReplaceBean, writeReplaceBean))
val graph = Pair(writeObjectBean, writeObjectBean)
val decodedGraph = roundtrip(graph)
assertThat(
decodedGraph.first,
sameInstance(decodedGraph.second)
)
val decodedPair = decodedGraph.first.value as Pair<*, *>
assertThat(
decodedPair.first,
sameInstance(decodedPair.second)
)
}
@Test
fun `leaves bean trace of Serializable objects`() {
val bean = SerializableWriteObjectBean(mock<Project>())
val problems = serializationProblemsOf(bean)
assertThat(
problems.single().trace.toString(),
equalTo(
"field `value` of `${bean.javaClass.name}` bean found in unknown property"
)
)
}
private
fun serializationProblemsOf(bean: Any): List<PropertyProblem> =
mutableListOf<PropertyProblem>().also { problems ->
writeTo(
NullOutputStream.INSTANCE,
bean
) { problems += it }
}
class SerializableWriteReplaceBean(val value: Any? = null) : Serializable {
@Suppress("unused")
private
fun writeReplace() = Memento()
private
class Memento {
@Suppress("unused")
fun readResolve() = SerializableWriteReplaceBean("42")
}
}
class SerializableWriteObjectBean(val value: Any) : Serializable {
companion object {
const val EXPECTED_INT: Int = 42
const val EXPECTED_STRING: String = "42"
}
@Transient
var transientInt: Int? = null
@Transient
var transientString: String? = null
private
fun writeObject(objectOutputStream: ObjectOutputStream) {
objectOutputStream.run {
defaultWriteObject()
writeInt(EXPECTED_INT)
writeUTF(EXPECTED_STRING)
}
}
private
fun readObject(objectInputStream: ObjectInputStream) {
objectInputStream.defaultReadObject()
transientInt = objectInputStream.readInt()
transientString = objectInputStream.readUTF()
}
}
private
fun <T : Any> roundtrip(graph: T): T =
writeToByteArray(graph)
.let(::readFromByteArray)!!
.uncheckedCast()
private
fun writeToByteArray(graph: Any): ByteArray {
val outputStream = ByteArrayOutputStream()
writeTo(outputStream, graph)
return outputStream.toByteArray()
}
private
fun writeTo(
outputStream: OutputStream,
graph: Any,
problemHandler: (PropertyProblem) -> Unit = mock()
) {
KryoBackedEncoder(outputStream).use { encoder ->
writeContextFor(encoder, problemHandler).run {
withIsolateMock {
runToCompletion {
write(graph)
}
}
}
}
}
private
fun readFromByteArray(bytes: ByteArray) =
readFrom(ByteArrayInputStream(bytes))
private
fun readFrom(inputStream: ByteArrayInputStream) =
readContextFor(inputStream).run {
initClassLoader(javaClass.classLoader)
withIsolateMock {
runToCompletion {
read()
}
}
}
private
inline fun <R> MutableIsolateContext.withIsolateMock(block: () -> R): R =
withIsolate(IsolateOwner.OwnerGradle(mock()), codecs().userTypesCodec) {
block()
}
private
fun writeContextFor(encoder: Encoder, problemHandler: (PropertyProblem) -> Unit) =
DefaultWriteContext(
codec = codecs().userTypesCodec,
encoder = encoder,
scopeLookup = mock(),
logger = mock(),
problemHandler = problemHandler
)
private
fun readContextFor(inputStream: ByteArrayInputStream) =
DefaultReadContext(
codec = codecs().userTypesCodec,
decoder = KryoBackedDecoder(inputStream),
constructors = BeanConstructors(TestCrossBuildInMemoryCacheFactory()),
logger = mock()
)
private
fun codecs() = Codecs(
directoryFileTreeFactory = mock(),
fileCollectionFactory = mock(),
fileLookup = mock(),
filePropertyFactory = mock(),
fileResolver = mock(),
instantiator = mock(),
listenerManager = mock(),
projectStateRegistry = mock(),
taskNodeFactory = mock(),
fingerprinterRegistry = mock(),
classLoaderHierarchyHasher = mock(),
buildOperationExecutor = mock(),
isolatableFactory = mock(),
valueSnapshotter = mock(),
fileCollectionFingerprinterRegistry = mock(),
isolatableSerializerRegistry = mock(),
projectFinder = mock(),
parameterScheme = mock(),
actionScheme = mock(),
attributesFactory = mock(),
transformListener = mock()
)
@Test
fun `Peano sanity check`() {
assertThat(
Peano.fromInt(0),
equalTo<Peano>(Peano.Zero)
)
assertThat(
Peano.fromInt(1024).toInt(),
equalTo(1024)
)
}
sealed class Peano {
companion object {
fun fromInt(n: Int): Peano = (0 until n).fold(Zero as Peano) { acc, _ -> Succ(acc) }
}
fun toInt(): Int = sequence().count() - 1
object Zero : Peano()
data class Succ(val n: Peano) : Peano()
private
fun sequence() = generateSequence(this) { previous ->
when (previous) {
is Zero -> null
is Succ -> previous.n
}
}
}
}
|
apache-2.0
|
f650c775a676bb38fc8c5c4cd0a1d4f5
| 28.119403 | 99 | 0.622963 | 5.134211 | false | false | false | false |
anton-okolelov/intellij-rust
|
src/main/kotlin/org/rust/cargo/toolchain/CargoCommandLine.kt
|
1
|
3009
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain
import com.intellij.execution.configuration.EnvironmentVariablesData
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.runconfig.command.workingDirectory
import java.nio.file.Path
data class CargoCommandLine(
val command: String, // Can't be `enum` because of custom subcommands
val workingDirectory: Path, // Note that working directory selects Cargo project as well
val additionalArguments: List<String> = emptyList(),
val backtraceMode: BacktraceMode = BacktraceMode.DEFAULT,
val channel: RustChannel = RustChannel.DEFAULT,
val environmentVariables: EnvironmentVariablesData = EnvironmentVariablesData.DEFAULT,
val nocapture: Boolean = true
) {
fun withDoubleDashFlag(arg: String): CargoCommandLine {
val (pre, post) = splitOnDoubleDash()
if (arg in post) return this
return copy(additionalArguments = pre + "--" + arg + post)
}
/**
* Splits [additionalArguments] into parts before and after `--`.
* For `cargo run --release -- foo bar`, returns (["--release"], ["foo", "bar"])
*/
fun splitOnDoubleDash(): Pair<List<String>, List<String>> {
val idx = additionalArguments.indexOf("--")
if (idx == -1) return additionalArguments to emptyList()
return additionalArguments.take(idx) to additionalArguments.drop(idx + 1)
}
companion object {
fun forTarget(
target: CargoWorkspace.Target,
command: String,
additionalArguments: List<String> = emptyList()
): CargoCommandLine {
val targetArgs = when (target.kind) {
CargoWorkspace.TargetKind.BIN -> listOf("--bin", target.name)
CargoWorkspace.TargetKind.TEST -> listOf("--test", target.name)
CargoWorkspace.TargetKind.EXAMPLE -> listOf("--example", target.name)
CargoWorkspace.TargetKind.BENCH -> listOf("--bench", target.name)
CargoWorkspace.TargetKind.LIB -> listOf("--lib")
CargoWorkspace.TargetKind.UNKNOWN -> emptyList()
}
return CargoCommandLine(
command,
workingDirectory = target.pkg.workspace.manifestPath.parent,
additionalArguments = listOf("--package", target.pkg.name) + targetArgs + additionalArguments
)
}
fun forProject(
cargoProject: CargoProject,
command: String,
additionalArguments: List<String> = emptyList(),
channel: RustChannel = RustChannel.DEFAULT
): CargoCommandLine {
return CargoCommandLine(
command,
cargoProject.workingDirectory,
additionalArguments,
channel = channel
)
}
}
}
|
mit
|
e45dfc41eda026dbbd1d6bed8419b250
| 38.077922 | 109 | 0.636424 | 5.074199 | false | false | false | false |
moezbhatti/qksms
|
data/src/main/java/com/moez/QKSMS/mapper/RatingManagerImpl.kt
|
3
|
1975
|
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.mapper
import com.f2prateek.rx.preferences2.RxSharedPreferences
import com.moez.QKSMS.manager.AnalyticsManager
import com.moez.QKSMS.manager.RatingManager
import io.reactivex.rxkotlin.Observables
import javax.inject.Inject
class RatingManagerImpl @Inject constructor(
rxPrefs: RxSharedPreferences,
private val analyticsManager: AnalyticsManager
) : RatingManager {
companion object {
private const val RATING_THRESHOLD = 10
}
private val sessions = rxPrefs.getInteger("sessions", 0)
private val rated = rxPrefs.getBoolean("rated", false)
private val dismissed = rxPrefs.getBoolean("dismissed", false)
override val shouldShowRating = Observables.combineLatest(
sessions.asObservable(),
rated.asObservable(),
dismissed.asObservable()
) { sessions, rated, dismissed ->
sessions > RATING_THRESHOLD && !rated && !dismissed
}
override fun addSession() {
sessions.set(sessions.get() + 1)
}
override fun rate() {
analyticsManager.track("Clicked Rate")
rated.set(true)
}
override fun dismiss() {
analyticsManager.track("Clicked Rate (Dismiss)")
dismissed.set(true)
}
}
|
gpl-3.0
|
905285598071f24f64534cac23149cea
| 30.854839 | 71 | 0.70481 | 4.408482 | false | false | false | false |
google/horologist
|
media-ui/src/debug/java/com/google/android/horologist/media/ui/screens/entity/EntityScreenPreview.kt
|
1
|
7457
|
/*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.screens.entity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.PlaylistPlay
import androidx.compose.material.icons.filled.Shuffle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.rememberScalingLazyListState
import com.google.android.horologist.base.ui.components.StandardButton
import com.google.android.horologist.base.ui.components.StandardChip
import com.google.android.horologist.composables.PlaceholderChip
import com.google.android.horologist.compose.tools.WearPreviewDevices
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
@WearPreviewDevices
@Composable
fun EntityScreenPreview() {
EntityScreen(
headerContent = {
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(
Brush.radialGradient(
listOf(
(Color.Green).copy(alpha = 0.3f),
Color.Transparent
)
)
),
contentAlignment = Alignment.Center
) {
Text("Playlist name")
}
},
scalingLazyListState = rememberScalingLazyListState(),
buttonsContent = {
Row(
modifier = Modifier
.padding(bottom = 16.dp)
.height(52.dp),
verticalAlignment = Alignment.CenterVertically
) {
StandardButton(
imageVector = Icons.Default.Favorite,
contentDescription = "Favorite",
onClick = { },
modifier = Modifier
.padding(start = 6.dp)
.weight(weight = 0.3F, fill = false)
)
StandardButton(
imageVector = Icons.Default.PlaylistPlay,
contentDescription = "Play",
onClick = { },
modifier = Modifier
.padding(start = 6.dp)
.weight(weight = 0.3F, fill = false)
)
}
},
content = {
item { StandardChip(label = "Song 1", onClick = { }) }
item { StandardChip(label = "Song 2", onClick = { }) }
}
)
}
@WearPreviewDevices
@Composable
fun EntityScreenPreviewLoadedState() {
EntityScreen(
entityScreenState = EntityScreenState.Loaded(listOf("Song 1", "Song 2")),
headerContent = { DefaultEntityScreenHeader(title = "Playlist name") },
loadingContent = { },
mediaContent = { song -> StandardChip(label = song, onClick = { }) },
scalingLazyListState = rememberScalingLazyListState(),
buttonsContent = { ButtonContentForStatePreview() }
)
}
@WearPreviewDevices
@Composable
fun EntityScreenPreviewLoadingState() {
EntityScreen(
entityScreenState = EntityScreenState.Loading<String>(),
headerContent = { DefaultEntityScreenHeader(title = "Playlist name") },
loadingContent = { items(count = 2) { PlaceholderChip(colors = ChipDefaults.secondaryChipColors()) } },
mediaContent = { },
scalingLazyListState = rememberScalingLazyListState(),
buttonsContent = { ButtonContentForStatePreview() }
)
}
@WearPreviewDevices
@Composable
fun EntityScreenPreviewFailedState() {
EntityScreen(
entityScreenState = EntityScreenState.Failed<String>(),
headerContent = { DefaultEntityScreenHeader(title = "Playlist name") },
loadingContent = { },
mediaContent = { },
scalingLazyListState = rememberScalingLazyListState(),
buttonsContent = { ButtonContentForStatePreview() },
failedContent = {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
imageVector = Icons.Default.CloudOff,
contentDescription = null,
modifier = Modifier
.size(24.dp)
.wrapContentSize(align = Alignment.Center)
)
Text(
text = "Could not retrieve the playlist.",
textAlign = TextAlign.Center
)
}
}
)
}
@Composable
private fun ButtonContentForStatePreview() {
Row(
modifier = Modifier
.padding(bottom = 16.dp)
.height(52.dp),
verticalAlignment = Alignment.CenterVertically
) {
StandardButton(
imageVector = Icons.Default.Download,
contentDescription = "Download",
onClick = { },
modifier = Modifier
.padding(start = 6.dp)
.weight(weight = 0.3F, fill = false)
)
StandardButton(
imageVector = Icons.Default.Shuffle,
contentDescription = "Shuffle",
onClick = { },
modifier = Modifier
.padding(start = 6.dp)
.weight(weight = 0.3F, fill = false)
)
StandardButton(
imageVector = Icons.Default.PlayArrow,
contentDescription = "Play",
onClick = { },
modifier = Modifier
.padding(start = 6.dp)
.weight(weight = 0.3F, fill = false)
)
}
}
|
apache-2.0
|
1877219d3fd20b2958273830591e2618
| 35.73399 | 111 | 0.613249 | 5.118051 | false | false | false | false |
Zhuinden/simple-stack
|
samples/legacy-samples/simple-stack-example-multistack-view/src/main/java/com/zhuinden/simplestackdemomultistack/core/navigation/MultistackViewStateChanger.kt
|
1
|
4113
|
package com.zhuinden.simplestackdemomultistack.core.navigation
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.zhuinden.simplestack.Backstack
import com.zhuinden.simplestack.StateChange
import com.zhuinden.simplestack.StateChanger
import com.zhuinden.simplestackdemomultistack.application.MainActivity
import com.zhuinden.simplestackdemomultistack.util.animateTogether
import com.zhuinden.simplestackdemomultistack.util.f
import com.zhuinden.simplestackdemomultistack.util.objectAnimate
import com.zhuinden.simplestackdemomultistack.util.waitForMeasure
class MultistackViewStateChanger(
private val activity: Activity,
private val multistack: Multistack,
private val root: ViewGroup,
private val animationStateListener: AnimationStateListener
) {
interface AnimationStateListener {
fun onAnimationStarted()
fun onAnimationEnded()
}
private fun exchangeViewForKey(stateChange: StateChange, direction: Int, completionCallback: StateChanger.Callback) {
val newKey = stateChange.topNewKey<MultistackViewKey>()
multistack.persistViewToState(root.getChildAt(0))
multistack.setSelectedStack(newKey.stackIdentifier())
val newContext = stateChange.createContext(activity, newKey)
val previousView: View? = root.getChildAt(0)
val newView = LayoutInflater.from(newContext).inflate(newKey.layout(), root, false)
multistack.restoreViewFromState(newView)
root.addView(newView)
if (previousView == null || direction == StateChange.REPLACE) {
finishStateChange(previousView, completionCallback)
} else {
animationStateListener.onAnimationStarted()
newView.waitForMeasure { _, _, _ ->
runAnimation(previousView, newView, direction, object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
animationStateListener.onAnimationEnded()
finishStateChange(previousView, completionCallback)
}
})
}
}
}
fun handleStateChange(stateChange: StateChange, completionCallback: StateChanger.Callback) {
var direction = StateChange.REPLACE
val currentView: View? = root.getChildAt(0)
if (currentView != null) {
val previousKey = Backstack.getKey<MultistackViewKey>(currentView.context)
val previousStack = MainActivity.StackType.valueOf(previousKey.stackIdentifier())
val newStack = MainActivity.StackType.valueOf((stateChange.topNewKey<Any>() as MultistackViewKey).stackIdentifier())
direction = when {
previousStack.ordinal < newStack.ordinal -> StateChange.FORWARD
previousStack.ordinal > newStack.ordinal -> StateChange.BACKWARD
else -> StateChange.REPLACE
}
}
exchangeViewForKey(stateChange, direction, completionCallback)
}
private fun finishStateChange(previousView: View?, completionCallback: StateChanger.Callback) {
if (previousView != null) {
root.removeView(previousView)
}
completionCallback.stateChangeComplete()
}
// animation
private fun runAnimation(previousView: View, newView: View, direction: Int, animatorListenerAdapter: AnimatorListenerAdapter) {
val animator = createSegue(previousView, newView, direction)
animator.addListener(animatorListenerAdapter)
animator.start()
}
private fun createSegue(from: View, to: View, direction: Int): Animator = run {
val fromTranslation = -1 * direction * from.width
val toTranslation = direction * to.width
to.translationX = toTranslation.f
animateTogether(
from.objectAnimate().translationX(fromTranslation.f).get(),
to.objectAnimate().translationX(0.f).get()
)
}
}
|
apache-2.0
|
f8f2326901e6c783f1526dd75cb254e0
| 40.969388 | 131 | 0.70338 | 5.034272 | false | false | false | false |
techlung/wearfaceutils
|
wearfaceutils-sample/src/main/java/com/techlung/wearfaceutils/sample/WearFaceUtilsSampleFace.kt
|
1
|
2179
|
package com.techlung.wearfaceutils.sample
import android.graphics.Canvas
import android.graphics.Rect
import android.support.wearable.watchface.WatchFaceService
import android.view.WindowInsets
import com.techlung.wearfaceutils.WearFaceUtils
import com.techlung.wearfaceutils.sample.generic.BaseWatchFaceService
import com.techlung.wearfaceutils.sample.modules.face.BackgroundPainter
import com.techlung.wearfaceutils.sample.modules.face.ClockworkPainter
class WearFaceUtilsSampleFace : BaseWatchFaceService() {
override fun onCreateEngine(): Engine {
return Engine()
}
inner class Engine : BaseWatchFaceService.BaseWatchFaceEngine() {
private var clockworkPainter: ClockworkPainter = ClockworkPainter()
private var backgroundPainter: BackgroundPainter = BackgroundPainter()
override fun setAmbientMode(isAmbient: Boolean) {
clockworkPainter.setAmbientMode(isAmbient)
backgroundPainter.setAmbientMode(isAmbient)
}
override fun setInsets(insets: WindowInsets) {
WearFaceUtils.init(insets)
}
override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) {
when (tapType) {
WatchFaceService.TAP_TYPE_TOUCH -> {
}
WatchFaceService.TAP_TYPE_TOUCH_CANCEL -> {
}
WatchFaceService.TAP_TYPE_TAP -> {
clockworkPainter.startAnimation()
}
}
invalidate()
}
override fun onDraw(canvas: Canvas?, bounds: Rect?) {
if (canvas == null || bounds == null) {
return
}
val canvasNonNull: Canvas = canvas
val boundsNonNull: Rect = bounds
var continueAnimation = false
continueAnimation = backgroundPainter.onDraw(applicationContext, canvasNonNull, boundsNonNull) || continueAnimation
continueAnimation = clockworkPainter.onDraw(applicationContext, canvasNonNull, boundsNonNull) || continueAnimation
if (continueAnimation) {
invalidate()
}
}
}
}
|
apache-2.0
|
9c32a99532078ec414604118c837b327
| 33.046875 | 127 | 0.651216 | 4.87472 | false | false | false | false |
talhacohen/android
|
app/src/main/java/com/etesync/syncadapter/ui/importlocal/AccountResolver.kt
|
1
|
1831
|
package com.etesync.syncadapter.ui.importlocal
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import com.etesync.syncadapter.App
import com.etesync.syncadapter.R
import java.util.*
internal class AccountResolver(private val context: Context) {
private val cache: HashMap<String, AccountInfo>
init {
this.cache = LinkedHashMap()
}
fun resolve(accountName: String): AccountInfo {
var accountName = accountName
// Hardcoded swaps for known accounts:
if (accountName == "com.google") {
accountName = "com.google.android.googlequicksearchbox"
} else if (accountName == App.addressBookAccountType) {
accountName = App.accountType
} else if (accountName == "at.bitfire.davdroid.address_book") {
accountName = "at.bitfire.davdroid"
}
var ret: AccountInfo? = cache[accountName]
if (ret == null) {
try {
val packageManager = context.packageManager
val applicationInfo = packageManager.getApplicationInfo(accountName, 0)
val name = if (applicationInfo != null) packageManager.getApplicationLabel(applicationInfo).toString() else accountName
val icon = context.packageManager.getApplicationIcon(accountName)
ret = AccountInfo(name, icon)
} catch (e: PackageManager.NameNotFoundException) {
ret = AccountInfo(accountName, ContextCompat.getDrawable(context, R.drawable.ic_account_dark)!!)
}
cache[accountName] = ret!!
}
return ret
}
class AccountInfo internal constructor(internal val name: String, internal val icon: Drawable)
}
|
gpl-3.0
|
c61e14278201f466e3189a4c17aace1e
| 37.145833 | 135 | 0.667941 | 5.016438 | false | false | false | false |
dya-tel/TSU-Schedule
|
src/main/kotlin/ru/dyatel/tsuschedule/MainActivity.kt
|
1
|
15161
|
package ru.dyatel.tsuschedule
import android.app.AlertDialog
import android.app.Dialog
import android.app.NotificationChannel
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.view.ViewCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.SearchView
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import com.mikepenz.community_material_typeface_library.CommunityMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.materialdrawer.Drawer
import com.mikepenz.materialdrawer.DrawerBuilder
import com.mikepenz.materialdrawer.model.DividerDrawerItem
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
import com.wealthfront.magellan.Navigator
import com.wealthfront.magellan.support.SingleActivity
import com.wealthfront.magellan.transitions.NoAnimationTransition
import hirondelle.date4j.DateTime
import kotlinx.coroutines.experimental.launch
import org.jetbrains.anko.ctx
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.editText
import org.jetbrains.anko.find
import org.jetbrains.anko.frameLayout
import org.jetbrains.anko.leftPadding
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.notificationManager
import org.jetbrains.anko.rightPadding
import org.jetbrains.anko.singleLine
import ru.dyatel.tsuschedule.database.database
import ru.dyatel.tsuschedule.events.Event
import ru.dyatel.tsuschedule.events.EventBus
import ru.dyatel.tsuschedule.events.EventListener
import ru.dyatel.tsuschedule.layout.DIM_DIALOG_SIDE_PADDING
import ru.dyatel.tsuschedule.layout.DIM_ELEVATION_F
import ru.dyatel.tsuschedule.model.currentWeekParity
import ru.dyatel.tsuschedule.screens.ExamScheduleScreen
import ru.dyatel.tsuschedule.screens.FilterScreen
import ru.dyatel.tsuschedule.screens.HistoryScreen
import ru.dyatel.tsuschedule.screens.HomeScreen
import ru.dyatel.tsuschedule.screens.PreferenceScreen
import ru.dyatel.tsuschedule.screens.ScheduleScreen
import ru.dyatel.tsuschedule.updater.Updater
import ru.dyatel.tsuschedule.utilities.Validator
import ru.dyatel.tsuschedule.utilities.schedulePreferences
import java.util.TimeZone
private const val SCHEDULE_SCREEN_ID_START = 1000
class MainActivity : SingleActivity(), EventListener {
private lateinit var toolbar: Toolbar
private lateinit var drawer: Drawer
private lateinit var parityItem: PrimaryDrawerItem
private val preferences = schedulePreferences
private val updater by lazy { Updater(this) }
private var selectedGroup: String?
get() {
val id = drawer.currentSelection - SCHEDULE_SCREEN_ID_START
return if (id >= 0) preferences.groups[id.toInt()] else null
}
set(value) {
val id = preferences.groups.indexOf(value) + SCHEDULE_SCREEN_ID_START
drawer.setSelection(id.toLong())
}
private val drawerListener = object : Drawer.OnDrawerListener {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit
override fun onDrawerClosed(drawerView: View) = Unit
override fun onDrawerOpened(drawerView: View) = updateParityItemText()
}
private val historySizeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == getString(R.string.preference_history_size)) {
preferences.groups.forEach {
database.snapshots.removeSurplus(it)
}
}
}
override fun createNavigator() = Navigator
.withRoot(HomeScreen())
.transition(NoAnimationTransition())
.build()!!
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleUpdateNotification(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = notificationManager
val name = getString(R.string.notification_channel_updates_name)
notificationManager.createNotificationChannel(
NotificationChannel(NOTIFICATION_CHANNEL_UPDATES, name, NotificationManagerCompat.IMPORTANCE_LOW)
)
}
updater.handleMigration()
toolbar = find(R.id.toolbar)
setSupportActionBar(toolbar)
drawer = DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withOnDrawerListener(drawerListener)
.withOnDrawerNavigationListener { onBackPressed(); true }
.withSavedInstance(savedInstanceState)
.build()
generateDrawerButtons()
defaultSharedPreferences.registerOnSharedPreferenceChangeListener(historySizeListener)
EventBus.subscribe(
this,
Event.SET_TOOLBAR_SHADOW_ENABLED, Event.SET_DRAWER_ENABLED, Event.ADD_GROUP
)
EventBus.broadcast(Event.SET_TOOLBAR_SHADOW_ENABLED, true)
if (!handleUpdateNotification(intent) && preferences.autoupdate) {
val now = DateTime.now(TimeZone.getDefault())
val scheduled = preferences.lastUpdateCheck?.plusDays(3)
if (scheduled == null || scheduled.lteq(now)) {
launch { updater.fetchUpdate(true) }
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
if (savedInstanceState == null) {
preferences.group?.let { selectedGroup = it }
if (preferences.pendingChangelogDisplay) {
updater.showChangelog()
}
}
}
override fun onDestroy() {
defaultSharedPreferences.unregisterOnSharedPreferenceChangeListener(historySizeListener)
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
menu.findItem(R.id.filters).icon = getActionBarIcon(CommunityMaterial.Icon.cmd_filter)
menu.findItem(R.id.exams).icon = getActionBarIcon(CommunityMaterial.Icon.cmd_calendar)
menu.findItem(R.id.history).icon = getActionBarIcon(CommunityMaterial.Icon.cmd_history)
menu.findItem(R.id.delete_group).icon = getActionBarIcon(CommunityMaterial.Icon.cmd_delete)
menu.findItem(R.id.search).apply { icon = getActionBarIcon(CommunityMaterial.Icon.cmd_magnify) }
.actionView.let { it as SearchView }
.apply {
queryHint = getString(R.string.menu_search) + "..."
setIconifiedByDefault(false)
isSubmitButtonEnabled = true
imeOptions = imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI
maxWidth = Int.MAX_VALUE
}
return super.onCreateOptionsMenu(menu)
}
private fun getActionBarIcon(icon: IIcon) =
IconicsDrawable(ctx).actionBar().icon(icon).colorRes(R.color.text_title_color)
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.filters -> getNavigator().goTo(FilterScreen(selectedGroup!!))
R.id.exams -> getNavigator().goTo(ExamScheduleScreen(selectedGroup!!))
R.id.history -> getNavigator().goTo(HistoryScreen(selectedGroup!!))
R.id.delete_group -> showDeleteGroupDialog()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun generateDrawerButtons() {
drawer.removeAllItems()
parityItem = PrimaryDrawerItem()
.withIcon(CommunityMaterial.Icon.cmd_calendar)
.withSelectable(false)
drawer.addItem(parityItem)
updateParityItemText()
drawer.addItem(DividerDrawerItem())
drawer.addItem(PrimaryDrawerItem()
.withIcon(CommunityMaterial.Icon.cmd_plus)
.withName(R.string.button_add_group)
.withSelectable(false)
.withOnDrawerItemClickListener { _, _, _ -> showAddGroupDialog(); true })
for ((id, group) in preferences.groups.withIndex()) {
drawer.addItem(PrimaryDrawerItem()
.withIdentifier((id + SCHEDULE_SCREEN_ID_START).toLong())
.withIcon(CommunityMaterial.Icon.cmd_account_multiple)
.withName(group)
.withSetSelected(preferences.group == group)
.withOnDrawerItemClickListener { _, _, _ -> getNavigator().replace(ScheduleScreen(group)); false })
}
drawer.addItem(DividerDrawerItem())
/*drawer.addItem(PrimaryDrawerItem()
.withIcon(CommunityMaterial.Icon.cmd_account)
.withName(R.string.screen_teachers)
.withOnDrawerItemClickListener { _, _, _ -> getNavigator().replace(TeacherSearchScreen()); false })
drawer.addItem(DividerDrawerItem())*/
drawer.addItem(PrimaryDrawerItem()
.withIcon(CommunityMaterial.Icon.cmd_settings)
.withName(R.string.screen_settings)
.withOnDrawerItemClickListener { _, _, _ -> getNavigator().goTo(PreferenceScreen()); false }
.withSelectable(false))
}
private fun updateParityItemText() {
val parityText = currentWeekParity.toText(ctx).capitalize()
parityItem.withName(ctx.getString(R.string.label_week, parityText))
drawer.updateItem(parityItem)
}
private fun handleUpdateNotification(intent: Intent): Boolean {
val result = intent.getStringExtra(INTENT_TYPE) == INTENT_TYPE_UPDATE
if (result) {
notificationManager.cancel(NOTIFICATION_UPDATE)
var preferenceScreen: PreferenceScreen? = null
getNavigator().navigate {
preferenceScreen = it.mapNotNull { it as? PreferenceScreen }.singleOrNull()
}
if (preferenceScreen == null) {
getNavigator().goTo(PreferenceScreen())
} else {
getNavigator().goBackTo(preferenceScreen)
}
}
return result
}
private fun showAddGroupDialog() {
val view = ctx.frameLayout {
editText {
singleLine = true
imeOptions = imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI
}.lparams(width = matchParent) {
leftPadding = DIM_DIALOG_SIDE_PADDING
rightPadding = DIM_DIALOG_SIDE_PADDING
}
}
val editor = view.getChildAt(0) as EditText
AlertDialog.Builder(ctx)
.setTitle(R.string.dialog_add_group_title)
.setMessage(R.string.dialog_add_group_message)
.setView(view)
.setPositiveButton(R.string.dialog_ok) { _, _ -> }
.setNegativeButton(R.string.dialog_cancel) { _, _ -> }
.show()
.apply {
getButton(Dialog.BUTTON_POSITIVE).setOnClickListener { _ ->
try {
val group = Validator.validateGroup(editor.text.toString())
if (group in preferences.groups) {
setMessage(getString(R.string.dialog_add_group_message_duplicate))
return@setOnClickListener
}
EventBus.broadcast(Event.ADD_GROUP, group)
dismiss()
} catch (e: BlankGroupIndexException) {
setMessage(getString(R.string.dialog_add_group_message_blank))
} catch (e: ShortGroupIndexException) {
setMessage(getString(R.string.dialog_add_group_message_short))
}
}
}
}
private fun showDeleteGroupDialog() {
val group = selectedGroup!!
AlertDialog.Builder(ctx)
.setTitle(R.string.dialog_remove_group_title)
.setMessage(getString(R.string.dialog_remove_group_message, group))
.setPositiveButton(R.string.dialog_ok) { _, _ ->
val navigator = getNavigator()
val groups = preferences.groups
val newGroup: String?
if (groups.size > 1) {
val index = groups.indexOf(group)
newGroup = if (index == groups.size - 1) groups[index - 1] else groups[index + 1]
navigator.replace(ScheduleScreen(newGroup))
} else {
preferences.group = null
newGroup = null
navigator.replace(HomeScreen())
}
database.snapshots.request(group).forEach {
database.snapshots.remove(it.id)
}
database.filters.remove(group)
database.exams.remove(group)
preferences.removeGroup(group)
generateDrawerButtons()
newGroup?.let { selectedGroup = it }
}
.setNegativeButton(R.string.dialog_cancel) { _, _ -> }
.show()
}
override fun handleEvent(type: Event, payload: Any?) {
when (type) {
Event.SET_TOOLBAR_SHADOW_ENABLED -> {
val enabled = payload as Boolean
ViewCompat.setElevation(toolbar, if (enabled) DIM_ELEVATION_F else 0f)
}
Event.SET_DRAWER_ENABLED -> {
val toggle = drawer.actionBarDrawerToggle
val layout = drawer.drawerLayout
val actionBar = supportActionBar!!
val enabled = payload as Boolean
if (enabled) {
actionBar.setDisplayHomeAsUpEnabled(false)
toggle.isDrawerIndicatorEnabled = true
layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
} else {
toggle.isDrawerIndicatorEnabled = false
actionBar.setDisplayHomeAsUpEnabled(true)
layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
}
Event.ADD_GROUP -> {
val group = payload as String
preferences.addGroup(group)
generateDrawerButtons()
selectedGroup = group
drawer.closeDrawer()
EventBus.broadcast(Event.INITIAL_DATA_FETCH, group)
}
}
}
}
|
mit
|
545cc3e2ad5e68b91c57793b16bd3f24
| 38.688482 | 119 | 0.625289 | 5.141065 | false | false | false | false |
alygin/intellij-rust
|
src/main/kotlin/org/rust/ide/search/RsUsageTypeProvider.kt
|
2
|
2500
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.search
import com.intellij.psi.PsiElement
import com.intellij.usages.UsageTarget
import com.intellij.usages.impl.rules.UsageType
import com.intellij.usages.impl.rules.UsageTypeProviderEx
import org.rust.lang.core.psi.*
object RsUsageTypeProvider : UsageTypeProviderEx {
override fun getUsageType(element: PsiElement?): UsageType? = getUsageType(element, UsageTarget.EMPTY_ARRAY)
override fun getUsageType(element: PsiElement?, targets: Array<out UsageTarget>): UsageType? {
if (element is RsUseGlob) {
return UsageType("use")
}
val parent = element?.goUp<RsPath>() ?: return null
if (parent is RsBaseType) {
val context = parent.goUp<RsBaseType>()
return when (context) {
is RsTypeReference -> {
when (context.parent) {
is RsImplItem -> UsageType("impl")
else -> UsageType("type reference")
}
}
else -> null
}
}
if (parent is RsPathExpr) {
val context = parent.goUp<RsPathExpr>()
return when (context) {
is RsDotExpr -> UsageType("dot expr")
is RsCallExpr -> UsageType("function call")
is RsValueArgumentList -> UsageType("argument")
is RsFormatMacroArg -> UsageType("macro argument")
is RsExpr -> UsageType("expr")
else -> null
}
}
return when (parent) {
is RsUseItem -> UsageType("use")
is RsStructLiteral -> UsageType("init struct")
is RsStructLiteralField -> UsageType("init field")
is RsTraitRef -> UsageType("trait ref")
is RsMethodCall -> UsageType("method call")
is RsMetaItem -> UsageType("meta item")
is RsFieldLookup -> UsageType("field")
else -> {
val context = parent.parent
when (context) {
is RsModDeclItem -> UsageType("mod")
else -> null
}
}
}
}
inline fun <reified T : PsiElement> PsiElement.goUp(): PsiElement {
var context = this
while (context is T) {
context = context.parent
}
return context
}
}
|
mit
|
ad29b69e21763cfdc1f8a2b311df2e65
| 34.714286 | 112 | 0.5492 | 5.070994 | false | false | false | false |
KotlinBy/awesome-kotlin
|
src/main/kotlin/link/kotlin/scripts/MarkdownRenderer.kt
|
1
|
919
|
package link.kotlin.scripts
import org.commonmark.ext.gfm.tables.TablesExtension
import org.commonmark.parser.Parser
import org.commonmark.renderer.Renderer
import org.commonmark.renderer.html.HtmlRenderer
interface MarkdownRenderer {
fun render(md: String): String
companion object
}
private class CommonMarkMarkdownRenderer(
private val parser: Parser,
private val renderer: Renderer
) : MarkdownRenderer {
override fun render(md: String): String {
val document = parser.parse(md)
return renderer.render(document)
}
}
fun MarkdownRenderer.Companion.default(): MarkdownRenderer {
val extensions = listOf(TablesExtension.create())
val parser = Parser.builder().extensions(extensions).build()
val renderer = HtmlRenderer.builder().extensions(extensions).build()
return CommonMarkMarkdownRenderer(
parser = parser,
renderer = renderer
)
}
|
apache-2.0
|
7bbaea15eecbd90e782919ac289feefb
| 26.848485 | 72 | 0.739935 | 4.527094 | false | false | false | false |
abdodaoud/Merlin
|
app/src/main/java/com/abdodaoud/merlin/data/db/Tables.kt
|
1
|
273
|
package com.abdodaoud.merlin.data.db
object MainFactsTable {
val NAME = "MainFacts"
val ID = "_id"
}
object DayFactTable {
val NAME = "DayFact"
val ID = "_id"
val FACTS_ID = "factsId"
val DATE = "date"
val TITLE = "title"
val URL = "url"
}
|
mit
|
0cf40600c46f9307cfe47444d0e51bed
| 17.266667 | 36 | 0.59707 | 2.935484 | false | false | false | false |
bornest/KotlinUtils
|
random/src/main/java/com/github/kotlinutils/random/extensions/random.kt
|
1
|
909
|
@file:Suppress("NOTHING_TO_INLINE")
package com.github.kotlinutils.random.extensions
/**
* Created by nbv54 on 17-Apr-17.
*/
inline fun sleepRandomTime(min: Long, max: Long) {
if (max > 0 && min in 0..(max - 1)) {
var randomDuration = (Math.random() * max.toDouble()).toLong()
randomDuration = maxOf(randomDuration, min)
Thread.sleep(randomDuration)
}
else {
throw IllegalArgumentException("Parameters have to satisfy (max > 0 && min in 0..(max - 1)) !")
}
}
inline fun randomBoolean(probOfTrue: Double): Boolean {
if (probOfTrue > 0 && probOfTrue < 1) {
return (Math.random() <= probOfTrue)
}
else if (probOfTrue == 0.0) {
return false
}
else if (probOfTrue == 1.0) {
return true
}
else {
throw IllegalArgumentException("probOfTrue has to satisfy (probOfTrue >= 0 && probOfTrue < 1) !")
}
}
|
apache-2.0
|
4e755dc2ae6aaf899c43d003ab738b82
| 26.575758 | 105 | 0.606161 | 3.550781 | false | false | false | false |
geckour/Egret
|
app/src/main/java/com/geckour/egret/view/activity/SettingActivity.kt
|
1
|
2209
|
package com.geckour.egret.view.activity
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.Toolbar
import com.geckour.egret.R
import com.geckour.egret.databinding.ActivityMainBinding
import com.geckour.egret.view.fragment.MiscFragment
import com.geckour.egret.view.fragment.SettingMainFragment
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper
class SettingActivity: BaseActivity() {
enum class Type {
Preference,
Misc
}
companion object {
private val ARGS_KEY_TYPE = "argsKeyType"
fun getIntent(context: Context, type: Type) = Intent(context, SettingActivity::class.java)
.apply {
putExtra(ARGS_KEY_TYPE, type)
}
}
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(if (isModeDark()) R.style.AppTheme_Dark_NoActionBar else R.style.AppTheme_NoActionBar)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
binding.appBarMain.contentMain.fab.hide()
if (savedInstanceState == null) {
if (intent.hasExtra(ARGS_KEY_TYPE)) {
when (intent.extras[ARGS_KEY_TYPE]) {
Type.Preference -> {
supportFragmentManager.beginTransaction()
.replace(R.id.container, SettingMainFragment.newInstance(), SettingMainFragment.TAG)
.commit()
}
Type.Misc -> {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MiscFragment.newInstance(), MiscFragment.TAG)
.commit()
}
}
}
}
}
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
}
|
gpl-3.0
|
8a68315301e926e86cf5b6e35ae057b3
| 35.229508 | 116 | 0.623812 | 5.043379 | false | false | false | false |
openhab/openhab.android
|
mobile/src/main/java/org/openhab/habdroid/ui/widget/RecyclerViewSwipeRefreshLayout.kt
|
1
|
5191
|
/*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import androidx.core.view.NestedScrollingChildHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlin.math.abs
class RecyclerViewSwipeRefreshLayout(context: Context, attrs: AttributeSet) : SwipeRefreshLayout(context, attrs) {
private val touchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop
private var downX: Float = 0F
private var downY: Float = 0F
private var childScrollableOnDown: Boolean = false
private val parentOffsetInWindow = IntArray(2)
private val nestedScrollingChildHelper = NestedScrollingChildHelper(this)
private var horizontalSwipe: Boolean = false
private var isOrWasUpSwipe: Boolean = false
var recyclerView: RecyclerView? = null
init {
isNestedScrollingEnabled = true
}
override fun canChildScrollUp(): Boolean {
val layoutManager = recyclerView?.layoutManager as LinearLayoutManager?
val firstVisibleItem = layoutManager?.findFirstCompletelyVisibleItemPosition()
return if (firstVisibleItem == null) super.canChildScrollUp() else firstVisibleItem != 0
}
override fun onStartNestedScroll(child: View, target: View, nestedScrollAxes: Int): Boolean {
return false
}
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
if (event.action != MotionEvent.ACTION_DOWN && shouldPreventRefresh()) {
return false
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
horizontalSwipe = false
isOrWasUpSwipe = false
childScrollableOnDown = canChildScrollUp()
}
MotionEvent.ACTION_MOVE -> {
val xDiff = abs(event.x - downX)
val yDiff = event.y - downY
if (yDiff < -touchSlop) {
isOrWasUpSwipe = true
}
if (horizontalSwipe || xDiff > touchSlop) {
horizontalSwipe = true
return false
}
}
}
return super.onInterceptTouchEvent(event)
}
override fun setNestedScrollingEnabled(enabled: Boolean) {
// This method is called from the super constructor, where the helper isn't initialized yet
@Suppress("UNNECESSARY_SAFE_CALL", "SAFE_CALL_WILL_CHANGE_NULLABILITY")
nestedScrollingChildHelper?.isNestedScrollingEnabled = enabled
}
override fun isNestedScrollingEnabled(): Boolean {
return nestedScrollingChildHelper.isNestedScrollingEnabled
}
override fun startNestedScroll(axes: Int): Boolean {
return nestedScrollingChildHelper.startNestedScroll(axes)
}
override fun stopNestedScroll() {
nestedScrollingChildHelper.stopNestedScroll()
}
override fun hasNestedScrollingParent(): Boolean {
return nestedScrollingChildHelper.hasNestedScrollingParent()
}
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?
): Boolean {
return nestedScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed, offsetInWindow)
}
override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?): Boolean {
return nestedScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow)
}
override fun dispatchNestedFling(velocityX: Float, velocityY: Float, consumed: Boolean): Boolean {
return nestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed)
}
override fun dispatchNestedPreFling(velocityX: Float, velocityY: Float): Boolean {
return nestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY)
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int
) {
if (shouldPreventRefresh()) {
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
parentOffsetInWindow)
} else {
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
}
}
private fun shouldPreventRefresh(): Boolean {
return childScrollableOnDown || isOrWasUpSwipe
}
}
|
epl-1.0
|
7b8436400a0cb2880fdb42d5a2852252
| 34.8 | 117 | 0.68638 | 5.275407 | false | false | false | false |
kannix68/advent_of_code_2016
|
day14/src_kotlin/Day14b.kt
|
1
|
3372
|
import java.security.* // MessageDigest
import java.math.* // BigInteger
import kotlin.system.exitProcess
/**
* AoC2016 Day14a main class.
* Run with:
*
* ```
* kotlinc -verbose -include-runtime -d day14a.jar *.kt
* java -jar day14a.jar
* ```
*
* Document with:
* `java -jar dokka-fatjar.jar day13a.kt -format html -module "aoc16 day14a" -nodeprecated`
*/
class Day14b {
val maxiter = 64000
val numkeystofind = 64
companion object {
fun create(): Day14b = Day14b()
/**
* PSVM main entry point.
*/
@JvmStatic fun main(args: Array<String>) {
println("Starting")
val salt: String
if (args.size > 0) {
salt = args[0]
} else {
salt = "abc"
}
val o = create()
//val outputstr = o.md5sumhex(input)
//println("md5sum($input) => $outputstr")
o.process(salt)
}
}
/**
* Calculate an md5sum for a string, return MD5-hex-string (32 chars).
* See: [Java calculate MD5 hash](<http://stackoverflow.com/questions/7776116/java-calculate-md5-hash>)
*/
fun md5sumhex(s: String): String {
val md = MessageDigest.getInstance("MD5")
val data = s.toByteArray() //java: s.getBytes();
md.update(data, 0, data.size)
//println(" message-len=${data.size}")
//val i = BigInteger(1, md.digest())
//println(" bigint=$i")
//return(java.lang.String.format("%1$032x", i))
return "%1$032x".format(BigInteger(1, md.digest())) // < kotlin stdlib
//return(java.lang.String.format("%1$032x", BigInteger(1, md.digest()))) < java standard runtime
}
fun process(salt: String): Boolean {
println("salt=$salt")
val rxkey = Regex("""([0-9a-f])\1\1""")
var stack = mutableListOf(listOf(1, "a"))
stack.clear()
var ok = false
var numkeysfound = 0
var loop = -1
val hashesMap = hashMapOf(Pair(0, "none"))
while (!ok && loop < maxiter) {
loop += 1
var output: String
if (hashesMap.containsKey(loop)) {
output = hashesMap[loop] as String
} else {
val input = "$salt$loop"
output = input
(1..2017).forEach {
output = md5sumhex(output)
}
println("input=$input; output=$output")
hashesMap[loop] = output
}
val mrkey = rxkey.find(output)
if (mrkey != null) {
val foundseq = mrkey.value //groupValues[0]
//println("found-seq=$foundseq for md5sum=$output of inp=$input")
val searchfor = foundseq.substring(0,1).repeat(5)
(loop+1..loop+1001).forEach { idx ->
var verout: String
if (hashesMap.containsKey(idx)) {
verout = hashesMap[idx] as String
} else {
val verinp = "$salt$idx"
verout = verinp
(1..2017).forEach {
verout = md5sumhex(verout)
}
hashesMap[idx] = verout
}
if (verout.contains(searchfor)) {
numkeysfound +=1
println("found key #$numkeysfound: at idx=$loop, verified @loop=$idx to $searchfor")
if (numkeysfound >= numkeystofind) {
println("success at loop $loop")
return true
}
}
}
}
}
return false
}
}
|
mit
|
c342939d066f96fa13c7e158399bb080
| 27.596491 | 105 | 0.542408 | 3.560718 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/ImportDialog.kt
|
1
|
5356
|
/****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[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.anki.dialogs
import android.os.Bundle
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.R
import timber.log.Timber
import java.net.URLDecoder
class ImportDialog : AsyncDialogFragment() {
interface ImportDialogListener {
fun importAdd(importPath: List<String>)
fun importReplace(importPath: List<String>)
fun dismissAllDialogFragments()
}
override fun onCreateDialog(savedInstanceState: Bundle?): MaterialDialog {
super.onCreate(savedInstanceState)
val type = requireArguments().getInt("dialogType")
val dialog = MaterialDialog(requireActivity())
dialog.cancelable(true)
val dialogMessageList = requireArguments().getStringArrayList("dialogMessage")!!
// Iterate over dialog message list & create display filename
val displayFileName = dialogMessageList.joinToString("\n") { filenameFromPath(convertToDisplayName(it)) }
return when (type) {
DIALOG_IMPORT_ADD_CONFIRM -> {
dialog.show {
title(R.string.import_title)
message(text = resources.getQuantityString(R.plurals.import_files_message_add_confirm, dialogMessageList.size, displayFileName))
positiveButton(R.string.import_message_add) {
(activity as ImportDialogListener).importAdd(dialogMessageList)
dismissAllDialogFragments()
}
negativeButton(R.string.dialog_cancel)
}
}
DIALOG_IMPORT_REPLACE_CONFIRM -> {
dialog.show {
title(R.string.import_title)
message(text = resources.getString(R.string.import_message_replace_confirm, displayFileName))
positiveButton(R.string.dialog_positive_replace) {
(activity as ImportDialogListener).importReplace(dialogMessageList)
dismissAllDialogFragments()
}
negativeButton(R.string.dialog_cancel)
}
}
else -> null!!
}
}
private fun convertToDisplayName(name: String): String {
// ImportUtils URLEncodes names, which isn't great for display.
// NICE_TO_HAVE: Pass in the DisplayFileName closer to the source of the bad data, rather than fixing it here.
return try {
URLDecoder.decode(name, "UTF-8")
} catch (e: Exception) {
Timber.w(e, "Failed to convert filename to displayable string")
name
}
}
override val notificationMessage: String
get() {
return res().getString(R.string.import_interrupted)
}
override val notificationTitle: String
get() {
return res().getString(R.string.import_title)
}
fun dismissAllDialogFragments() {
(activity as ImportDialogListener).dismissAllDialogFragments()
}
companion object {
const val DIALOG_IMPORT_ADD_CONFIRM = 2
const val DIALOG_IMPORT_REPLACE_CONFIRM = 3
/**
* A set of dialogs which deal with importing a file
*
* @param dialogType An integer which specifies which of the sub-dialogs to show
* @param dialogMessageList An optional ArrayList of string(s) which can be used to show a custom message
* or specify import path
*/
fun newInstance(dialogType: Int, dialogMessageList: ArrayList<String>): ImportDialog {
val f = ImportDialog()
val args = Bundle()
args.putInt("dialogType", dialogType)
args.putStringArrayList("dialogMessage", dialogMessageList)
f.arguments = args
return f
}
private fun filenameFromPath(path: String): String {
return path.split("/").toTypedArray()[path.split("/").toTypedArray().size - 1]
}
}
}
|
gpl-3.0
|
87fe4411f8de6be15466a5505fffb595
| 44.777778 | 148 | 0.557506 | 5.573361 | false | false | false | false |
tokenbrowser/token-android-client
|
app/src/main/java/com/toshi/util/webView/WebViewCookieJar.kt
|
1
|
1750
|
/*
* Copyright (c) 2017. Toshi 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/>.
*/
package com.toshi.util.webView
import android.webkit.CookieManager
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
class WebViewCookieJar : CookieJar {
private val webViewCookieManager by lazy { CookieManager.getInstance() }
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
val urlString = url.toString()
cookies.forEach { webViewCookieManager.setCookie(urlString, it.toString()) }
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val urlString = url.toString()
val cookiesString = webViewCookieManager.getCookie(urlString)
if (cookiesString != null && cookiesString.isNotEmpty()) {
val cookieHeaders = cookiesString.split(";".toRegex())
val cookies = mutableListOf<Cookie>()
cookieHeaders
.map { Cookie.parse(url, it) }
.forEach { it?.let { cookies.add(it) } }
return cookies
}
return emptyList()
}
}
|
gpl-3.0
|
7053fafae31a5cb059eba9f3847bedbe
| 37.065217 | 84 | 0.670857 | 4.452926 | false | false | false | false |
toxxmeister/BLEacon
|
library/src/main/java/de/troido/bleacon/scanner/BleScanner.kt
|
1
|
2596
|
package de.troido.bleacon.scanner
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Handler
import de.troido.bleacon.ble.HandledBleActor
import de.troido.bleacon.ble.obtainScanner
import de.troido.bleacon.config.scan.scanSettings
import java.util.UUID
/**
* A more idiomatic wrapper for [android.bluetooth.le.BluetoothLeScanner].
*
* @param[svcUuid] UUID of the target service.
*
* @param[chrUuid] UUID of the target characteristic of the target service.
*
* @param[autoConnect] if `false`, directly connect to the remote device, or if `true`,
* automatically connect as soon as the remote device becomes available.
* See [android.bluetooth.BluetoothDevice.connectGatt]'s `autoConnect` param for more details.
*
* @param[stopWhenFound] if `true` then the scanner will be automatically stopped on first result.
*
* @param[handler] optional handler for sharing with other asynchronous actions.
*/
class BleScanner(context: Context,
filter: ScanFilter,
svcUuid: UUID,
chrUuid: UUID,
callback: BleScanCallback,
private val settings: ScanSettings = scanSettings(),
autoConnect: Boolean = false,
stopWhenFound: Boolean = true,
handler: Handler = Handler()
) : HandledBleActor(handler) {
private val scanner = obtainScanner()
private val filters = listOf(filter)
private val gattCallback = callback.toBtGattCallback(svcUuid, chrUuid, this)
private val scanCallback = object : ScanCallback() {
private fun connectDevice(device: BluetoothDevice) {
if (stopWhenFound) {
scanner.stopScan(this)
}
device.connectGatt(context, autoConnect, gattCallback)
}
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.device?.let(this::connectDevice)
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
super.onBatchScanResults(results)
results?.mapNotNull { it.device }?.firstOrNull()?.let(this::connectDevice)
}
}
override fun start() {
handler.post { scanner.startScan(filters, settings, scanCallback) }
}
override fun stop() {
handler.post { scanner.stopScan(null) }
}
}
|
apache-2.0
|
178e7f0df80a78a260ee79962c54c944
| 34.081081 | 98 | 0.683359 | 4.514783 | false | false | false | false |
pdvrieze/ProcessManager
|
PE-common/src/jvmMain/kotlin/nl/adaptivity/util/xml/AbstractEventReader.kt
|
1
|
2295
|
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util.xml
import javax.xml.stream.XMLEventReader
import javax.xml.stream.XMLStreamException
import javax.xml.stream.events.Characters
import javax.xml.stream.events.XMLEvent
abstract class AbstractEventReader : XMLEventReader {
override fun next(): XMLEvent = nextEvent()
@Throws(XMLStreamException::class)
override fun getElementText(): String {
val result = StringBuilder()
var event = nextEvent()
while (!event.isEndElement) {
if (event.isCharacters) {
result.append((event as Characters).data)
} else if (event.isAttribute) {
// ignore
} else {
throw XMLStreamException("Unexpected child")
}
event = nextEvent()
}
return result.toString()
}
@Throws(XMLStreamException::class)
override fun nextTag(): XMLEvent {
var event = nextEvent()
while (!event.isEndDocument) {
if (event.isStartElement) {
return event
} else if (event.isEndElement) {
return event
} else if (event.isAttribute) { // ignore
} else if (event.isCharacters) {
if (!event.asCharacters().isIgnorableWhiteSpace) {
throw XMLStreamException("Non-whitespace text encountered")
}
} else {
throw XMLStreamException("Unexpected tags encountered")
}
event = nextEvent()
}
throw XMLStreamException("Unexpected end of document")
}
}
|
lgpl-3.0
|
f6cdd117fff3a0dfb9d60bcb70972584
| 33.253731 | 112 | 0.631808 | 4.872611 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/cause/LanternCauseStackManager.kt
|
1
|
3991
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.cause
import org.lanternpowered.api.cause.Cause
import org.lanternpowered.api.cause.CauseContext
import org.lanternpowered.api.cause.CauseContextKey
import org.lanternpowered.api.cause.CauseStack
import org.lanternpowered.api.cause.CauseStackManager
import org.lanternpowered.api.util.concurrent.ThreadLocal
import org.lanternpowered.server.util.LanternThread
import java.util.Optional
import kotlin.reflect.KClass
/**
* A [CauseStackManager] that manages the [LanternCauseStack]s for all
* the supported [Thread]s. (main, world threads, etc.)
*/
object LanternCauseStackManager : CauseStackManager {
/**
* A [ThreadLocal] to fall back to if a thread doesn't extend [LanternThread].
*/
private val fallbackCauseStacks = ThreadLocal<LanternCauseStack>()
/**
* Sets the [LanternCauseStack] for the current [Thread].
*/
fun setCurrentCauseStack(causeStack: LanternCauseStack) {
val thread = Thread.currentThread()
if (thread is LanternThread) {
thread.causeStack = causeStack
} else {
this.fallbackCauseStacks.set(causeStack)
}
}
override fun currentStackOrNull() = this.getCauseStackOrNull(Thread.currentThread())
private fun getCauseStackOrNull(thread: Thread)
= if (thread is LanternThread) thread.causeStack else this.fallbackCauseStacks.get()
fun getCauseStackOrEmpty(thread: Thread) = this.getCauseStackOrNull(thread) ?: EmptyCauseStack
override fun currentStackOrEmpty(): CauseStack = this.currentStackOrNull() ?: EmptyCauseStack
override fun currentStack() = this.currentStackOrNull() ?: error("The current thread doesn't support a cause stack.")
override fun getCurrentCause(): Cause = this.currentStack().currentCause
override fun getCurrentContext(): CauseContext = this.currentStack().currentContext
override fun pushCause(obj: Any): CauseStackManager = apply { this.currentStack().pushCause(obj) }
override fun popCause(): Any = this.currentStack().popCause()
override fun popCauses(n: Int) = this.currentStack().popCauses(n)
override fun peekCause(): Any = this.currentStack().peekCause()
override fun pushCauseFrame(): CauseStack.Frame = this.currentStack().pushCauseFrame()
override fun popCauseFrame(handle: org.spongepowered.api.event.CauseStackManager.StackFrame) = this.currentStack().popCauseFrame(handle)
override fun <T : Any> addContext(key: CauseContextKey<T>, value: T): CauseStackManager = apply { this.currentStack().addContext(key, value) }
override fun <T : Any> getContext(key: CauseContextKey<T>): Optional<T> = this.currentStack().getContext(key)
override fun <T : Any> removeContext(key: CauseContextKey<T>): Optional<T> = this.currentStack().removeContext(key)
override fun <T : Any> get(key: CauseContextKey<T>): T?= this.currentStack()[key]
override fun <T : Any> set(key: CauseContextKey<T>, value: T) = this.currentStack().set(key, value)
override fun <T : Any> first(target: KClass<T>): T? = this.currentStack().first(target)
override fun <T : Any> first(target: Class<T>): Optional<T> = this.currentStack().first(target)
override fun <T : Any> last(target: KClass<T>): T? = this.currentStack().last(target)
override fun <T : Any> last(target: Class<T>): Optional<T> = this.currentStack().last(target)
override fun containsType(target: KClass<*>): Boolean = this.currentStack().containsType(target)
override fun containsType(target: Class<*>): Boolean = this.currentStack().containsType(target)
override fun contains(any: Any): Boolean = this.currentStack().contains(any)
}
|
mit
|
05dd5583c2c7786c65fd1cb99b3e6601
| 50.831169 | 146 | 0.730143 | 3.9751 | false | false | false | false |
ratabb/Hishoot2i
|
app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/template/SortTemplateDialog.kt
|
1
|
2977
|
package org.illegaller.ratabb.hishoot2i.ui.template
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.setFragmentResult
import androidx.navigation.fragment.navArgs
import common.ext.preventMultipleClick
import org.illegaller.ratabb.hishoot2i.R
import org.illegaller.ratabb.hishoot2i.databinding.DialogSortTemplateBinding
import org.illegaller.ratabb.hishoot2i.ui.ARG_SORT
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SORT
import template.TemplateComparator
import template.TemplateComparator.DATE_ASC
import template.TemplateComparator.DATE_DESC
import template.TemplateComparator.NAME_ASC
import template.TemplateComparator.NAME_DESC
import template.TemplateComparator.TYPE_ASC
import template.TemplateComparator.TYPE_DESC
class SortTemplateDialog : AppCompatDialogFragment() {
private val args: SortTemplateDialogArgs by navArgs()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
super.onCreateDialog(savedInstanceState).apply {
setStyle(DialogFragment.STYLE_NO_FRAME, theme)
setCancelable(false)
setCanceledOnTouchOutside(false)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = DialogSortTemplateBinding.inflate(inflater, container, false).apply {
// views order must sync with TemplateComparator#ordinal
val views = arrayOf(
actionSortNameAsc, actionSortNameDesc, actionSortTypeAsc,
actionSortTypeDesc, actionSortDateAsc, actionSortDateDesc
)
// NOTE: are we need setBackground view to null ?
views.forEach { it.background = null }
// NOTE: emit | setBackground selected indicator.
views[args.templateComparator.ordinal].setBackgroundResource(R.drawable.sort_selected)
//
val click: (View, TemplateComparator) -> Unit = { view, comparator ->
view.preventMultipleClick {
if (args.templateComparator != comparator) {
setFragmentResult(KEY_REQ_SORT, bundleOf(ARG_SORT to comparator.ordinal))
}
dismiss()
}
}
actionSortNameAsc.setOnClickListener { click(it, NAME_ASC) }
actionSortNameDesc.setOnClickListener { click(it, NAME_DESC) }
actionSortTypeAsc.setOnClickListener { click(it, TYPE_ASC) }
actionSortTypeDesc.setOnClickListener { click(it, TYPE_DESC) }
actionSortDateAsc.setOnClickListener { click(it, DATE_ASC) }
actionSortDateDesc.setOnClickListener { click(it, DATE_DESC) }
//
actionSortCancel.setOnClickListener { click(it, args.templateComparator) }
}.run { root }
}
|
apache-2.0
|
7dd1f0bda46c53b743fe07b8f9f7f0f9
| 42.779412 | 94 | 0.730601 | 4.688189 | false | false | false | false |
debop/debop4k
|
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/utils/Times.kt
|
1
|
15177
|
/*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("Times")
package debop4k.timeperiod.utils
import debop4k.core.kodatimes.asDate
import debop4k.core.kodatimes.months
import debop4k.core.kodatimes.startOfDay
import debop4k.core.kodatimes.today
import debop4k.timeperiod.*
import debop4k.timeperiod.models.*
import debop4k.timeperiod.timeranges.WeekRange
import org.joda.time.DateTime
import org.joda.time.LocalDate
import org.joda.time.LocalTime
import java.util.*
fun now(): DateTime = DateTime.now()
fun today(): DateTime = DateTime.now().withTimeAtStartOfDay()
fun DateTime.localDate(): LocalDate = this.toLocalDate()
fun DateTime.localTime(): LocalTime = this.toLocalTime()
@Suppress("UNUSED_PARAMETER")
@JvmOverloads
fun yearOf(year: Int, monthOfYear: Int, calendar: ITimeCalendar = DefaultTimeCalendar): Int
= if (monthOfYear >= 1) year else year - 1
@JvmOverloads
fun DateTime.yearOf(calendar: ITimeCalendar = DefaultTimeCalendar): Int
= yearOf(this.year, this.monthOfYear, calendar)
fun daysOfYear(year: Int): Int = asDate(year + 1).minusDays(1).dayOfYear
fun addHalfyear(year: Int, halfyear: Halfyear, delta: Int): YearHalfyear {
if (delta == 0)
return YearHalfyear(year, halfyear)
return YearHalfyear(startTimeOfHalfyear(year, halfyear).plusMonths(delta * MonthsPerHalfyear))
}
fun YearHalfyear.addHalfyear(delta: Int): YearHalfyear {
if (delta == 0)
return YearHalfyear(this)
val end = startTimeOfHalfyear(year, halfyear).plusMonths(delta * MonthsPerHalfyear)
return YearHalfyear(end)
}
fun nextHalfyear(year: Int, halfyear: Halfyear): YearHalfyear = addHalfyear(year, halfyear, 1)
fun YearHalfyear.nextHalfyear(): YearHalfyear = this.addHalfyear(1)
fun prevHalfyear(year: Int, halfyear: Halfyear): YearHalfyear = addHalfyear(year, halfyear, -1)
fun YearHalfyear.prevHalfyear(): YearHalfyear = this.addHalfyear(-1)
fun halfyearOfMonth(monthOfYear: Int): Halfyear = if (FirstHalfyearMonths.contains(monthOfYear)) Halfyear.First else Halfyear.Second
fun addQuarter(year: Int, quarter: Quarter, delta: Int): YearQuarter {
if (delta == 0)
return YearQuarter(year, quarter)
return YearQuarter(startTimeOfQuarter(year, quarter).plusMonths(MonthsPerQuarter * delta))
}
fun YearQuarter.addQuarter(delta: Int): YearQuarter
= addQuarter(year, quarter, delta)
fun nextQuarter(year: Int, quarter: Quarter): YearQuarter = addQuarter(year, quarter, 1)
fun YearQuarter.nextQuarter(): YearQuarter = this.addQuarter(1)
fun prevQuarter(year: Int, quarter: Quarter): YearQuarter = addQuarter(year, quarter, -1)
fun YearQuarter.prevQuarter(): YearQuarter = this.addQuarter(-1)
fun quarterOfMonth(monthOfYear: Int): Quarter = Quarter.ofMonth(monthOfYear)
fun addMonth(year: Int, monthOfYear: Int, delta: Int): YearMonth {
return YearMonth(year, monthOfYear).addMonth(delta)
}
fun YearMonth.addMonth(delta: Int): YearMonth {
if (delta == 0) return this.copy()
val dt = this.startTimeOfMonth() + delta.months()
return YearMonth(dt.year, dt.monthOfYear)
}
fun nextMonth(year: Int, monthOfYear: Int): YearMonth = addMonth(year, monthOfYear, 1)
fun YearMonth.nextMonth(): YearMonth = this.addMonth(1)
fun prevMonth(year: Int, monthOfYear: Int): YearMonth = addMonth(year, monthOfYear, -1)
fun YearMonth.prevMonth(): YearMonth = this.addMonth(-1)
fun daysInMonth(year: Int, monthOfYear: Int): Int
= asDate(year, monthOfYear).plusMonths(1).minusDays(1).dayOfMonth
fun DateTime.daysInMonth(): Int = daysInMonth(this.year, this.monthOfYear)
fun YearMonth.daysInMonth(): Int = daysInMonth(this.year, this.monthOfYear)
fun DateTime.startOfWeek(): DateTime {
val day = this.startOfDay()
val dayOfWeek = day.dayOfWeek
return day.minusDays(dayOfWeek - 1)
}
fun DateTime.weekOfMonth(): MonthWeek {
val calendar = Calendar.getInstance()
calendar.timeInMillis = this.millis
calendar.minimalDaysInFirstWeek = 1
calendar.firstDayOfWeek = Calendar.MONDAY
return MonthWeek(this.monthOfYear, calendar.get(Calendar.WEEK_OF_MONTH))
}
@Suppress("UNUSED_PARAMETER")
@JvmOverloads
fun DateTime.weekOfYear(calendar: ITimeCalendar = TimeCalendar.DEFAULT): YearWeek = YearWeek.of(this)
fun lastWeekOfYear(year: Int): YearWeek {
var lastDay = asDate(year, 12, 31)
while (lastDay.weekyear > year) {
lastDay = lastDay.minusDays(1)
}
return YearWeek(year, lastDay.weekOfWeekyear)
}
fun startOfYearWeek(weekyear: Int, weekOfWeekyear: Int): DateTime {
return today().withWeekyear(weekyear).withWeekOfWeekyear(weekOfWeekyear)
}
fun YearWeek.startOfYearWeek(): DateTime = startOfYearWeek(this.weekyear, this.weekOfWeekyear)
fun DateTime.dayStart(): DateTime = this.withTimeAtStartOfDay()
fun addDayOfWeek(dow: DayOfWeek, delta: Int = 1): DayOfWeek = dow + delta
fun DayOfWeek.nextDayOfWeek(): DayOfWeek = addDayOfWeek(this, 1)
fun DayOfWeek.prevDayOfWeek(): DayOfWeek = addDayOfWeek(this, -1)
fun DateTime.isSameTime(other: DateTime?, unit: PeriodUnit): Boolean = when (unit) {
PeriodUnit.YEAR -> isSameYear(other)
PeriodUnit.HALFYEAR -> isSameHalfyear(other)
PeriodUnit.QUARTER -> isSameQuarter(other)
PeriodUnit.MONTH -> isSameMonth(other)
PeriodUnit.DAY -> isSameDay(other)
PeriodUnit.HOUR -> isSameHour(other)
PeriodUnit.MINUTE -> isSameMinute(other)
PeriodUnit.SECOND -> isSameSecond(other)
else -> isSameDateTime(other)
}
fun DateTime.isSameYear(other: DateTime?): Boolean
= other != null && this.year == other.year
fun DateTime.isSameHalfyear(other: DateTime?): Boolean
= isSameYear(other) && halfyearOf() == other!!.halfyearOf()
fun DateTime.isSameQuarter(other: DateTime?): Boolean
= isSameYear(other) && quarterOf() == other!!.quarterOf()
fun DateTime.isSameMonth(other: DateTime?): Boolean
= isSameYear(other) && monthOfYear == other!!.monthOfYear
fun DateTime.isSameWeek(other: DateTime?): Boolean
= isSameMonth(other) && weekyear == other!!.weekyear && weekOfWeekyear == other.weekOfWeekyear
fun DateTime.isSameDay(other: DateTime?): Boolean
= isSameYear(other) && dayOfYear == other!!.dayOfYear
fun DateTime.isSameHour(other: DateTime?): Boolean
= isSameDay(other) && hourOfDay == other!!.hourOfDay
fun DateTime.isSameMinute(other: DateTime?): Boolean
= isSameDay(other) && minuteOfDay == other!!.minuteOfDay
fun DateTime.isSameSecond(other: DateTime?): Boolean
= isSameDay(other) && secondOfDay == other!!.secondOfDay
fun DateTime.isSameDateTime(other: DateTime?): Boolean
= other != null && millis == other.millis
fun currentYear(): DateTime
= asDate(now().year, 1, 1)
fun currentHalfyear(): DateTime {
val current = today()
return startTimeOfHalfyear(current.year, current.halfyearOf())
}
fun currentQuarter(): DateTime {
val current = today()
return startTimeOfQuarter(current.year, current.quarterOf())
}
fun currentMonth(): DateTime = today().startTimeOfMonth()
fun currentWeek(): DateTime = today().startTimeOfWeek()
fun currentDay(): DateTime = today().startTimeOfDay()
fun currentHour(): DateTime = today().startTimeOfHour()
fun currentMinute(): DateTime = today().startTimeOfMinute()
fun currentSecond(): DateTime = today().startTimeOfSecond()
fun startTimeOfYear(year: Int): DateTime = asDate(year, 1, 1)
fun DateTime.startTimeOfYear(): DateTime
= startTimeOfYear(this.year)
fun endTimeOfYear(year: Int): DateTime
= startTimeOfYear(year).plusYears(1).minusMillis(1)
fun DateTime.endTimeOfYear(): DateTime
= endTimeOfYear(this.year)
fun startTimeOfHalfyear(year: Int, halfyear: Halfyear): DateTime
= asDate(year, halfyear.startMonth.value, 1)
fun startTimeOfHalfyear(year: Int, monthOfYear: Int): DateTime
= startTimeOfHalfyear(year, halfyearOf(monthOfYear))
fun YearHalfyear.startTimeOfHalfyear(): DateTime
= startTimeOfHalfyear(year, halfyear)
fun DateTime.startTimeOfHalfyear(): DateTime
= startTimeOfHalfyear(this.year, this.monthOfYear)
fun endTimeOfHalfyear(year: Int, monthOfYear: Int): DateTime
= startTimeOfHalfyear(year, monthOfYear).plusMonths(MonthsPerHalfyear).minusMillis(1)
fun endTimeOfHalfyear(year: Int, halfyear: Halfyear): DateTime
= endTimeOfHalfyear(year, halfyear.startMonth.value)
fun YearHalfyear.endTimeOfHalfyear(): DateTime
= endTimeOfHalfyear(year, halfyear)
fun DateTime.endTimeOfHalfyear(): DateTime
= endTimeOfHalfyear(this.year, this.monthOfYear)
fun startTimeOfQuarter(year: Int, monthOfYear: Int): DateTime
= startTimeOfQuarter(year, quarterOf(monthOfYear))
fun startTimeOfQuarter(year: Int, quarter: Quarter): DateTime
= asDate(year, quarter.startMonth, 1)
fun YearQuarter.startTimeOfQuarter(): DateTime
= startTimeOfQuarter(year, quarter)
fun DateTime.startTimeOfQuarter(): DateTime
= startTimeOfQuarter(this.year, this.monthOfYear)
fun endTimeOfQuarter(year: Int, monthOfYear: Int): DateTime
= endTimeOfQuarter(year, quarterOf(monthOfYear))
fun endTimeOfQuarter(year: Int, quarter: Quarter): DateTime
= asDate(year, quarter.endMonth + 1, 1).minusMillis(1)
fun YearQuarter.endTimeOfQuarter(): DateTime
= endTimeOfQuarter(year, quarter)
fun DateTime.endTimeOfQuarter(): DateTime
= endTimeOfQuarter(this.year, this.monthOfYear)
fun startTimeOfMonth(year: Int, monthOfYear: Int): DateTime = asDate(year, monthOfYear, 1)
fun startTimeOfMonth(year: Int, month: Month): DateTime = startTimeOfMonth(year, month.value)
fun YearMonth.startTimeOfMonth(): DateTime = startTimeOfMonth(this.year, this.monthOfYear)
fun DateTime.startTimeOfMonth(): DateTime = startTimeOfMonth(this.year, this.monthOfYear)
fun endTimeOfMonth(year: Int, monthOfYear: Int): DateTime
= startTimeOfMonth(year, monthOfYear).plusMonths(1).minusMillis(1)
fun endTimeOfMonth(year: Int, month: Month): DateTime
= endTimeOfMonth(year, month.value)
fun YearMonth.endTimeOfMonth(): DateTime
= endTimeOfMonth(this.year, this.monthOfYear)
fun DateTime.endTimeOfMonth(): DateTime
= endTimeOfMonth(this.year, this.monthOfYear)
fun startTimeOfWeek(weekyear: Int, weekOfWeekyear: Int): DateTime
= DateTime().withWeekyear(weekyear).withWeekOfWeekyear(weekOfWeekyear)
fun YearWeek.startTimeOfWeek(): DateTime
= startTimeOfWeek(this.weekyear, this.weekOfWeekyear)
fun DateTime.startTimeOfWeek(): DateTime {
val day = asDate()
val dayOfWeek = day.dayOfWeek
return day.minusDays(dayOfWeek - 1)
}
fun endTimeOfWeek(weekyear: Int, weekOfWeekyear: Int): DateTime
= startTimeOfWeek(weekyear, weekOfWeekyear).plusWeeks(1).minusMillis(1)
fun YearWeek.endTimeOfWeek(): DateTime
= endTimeOfWeek(this.weekyear, this.weekOfWeekyear)
fun DateTime.endTimeOfWeek(): DateTime {
return startTimeOfWeek().plusDays(7)
}
fun DateTime.startTimeOfDay(): DateTime = this.withTimeAtStartOfDay()
fun DateTime.endTimeOfDay(): DateTime = startTimeOfDay().plusDays(1).minusMillis(1)
fun DateTime.startTimeOfHour(): DateTime = startTimeOfDay().plusHours(this.hourOfDay)
fun DateTime.endTimeOfHour(): DateTime = startTimeOfHour().plusHours(1).minusMillis(1)
fun DateTime.startTimeOfMinute(): DateTime = startTimeOfHour().plusMinutes(this.minuteOfHour)
fun DateTime.endTimeOfMinute(): DateTime = startTimeOfMinute().plusMinutes(1).minusMillis(1)
fun DateTime.startTimeOfSecond(): DateTime = startTimeOfMinute().plusSeconds(this.secondOfMinute)
fun DateTime.endTimeOfSecond(): DateTime = startTimeOfSecond().plusSeconds(1).minusMillis(1)
fun halfyearOf(monthOfYear: Int): Halfyear = Halfyear.ofMonth(monthOfYear)
fun DateTime.halfyearOf(): Halfyear = Halfyear.ofMonth(this.monthOfYear)
fun quarterOf(monthOfYear: Int): Quarter = Quarter.ofMonth(monthOfYear)
fun DateTime.quarterOf(): Quarter = Quarter.ofMonth(this.monthOfYear)
/** 현 일자의 다음주 같은 요일 */
fun DateTime.nextDayOfWeek(): DateTime = this.plusWeeks(1)
fun DateTime.prevDayOfWeek(): DateTime = this.minusWeeks(1)
fun DateTime?.hasDate(): Boolean
= this != null && this.withTimeAtStartOfDay().millis > 0
fun DateTime.setDatepart(date: DateTime): DateTime
= date.startTimeOfDay().withMillisOfDay(this.millisOfDay)
@JvmOverloads
fun DateTime.setDatepart(year: Int, monthOfYear: Int = 1, dayOfMonth: Int = 1): DateTime
= asDate(year, monthOfYear, dayOfMonth).withMillisOfDay(this.millisOfDay)
fun DateTime.setYear(year: Int): DateTime = this.withYear(year)
fun DateTime.setMonth(monthOfYear: Int): DateTime = this.withMonthOfYear(monthOfYear)
fun DateTime.setDay(dayOfMonth: Int): DateTime = this.withDayOfMonth(dayOfMonth)
fun DateTime.setTimepart(time: DateTime): DateTime
= this.startTimeOfDay().withMillisOfDay(time.millisOfDay)
@JvmOverloads
fun DateTime.setTimepart(hourOfDay: Int,
minuteOfHour: Int = 0,
secondOfMinute: Int = 0,
millisOfSecond: Int = 0): DateTime
= this.startTimeOfDay().withTime(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond)
fun DateTime.getTimepart(): Int = this.millisOfDay
fun DateTime?.hasTimepart(): Boolean = this != null && this.millisOfDay > 0
fun combine(date: DateTime, time: DateTime): DateTime = date.setTimepart(time)
fun combine(date: LocalDate, time: LocalTime): DateTime = date.toDateTime(time)
fun DateTime.setHour(hourOfDay: Int): DateTime = this.withHourOfDay(hourOfDay)
fun DateTime.setMinute(minuteOfHour: Int): DateTime = this.withMinuteOfHour(minuteOfHour)
fun DateTime.setSecond(secondOfMinute: Int): DateTime = this.withSecondOfMinute(secondOfMinute)
fun DateTime.setMillis(millisOfSeocond: Int): DateTime = this.withMillisOfSecond(millisOfSeocond)
fun DateTime.setMillisOfDay(millisOfDay: Int): DateTime = this.withMillisOfDay(millisOfDay)
fun DateTime.addDate(unit: PeriodUnit, delta: Int): DateTime = when (unit) {
PeriodUnit.YEAR -> this.plusYears(delta)
PeriodUnit.HALFYEAR -> this.plusMonths(MonthsPerHalfyear * delta)
PeriodUnit.QUARTER -> this.plusMonths(MonthsPerQuarter * delta)
PeriodUnit.MONTH -> this.plusMonths(delta)
PeriodUnit.WEEK -> this.plusWeeks(delta)
PeriodUnit.DAY -> this.plusDays(delta)
PeriodUnit.HOUR -> this.plusHours(delta)
PeriodUnit.MINUTE -> this.plusMinutes(delta)
PeriodUnit.SECOND -> this.plusSeconds(delta)
PeriodUnit.MILLISECOND -> this.plusMillis(delta)
else -> throw IllegalArgumentException("Unsupported period unit. unit=$unit")
}
fun startWeekRangeOfYear(year: Int): WeekRange = WeekRange(YearWeek(year, 1))
fun endWeekRangeOfYear(year: Int): WeekRange = WeekRange(lastWeekOfYear(year))
fun maxWeekOfYear(year: Int): YearWeek = YearWeek.of(asDate(year, 12, 28))
fun DayOfWeek.isWeekday(): Boolean = WeekdayList.contains(this)
fun DayOfWeek.isWeekend(): Boolean = WeekendList.contains(this)
|
apache-2.0
|
db1d45fb1e76febad9b2cc2f5485de57
| 37.660714 | 132 | 0.761201 | 3.814498 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA
|
src/nl/hannahsten/texifyidea/util/SystemEnvironment.kt
|
1
|
4249
|
package nl.hannahsten.texifyidea.util
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessNotCreatedException
import com.intellij.openapi.util.SystemInfo
import org.apache.maven.artifact.versioning.DefaultArtifactVersion
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Information about the system other than the LatexDistribution or the OS.
*/
class SystemEnvironment {
companion object {
val inkscapeMajorVersion: Int by lazy {
"inkscape --version".runCommand()
?.split(" ")?.getOrNull(1)
?.split(".")?.firstOrNull()
?.toInt() ?: 0
}
val isInkscapeInstalledAsSnap: Boolean by lazy {
"snap list".runCommand()?.contains("inkscape") == true
}
/** Cache for [isAvailable]. */
private var availabilityCache = mutableMapOf<String, Boolean>()
/**
* Check if [command] is available as a system command.
*/
fun isAvailable(command: String): Boolean {
// Not thread-safe, but don't think that's a problem here
availabilityCache.getOrDefault(command, null)?.let { return it }
val isAvailable = if (SystemInfo.isUnix) {
"command -v $command".runCommandWithExitCode().second == 0
}
else {
"where $command".runCommandWithExitCode().second == 0
}
availabilityCache[command] = isAvailable
return isAvailable
}
// Assumes version will be given in the format GNOME Document Viewer 3.34.2
val evinceVersion: DefaultArtifactVersion by lazy {
DefaultArtifactVersion("evince --version".runCommand()?.split(" ")?.lastOrNull() ?: "")
}
}
}
/**
* Run a command in the terminal.
*
* @return The output of the command or null if an exception was thrown.
*/
fun runCommand(vararg commands: String, workingDirectory: File? = null): String? {
return runCommandWithExitCode(*commands, workingDirectory = workingDirectory).first
}
/**
* See [runCommand], but also returns exit code.
*
* @param returnExceptionMessage Whether to return exception messages if exceptions are thrown.
*/
fun runCommandWithExitCode(vararg commands: String, workingDirectory: File? = null, timeout: Long = 3, returnExceptionMessage: Boolean = false): Pair<String?, Int> {
Log.debug("Executing in ${workingDirectory ?: "current working directory"} ${GeneralCommandLine(*commands).commandLineString}")
return try {
val proc = GeneralCommandLine(*commands)
.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE)
.withWorkDirectory(workingDirectory)
.createProcess()
if (proc.waitFor(timeout, TimeUnit.SECONDS)) {
val output = proc.inputStream.bufferedReader().readText().trim() + proc.errorStream.bufferedReader().readText().trim()
if (proc.exitValue() != 0) {
Log.debug("${commands.firstOrNull()} exited with ${proc.exitValue()} ${output.take(100)}")
}
return Pair(output, proc.exitValue())
}
else {
val output = proc.inputStream.bufferedReader().readText().trim() + proc.errorStream.bufferedReader().readText().trim()
proc.destroy()
proc.waitFor()
Log.info("${commands.firstOrNull()} exited ${proc.exitValue()} with timeout")
Pair(output, proc.exitValue())
}
}
catch (e: IOException) {
Log.info(e.message ?: "Unknown IOException occurred")
if (!returnExceptionMessage) {
Pair(null, -1) // Don't print the stacktrace because that is confusing.
}
else {
Pair(e.message, -1)
}
}
catch (e: ProcessNotCreatedException) {
Log.info(e.message ?: "Unknown ProcessNotCreatedException occurred")
// e.g. if the command is just trying if a program can be run or not, and it's not the case
if (!returnExceptionMessage) {
Pair(null, -1)
}
else {
Pair(e.message, -1)
}
}
}
|
mit
|
5e419591928c0bb6646aa33a2c218d0a
| 36.9375 | 165 | 0.627912 | 4.790304 | false | false | false | false |
MehdiK/Humanizer.jvm
|
src/main/kotlin/org/humanizer/jvm/Truncators.kt
|
1
|
2512
|
package org.humanizer.jvm
fun truncateFixedLength(value: String, length: Int, truncationString: String, truncateFrom: TruncateFrom) : String
{
var adjustedLength = length - (truncationString.length() - 1)
var adjustedTruncationString = truncationString
if(adjustedLength <= 0) {
adjustedLength = length + 1
adjustedTruncationString = ""
}
if (value.length() <= length) return value
if (truncateFrom == TruncateFrom.Left) return "${adjustedTruncationString}${value.substring(value.length() - adjustedLength + 1, value.length())}"
return "${value.substring(0, adjustedLength - 1)}${adjustedTruncationString}"
}
fun truncateFixedNumberOfCharacters(value: String, length: Int, truncationString: String, truncateFrom: TruncateFrom) : String {
var adjustedLength = length - (truncationString.length() - 1)
var adjustedTruncationString = truncationString
if (adjustedLength <= 0) {
adjustedLength = length + 1
adjustedTruncationString = ""
}
if (length >= value.count { Character.isLetterOrDigit(it) }) return value
if(truncateFrom == TruncateFrom.Right) {
var t = ""
var l2 = 0
value.forEach {
if (Character.isLetterOrDigit(it)) l2++
if (adjustedLength > l2) {
t = t + it
}
}
return "${t}${adjustedTruncationString}"
}
else {
var t = ""
var l2 = 0
value.reverse().forEach {
if (Character.isLetterOrDigit(it)) l2++
if (adjustedLength > l2) {
t = t + it
}
}
return "${adjustedTruncationString}${t.reverse()}"
}
}
fun truncateFixedNumberOfWords(value: String, length: Int, truncationString: String, truncateFrom: TruncateFrom): String {
if(length >= value.split("\\s+").count()) return value
if(truncateFrom == TruncateFrom.Right){
var t = ""
var l2 = 0
value.forEach {
if (Character.isWhitespace(it)) l2++
if(length > l2){ t = t+it}
}
return "${t}${truncationString}"
}
else {
var t = ""
var l2 = 0
value.trimEnd().reverse().forEach {
if (Character.isWhitespace(it)) l2++
if(length > l2){ t = t+it}
}
return "${truncationString}${t.reverse()}"
}
}
enum class Truncator {
FixedLength
FixedNumberOfCharacters
FixedNumberOfWords
}
enum class TruncateFrom {
Left
Right
}
|
apache-2.0
|
7ba8f3c0e8410568bab4fadca03b4ea0
| 30.797468 | 150 | 0.598328 | 4.131579 | false | false | false | false |
B515/Schedule
|
app/src/main/kotlin/xyz/b515/schedule/ui/view/WeekCoursesFragment.kt
|
1
|
3288
|
package xyz.b515.schedule.ui.view
import android.app.Fragment
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import kotlinx.android.synthetic.main.fragment_week.view.*
import org.jetbrains.anko.startActivity
import xyz.b515.schedule.Constant
import xyz.b515.schedule.R
import xyz.b515.schedule.db.CourseManager
import xyz.b515.schedule.entity.Spacetime
/**
* Created by Yun on 2017.4.24.
*/
class WeekCoursesFragment : Fragment() {
private val manager: CourseManager by lazy { CourseManager(context) }
private val preferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
private var baseHeight: Int = 0
private var baseWidth: Int = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_week, container, false)
showHeaders(view)
showCourses(view)
return view
}
private fun showHeaders(view: View) {
val column = 7
val row = 12
val metrics = resources.displayMetrics
baseHeight = Math.round(metrics.heightPixels * (1.0 / 15.0)).toInt()
baseWidth = Math.round(metrics.widthPixels * (2.0 / 15.0)).toInt()
for (i in 0 until column) {
val tv = TextView(context)
tv.text = resources.getStringArray(R.array.weekdays)[i]
tv.gravity = Gravity.CENTER
tv.width = baseWidth
view.header_weeks.addView(tv)
}
for (i in 1..row) {
val tv = TextView(context)
tv.text = i.toString()
tv.gravity = Gravity.CENTER
tv.height = baseHeight
view.header_time.addView(tv)
}
}
private fun showCourses(view: View) {
val currentWeek = preferences.getInt(Constant.CURRENT_WEEK, -1) + 1
val list = manager.getAllCourse()
list.flatMap { it.spacetimes!! }
.filter { currentWeek in it.startWeek..it.endWeek }
.forEach { this.addCourseToView(it, view) }
}
private fun addCourseToView(spacetime: Spacetime, view: View) {
val course = spacetime.course
val v = LayoutInflater.from(context).inflate(R.layout.item_course_view, view.courses_layout, false) as LinearLayout
val textView = v.findViewById<TextView>(R.id.course_name)
textView.text = "${course.name}\n${spacetime.location}"
v.setBackgroundColor(course.color)
val weekday = if (spacetime.weekday == 1) 7 else spacetime.weekday - 1
v.x = ((weekday - 1) * baseWidth).toFloat()
v.y = ((spacetime.startTime - 1) * baseHeight).toFloat()
view.courses_layout.addView(v)
v.layoutParams.height = (spacetime.endTime - spacetime.startTime + 1) * baseHeight
v.layoutParams.width = baseWidth
v.setOnClickListener {
context.startActivity<CourseDetailActivity>(Constant.TOOLBAR_TITLE to false, Constant.COURSE_ID to course.id)
}
}
}
|
apache-2.0
|
fbd862237a758189ae8c4e1b55016e66
| 36.363636 | 123 | 0.671229 | 4.099751 | false | false | false | false |
FHannes/intellij-community
|
platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.kt
|
5
|
9377
|
/*
* 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 com.intellij.ide.browsers
import com.intellij.CommonBundle
import com.intellij.Patches
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.BrowserUtil
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.PathUtil
import com.intellij.util.io.URLUtil
import org.jetbrains.annotations.Contract
import java.awt.Desktop
import java.io.File
import java.io.IOException
import java.util.*
open class BrowserLauncherAppless : BrowserLauncher() {
companion object {
internal val LOG = Logger.getInstance(BrowserLauncherAppless::class.java)
private fun isDesktopActionSupported(action: Desktop.Action): Boolean {
return !Patches.SUN_BUG_ID_6486393 && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(action)
}
@JvmStatic
fun canUseSystemDefaultBrowserPolicy(): Boolean {
return isDesktopActionSupported(Desktop.Action.BROWSE) ||
SystemInfo.isMac || SystemInfo.isWindows ||
SystemInfo.isUnix && SystemInfo.hasXdgOpen()
}
private val generalSettings: GeneralSettings
get() {
if (ApplicationManager.getApplication() != null) {
GeneralSettings.getInstance()?.let {
return it
}
}
return GeneralSettings()
}
private val defaultBrowserCommand: List<String>?
get() {
if (SystemInfo.isWindows) {
return listOf(ExecUtil.getWindowsShellName(), "/c", "start", GeneralCommandLine.inescapableQuote(""))
}
else if (SystemInfo.isMac) {
return listOf(ExecUtil.getOpenCommandPath())
}
else if (SystemInfo.isUnix && SystemInfo.hasXdgOpen()) {
return listOf("xdg-open")
}
else {
return null
}
}
private fun addArgs(command: GeneralCommandLine, settings: BrowserSpecificSettings?, additional: Array<String>) {
val specific = settings?.additionalParameters ?: emptyList<String>()
if (specific.size + additional.size > 0) {
if (isOpenCommandUsed(command)) {
if (BrowserUtil.isOpenCommandSupportArgs()) {
command.addParameter("--args")
}
else {
LOG.warn("'open' command doesn't allow to pass command line arguments so they will be ignored: " +
StringUtil.join(specific, ", ") + " " + Arrays.toString(additional))
return
}
}
command.addParameters(specific)
command.addParameters(*additional)
}
}
fun isOpenCommandUsed(command: GeneralCommandLine) = SystemInfo.isMac && ExecUtil.getOpenCommandPath() == command.exePath
}
override fun open(url: String) = openOrBrowse(url, false)
override fun browse(file: File) {
var path = file.absolutePath
if (SystemInfo.isWindows && path[0] != '/') {
path = '/' + path
}
openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true)
}
protected open fun browseUsingNotSystemDefaultBrowserPolicy(url: String, settings: GeneralSettings, project: Project?) {
browseUsingPath(url, settings.browserPath, project = project)
}
private fun openOrBrowse(_url: String, browse: Boolean, project: Project? = null) {
val url = signUrl(_url.trim { it <= ' ' })
if (!BrowserUtil.isAbsoluteURL(url)) {
val file = File(url)
if (!browse && isDesktopActionSupported(Desktop.Action.OPEN)) {
if (!file.exists()) {
showError(IdeBundle.message("error.file.does.not.exist", file.path), null, null, null, null)
return
}
try {
Desktop.getDesktop().open(file)
return
}
catch (e: IOException) {
LOG.debug(e)
}
}
browse(file)
return
}
LOG.debug("Launch browser: [$url]")
val settings = generalSettings
if (settings.isUseDefaultBrowser) {
val uri = VfsUtil.toUri(url)
if (uri == null) {
showError(IdeBundle.message("error.malformed.url", url), project = project)
return
}
var tryToUseCli = true
if (isDesktopActionSupported(Desktop.Action.BROWSE)) {
try {
Desktop.getDesktop().browse(uri)
LOG.debug("Browser launched using JDK 1.6 API")
return
}
catch (e: Exception) {
LOG.warn("Error while using Desktop API, fallback to CLI", e)
// if "No application knows how to open", then we must not try to use OS open
tryToUseCli = !e.message!!.contains("Error code: -10814")
}
}
if (tryToUseCli) {
defaultBrowserCommand?.let {
doLaunch(url, it, null, project)
return
}
}
}
browseUsingNotSystemDefaultBrowserPolicy(url, settings, project = project)
}
open protected fun signUrl(url: String): String = url
override final fun browse(url: String, browser: WebBrowser?, project: Project?) {
val effectiveBrowser = getEffectiveBrowser(browser)
// if browser is not passed, UrlOpener should be not used for non-http(s) urls
if (effectiveBrowser == null || (browser == null && !url.startsWith(URLUtil.HTTP_PROTOCOL))) {
openOrBrowse(url, true, project)
}
else {
UrlOpener.EP_NAME.extensions.any { it.openUrl(effectiveBrowser, signUrl(url), project) }
}
}
override fun browseUsingPath(url: String?, browserPath: String?, browser: WebBrowser?, project: Project?, additionalParameters: Array<String>): Boolean {
var browserPathEffective = browserPath
var launchTask: (() -> Unit)? = null
if (browserPath == null && browser != null) {
browserPathEffective = PathUtil.toSystemDependentName(browser.path)
launchTask = { browseUsingPath(url, null, browser, project, additionalParameters) }
}
return doLaunch(url, browserPathEffective, browser, project, additionalParameters, launchTask)
}
private fun doLaunch(url: String?, browserPath: String?, browser: WebBrowser?, project: Project?, additionalParameters: Array<String>, launchTask: (() -> Unit)?): Boolean {
if (!checkPath(browserPath, browser, project, launchTask)) {
return false
}
return doLaunch(url, BrowserUtil.getOpenBrowserCommand(browserPath!!, false), browser, project, additionalParameters, launchTask)
}
@Contract("null, _, _, _ -> false")
fun checkPath(browserPath: String?, browser: WebBrowser?, project: Project?, launchTask: (() -> Unit)?): Boolean {
if (!browserPath.isNullOrBlank()) {
return true
}
val message = browser?.browserNotFoundMessage ?: IdeBundle.message("error.please.specify.path.to.web.browser", CommonBundle.settingsActionPath())
showError(message, browser, project, IdeBundle.message("title.browser.not.found"), launchTask)
return false
}
private fun doLaunch(url: String?, command: List<String>, browser: WebBrowser?, project: Project?, additionalParameters: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY, launchTask: (() -> Unit)? = null): Boolean {
val commandLine = GeneralCommandLine(command)
if (url != null) {
if (url.startsWith("jar:")) {
return false
}
commandLine.addParameter(url)
}
val browserSpecificSettings = browser?.specificSettings
if (browserSpecificSettings != null) {
commandLine.environment.putAll(browserSpecificSettings.environmentVariables)
}
addArgs(commandLine, browserSpecificSettings, additionalParameters)
try {
checkCreatedProcess(browser, project, commandLine, commandLine.createProcess(), launchTask)
return true
}
catch (e: ExecutionException) {
showError(e.message, browser, project, null, null)
return false
}
}
protected open fun checkCreatedProcess(browser: WebBrowser?, project: Project?, commandLine: GeneralCommandLine, process: Process, launchTask: (() -> Unit)?) {
}
protected open fun showError(error: String?, browser: WebBrowser? = null, project: Project? = null, title: String? = null, launchTask: (() -> Unit)? = null) {
// Not started yet. Not able to show message up. (Could happen in License panel under Linux).
LOG.warn(error)
}
open protected fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? = browser
}
|
apache-2.0
|
58bfa59255ce0065c832a94d8d8a5dab
| 35.632813 | 213 | 0.678895 | 4.538722 | false | false | false | false |
GeoffreyMetais/vlc-android
|
application/television/src/main/java/org/videolan/television/ui/FocusableRecyclerView.kt
|
1
|
1719
|
package org.videolan.television.ui
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
import org.videolan.resources.interfaces.FocusListener
import org.videolan.vlc.util.getScreenHeight
/**
* Recyclerview that scrolls the right amount in order to have the focused item always in the middle of the screen
*/
class FocusableRecyclerView : RecyclerView {
private var focusListener: FocusListener? = null
private var screenHeight: Int = 0
constructor(context: Context) : super(context) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
init(context)
}
private fun init(context: Context) {
screenHeight = (context as Activity).getScreenHeight()
this.focusListener = object : FocusListener {
override fun onFocusChanged(position: Int) {
//Center current item on screen
val originalPos = IntArray(2)
val view = layoutManager!!.findViewByPosition(position)
view?.let {
it.getLocationInWindow(originalPos)
val y = originalPos[1]
smoothScrollBy(0, y - screenHeight / 2 + view.height / 2)
}
}
}
}
override fun setAdapter(adapter: Adapter<*>?) {
if (adapter is TvItemAdapter) {
adapter.setOnFocusChangeListener(focusListener)
}
super.setAdapter(adapter)
}
}
|
gpl-2.0
|
469365f6e5573e6bd4a1a89763101402
| 25.859375 | 114 | 0.641652 | 4.925501 | false | false | false | false |
GeoffreyMetais/vlc-android
|
application/vlc-android/test-common/org/videolan/vlc/util/TestUtil.kt
|
1
|
6688
|
/*******************************************************************************
* TestUtil.kt
* ****************************************************************************
* Copyright © 2018 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
******************************************************************************/
package org.videolan.vlc.util
import android.net.Uri
import org.videolan.libvlc.interfaces.IMedia
import org.videolan.resources.TYPE_LOCAL_FAV
import org.videolan.resources.TYPE_NETWORK_FAV
import org.videolan.resources.opensubtitles.OpenSubtitle
import org.videolan.resources.opensubtitles.QueryParameters
import org.videolan.vlc.gui.dialogs.State
import org.videolan.vlc.gui.dialogs.SubtitleItem
object TestUtil {
private const val fakeUri: String = "https://www.videolan.org/fake_"
private const val fakeSubUri: String = "/storage/emulated/0/Android/data/org.videolan.vlc.debug/files/subs/"
private const val fakeMediaUri: String = "/storage/emulated/0/Android/data/org.videolan.vlc.debug/files/media/"
fun createLocalFav(uri: Uri, title: String, iconUrl: String?): org.videolan.vlc.mediadb.models.BrowserFav {
return org.videolan.vlc.mediadb.models.BrowserFav(uri, TYPE_LOCAL_FAV, title, iconUrl)
}
fun createLocalUris(count: Int): List<String> {
return (0 until count).map {
"${fakeMediaUri}local_$it.mp4"
}
}
fun createLocalFavs(count: Int): List<org.videolan.vlc.mediadb.models.BrowserFav> {
return (0 until count).map {
createLocalFav(Uri.parse("${fakeMediaUri}_$it.mp4"), "local$it", null)
}
}
fun createNetworkFav(uri: Uri, title: String, iconUrl: String?): org.videolan.vlc.mediadb.models.BrowserFav {
return org.videolan.vlc.mediadb.models.BrowserFav(uri, TYPE_NETWORK_FAV, title, iconUrl)
}
fun createNetworkUris(count: Int): List<String> {
return (0 until count).map { "${fakeUri}_network$it.mp4" }
}
fun createNetworkFavs(count: Int): List<org.videolan.vlc.mediadb.models.BrowserFav> {
return (0 until count).map {
createNetworkFav(
Uri.parse(fakeUri + "network" + it),
"network" + 1,
null)
}
}
fun createExternalSub(
idSubtitle: String,
subtitlePath: String,
mediaPath: String,
subLanguageID: String,
movieReleaseName: String): org.videolan.vlc.mediadb.models.ExternalSub {
return org.videolan.vlc.mediadb.models.ExternalSub(idSubtitle, subtitlePath, mediaPath, subLanguageID, movieReleaseName)
}
fun createExternalSubsForMedia(mediaPath: String, mediaName: String, count: Int): List<org.videolan.vlc.mediadb.models.ExternalSub> {
return (0 until count).map {
org.videolan.vlc.mediadb.models.ExternalSub(it.toString(), "${fakeSubUri}$mediaName$it", mediaPath, "en", mediaName)
}
}
fun createSubtitleSlave(mediaPath: String, uri: String): org.videolan.vlc.mediadb.models.Slave {
return org.videolan.vlc.mediadb.models.Slave(mediaPath, IMedia.Slave.Type.Subtitle, 2, uri)
}
fun createSubtitleSlavesForMedia(mediaName: String, count: Int): List<org.videolan.vlc.mediadb.models.Slave> {
return (0 until count).map {
createSubtitleSlave("$fakeMediaUri$mediaName", "$fakeSubUri$mediaName$it.srt")
}
}
fun createCustomDirectory(path: String): org.videolan.vlc.mediadb.models.CustomDirectory {
return org.videolan.vlc.mediadb.models.CustomDirectory(path)
}
fun createCustomDirectories(count: Int): List<org.videolan.vlc.mediadb.models.CustomDirectory> {
val directory = "/sdcard/foo"
return (0 until count).map {
createCustomDirectory("$directory$it")
}
}
fun createDownloadingSubtitleItem(
idSubtitle: String,
mediaUri: Uri,
subLanguageID: String,
movieReleaseName: String,
zipDownloadLink: String): SubtitleItem = SubtitleItem(idSubtitle, mediaUri, subLanguageID, movieReleaseName, State.Downloading, zipDownloadLink)
fun createDownloadingSubtitleItem(
idSubtitle: String,
mediaPath: String,
subLanguageID: String,
movieReleaseName: String,
zipDownloadLink: String): SubtitleItem = TestUtil.createDownloadingSubtitleItem(idSubtitle, Uri.parse(mediaPath), subLanguageID, movieReleaseName, zipDownloadLink)
fun createOpenSubtitle(
idSubtitle: String,
subLanguageID: String,
movieReleaseName: String,
zipDownloadLink: String) = OpenSubtitle(
idSubtitle = idSubtitle, subLanguageID = subLanguageID, movieReleaseName = movieReleaseName, zipDownloadLink = zipDownloadLink,
idMovie = "", idMovieImdb = "", idSubMovieFile = "", idSubtitleFile = "", infoFormat = "", infoOther = "", infoReleaseGroup = "",
userID = "", iSO639 = "", movieFPS = "", languageName = "", subActualCD = "", subSumVotes = "", subAuthorComment = "", subComments = "",
score = 0.0, seriesEpisode = "", seriesIMDBParent = "", seriesSeason = "", subAddDate = "", subAutoTranslation = "", subBad = "", subDownloadLink = "",
subDownloadsCnt = "", subEncoding = "", subFeatured = "", subFileName = "", subForeignPartsOnly = "", subFormat = "", subFromTrusted = "", subHash = "",
subHD = "", subHearingImpaired = "", subLastTS = "", subRating = "", subSize = "", subSumCD = "", subtitlesLink = "", subTranslator = "", subTSGroup = "",
subTSGroupHash = "", movieByteSize = "", movieHash = "", movieTimeMS = "", queryParameters = QueryParameters("", "", ""), queryNumber = "",
userNickName = "", userRank = "", matchedBy = "", movieImdbRating = "", movieKind = "", movieName = "", movieNameEng = "", movieYear = "")
}
|
gpl-2.0
|
dcaaec2531c81ae0e3ff59f571b547b1
| 48.902985 | 175 | 0.64274 | 4.311412 | false | false | false | false |
didi/DoraemonKit
|
Android/dokit-gps-mock/src/main/java/com/didichuxing/doraemonkit/gps_mock/gpsmock/GpsMockProxyManager.kt
|
1
|
9061
|
package com.didichuxing.doraemonkit.gps_mock.gpsmock
import android.location.Location
import android.location.LocationListener
import com.amap.api.location.AMapLocationListener
import com.amap.api.navi.AMapNaviListener
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocationListener
import com.didichuxing.doraemonkit.gps_mock.gpsmock.LocationHooker.LocationListenerProxy
import com.didichuxing.doraemonkit.gps_mock.map.*
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
/**
* 三方地图管理类
*/
object GpsMockProxyManager {
private val mAMapLocationListenerProxies: MutableList<AMapLocationListenerProxy?> = ArrayList()
private val mAMapLocationChangedListenerProxies: MutableList<AMapLocationChangedListenerProxy?> =
ArrayList()
private val mAMapNaviListenerProxies: MutableList<AMapNaviListenerProxy?> = ArrayList()
private val mBDAbsLocationListenerProxies: MutableList<BDAbsLocationListenerProxy?> =
ArrayList()
private val mBDLocationListenerProxies: MutableList<BDLocationListenerProxy?> = ArrayList()
private val mTencentLocationListenerProxies: MutableList<TencentLocationListenerProxy?> =
ArrayList()
private val mLocationListenerProxies: MutableList<LocationListenerProxy> = ArrayList()
private val mDMapLocationListenerProxies: MutableList<DMapLocationListener> = ArrayList()
private val mDMapNaviListenerProxies: MutableList<DMapLocationListener?> = ArrayList()
fun addAMapLocationListenerProxy(aMapLocationListenerProxy: AMapLocationListenerProxy) {
mAMapLocationListenerProxies.add(aMapLocationListenerProxy)
}
fun addAMapLocationChangedListenerProxy(aMapLocationChangedListenerProxy: AMapLocationChangedListenerProxy) {
mAMapLocationChangedListenerProxies.add(aMapLocationChangedListenerProxy)
}
fun addAMapNaviListenerProxy(aMapNaviListenerProxy: AMapNaviListenerProxy) {
mAMapNaviListenerProxies.add(aMapNaviListenerProxy)
}
fun addBDAbsLocationListenerProxy(bdAbsLocationListenerProxy: BDAbsLocationListenerProxy) {
mBDAbsLocationListenerProxies.add(bdAbsLocationListenerProxy)
}
fun addBDLocationListenerProxy(bdLocationListenerProxy: BDLocationListenerProxy) {
mBDLocationListenerProxies.add(bdLocationListenerProxy)
}
fun addTencentLocationListenerProxy(tencentLocationListenerProxy: TencentLocationListenerProxy) {
mTencentLocationListenerProxies.add(tencentLocationListenerProxy)
}
fun addDMapLocationListenerProxy(locationListenerProxy: DMapLocationListener) {
mDMapLocationListenerProxies.add(locationListenerProxy)
}
fun addDMapNaviListenerProxy( dMapNaviListener: DMapLocationListener){
mDMapNaviListenerProxies.add(dMapNaviListener)
}
fun addLocationListenerProxy(locationListenerProxy: LocationListenerProxy) {
mLocationListenerProxies.add(locationListenerProxy)
}
fun removeAMapLocationListener(listener: AMapLocationListener) {
val it = mAMapLocationListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy?.aMapLocationListener === listener) {
it.remove()
}
}
}
fun removeAMapNaviListener(listener: AMapNaviListener) {
val it = mAMapNaviListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy?.aMapNaviListener === listener) {
it.remove()
}
}
}
fun removeTencentLocationListener(listener: TencentLocationListener) {
val it = mTencentLocationListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy?.mTencentLocationListener === listener) {
it.remove()
}
}
}
fun removeBDLocationListener(listener: BDLocationListener) {
val it = mBDLocationListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy?.mBdLocationListener === listener) {
it.remove()
}
}
}
fun removeBDAbsLocationListener(listener: BDAbstractLocationListener) {
val it = mBDAbsLocationListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy?.mBdLocationListener === listener) {
it.remove()
}
}
}
fun removeLocationListener(listener: LocationListener) {
val it = mLocationListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy.locationListener === listener) {
it.remove()
}
}
}
fun removeDMapLocationListener(listener: DMapLocationListener) {
val it = mDMapLocationListenerProxies.iterator()
while (it.hasNext()) {
val proxy = it.next()
if (proxy.getDMapLocation() === listener) {
it.remove()
}
}
}
fun clearProxy() {
mAMapLocationListenerProxies.clear()
mBDAbsLocationListenerProxies.clear()
mBDLocationListenerProxies.clear()
mTencentLocationListenerProxies.clear()
mLocationListenerProxies.clear()
}
fun mockLocationWithNotify(location: Location?) {
if (location == null) return
try {
notifyLocationListenerProxy(location)
} catch (e: Exception) {
e.printStackTrace()
}
try {
notifyAMapLocationListenerProxy(location)
} catch (e: Exception) {
e.printStackTrace()
}
try {
notifyBDAbsLocationListenerProxy(location)
} catch (e: Exception) {
e.printStackTrace()
}
try {
notifyBDLocationListenerProxy(location)
} catch (e: Exception) {
e.printStackTrace()
}
try {
notifyTencentLocationListenerProxy(location)
} catch (e: Exception) {
e.printStackTrace()
}
try {
notifyDMapLocationListenerProxy(location)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun notifyAMapLocationListenerProxy(location: Location?) {
if (location != null) {
//location
for (aMapLocationListenerProxy in mAMapLocationListenerProxies) {
aMapLocationListenerProxy?.onLocationChanged(LocationBuilder.toAMapLocation(location))
}
//location source
for (aMapLocationChangedListenerProxy in mAMapLocationChangedListenerProxies) {
aMapLocationChangedListenerProxy?.onLocationChanged(location)
}
if (GpsMockManager.mockAMapNavLocation()) {
for (aMapNaviListenerProxy in mAMapNaviListenerProxies) {
aMapNaviListenerProxy?.onLocationChange(
LocationBuilder.toAMapNaviLocation(
location
)
)
}
}
}
}
private fun notifyBDAbsLocationListenerProxy(location: Location?) {
if (location != null) {
for (bdAbsLocationListenerProxy in mBDAbsLocationListenerProxies) {
bdAbsLocationListenerProxy?.onReceiveLocation(LocationBuilder.toBdLocation(location))
}
}
}
private fun notifyBDLocationListenerProxy(location: Location?) {
if (location != null) {
for (bdLocationListenerProxy in mBDLocationListenerProxies) {
bdLocationListenerProxy?.onReceiveLocation(LocationBuilder.toBdLocation(location))
}
}
}
private fun notifyTencentLocationListenerProxy(location: Location?) {
if (location != null) {
for (tencentLocationListenerProxy in mTencentLocationListenerProxies) {
tencentLocationListenerProxy?.onLocationChanged(
LocationBuilder.toTencentLocation(
location
), TencentLocation.ERROR_OK, ""
)
}
}
}
private fun notifyLocationListenerProxy(location: Location?) {
if (location != null) {
for (systemLocationListenerProxy in mLocationListenerProxies) {
systemLocationListenerProxy.onLocationChanged(location)
}
}
}
private fun notifyDMapLocationListenerProxy(location: Location?) {
if (location != null) {
for (dMapLocationListener in mDMapLocationListenerProxies){
dMapLocationListener.onLocationChange(location)
}
for (dMapNavLocationListener in mDMapNaviListenerProxies){
dMapNavLocationListener?.onLocationChange(location)
}
}
}
}
|
apache-2.0
|
9820061606d054e1a79c6e347d01ebb4
| 34.758893 | 113 | 0.653145 | 5.082584 | false | false | false | false |
nickthecoder/paratask
|
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/IntField.kt
|
1
|
5174
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters.fields
import javafx.scene.control.Spinner
import javafx.scene.control.SpinnerValueFactory
import javafx.scene.input.KeyEvent
import uk.co.nickthecoder.paratask.gui.ApplicationActions
import uk.co.nickthecoder.paratask.parameters.IntParameter
class IntField(val intParameter: IntParameter)
: ParameterField(intParameter) {
private var dirty = false
override fun createControl(): Spinner<*> {
val spinner = createSpinner()
spinner.valueFactory.converter = intParameter.converter
spinner.editableProperty().set(true)
spinner.editor.addEventHandler(KeyEvent.KEY_PRESSED, { event ->
if (ApplicationActions.SPINNER_INCREMENT.match(event)) {
try {
spinner.increment(1)
} catch (e: Exception) {
// Do nothing when spinner's editor contains an invalid number
}
event.consume()
} else if (ApplicationActions.SPINNER_DECREMENT.match(event)) {
try {
spinner.decrement(1)
} catch (e: Exception) {
// Do nothing when spinner's editor contains an invalid number
}
event.consume()
} else if (ApplicationActions.ENTER.match(event)) {
processEnter()
event.consume()
}
})
spinner.editor.textProperty().addListener({ _, _, newValue: String ->
try {
val v = intParameter.converter.fromString(newValue)
if (intParameter.expression == null) {
spinner.valueFactory.value = v
}
showOrClearError(intParameter.errorMessage(v))
dirty = false
} catch (e: Exception) {
showError("Not an integer")
dirty = true
}
})
return spinner
}
override fun isDirty(): Boolean = dirty
/**
* Spinners normally consume the ENTER key, which means the default button won't be run when ENTER is
* pressed in a Spinner. My Spinner doesn't need to handle the ENTER key, and therefore, this code
* re-introduces the expected behaviour of the ENTER key (i.e. performing the default button's action).
*/
private fun processEnter() {
val defaultRunnable = control?.scene?.accelerators?.get(ApplicationActions.ENTER.keyCodeCombination)
defaultRunnable?.let { defaultRunnable.run() }
}
private fun createSpinner(): Spinner<*> {
val spinner = Spinner(IntSpinnerValueFactory(intParameter.minValue..intParameter.maxValue, intParameter.value))
if (intParameter.expression == null) {
intParameter.value = spinner.valueFactory.value
}
spinner.editor.prefColumnCount = intParameter.columnCount
spinner.valueFactory.valueProperty().bindBidirectional(intParameter.valueProperty)
return spinner
}
class IntSpinnerValueFactory(
val min: Int = Integer.MIN_VALUE,
val max: Int = Integer.MAX_VALUE,
initialValue: Int? = null,
val amountToStepBy: Int = 1)
: SpinnerValueFactory<Int?>() {
constructor(range: IntRange, initialValue: Int? = null, amountToStepBy: Int = 1)
: this(range.start, range.endInclusive, initialValue, amountToStepBy)
init {
value = initialValue
valueProperty().addListener { _, _, newValue: Int? ->
value = newValue
}
}
private fun add(from: Int?, diff: Int): Int {
if (from == null) {
// Set to 0, or min/max if 0 is not within the range
if (min > 0) {
return min
} else if (max < 0) {
return max
} else {
return 0
}
} else {
return from + diff
}
}
override fun decrement(steps: Int) {
val newValue: Int = add(value, -steps * amountToStepBy)
value = if (newValue >= min) newValue else if (isWrapAround) max else min
}
override fun increment(steps: Int) {
val newValue: Int = add(value, steps * amountToStepBy)
value = if (newValue <= max) newValue else if (isWrapAround) min else max
}
}
}
|
gpl-3.0
|
62970590f6c6a78405a5958758365723
| 34.9375 | 119 | 0.600309 | 4.858216 | false | false | false | false |
jonalmeida/focus-android
|
app/src/main/java/org/mozilla/focus/fragment/UrlInputFragment.kt
|
1
|
30671
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.SharedPreferences
import android.content.res.Configuration
import android.graphics.drawable.TransitionDrawable
import android.os.Bundle
import android.preference.PreferenceManager
import android.text.InputType
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.URLUtil
import android.widget.FrameLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.fragment_urlinput.*
import kotlinx.android.synthetic.main.fragment_urlinput.view.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import mozilla.components.browser.domains.CustomDomains
import mozilla.components.browser.domains.autocomplete.CustomDomainsProvider
import mozilla.components.browser.domains.autocomplete.DomainAutocompleteResult
import mozilla.components.browser.domains.autocomplete.ShippedDomainsProvider
import mozilla.components.browser.session.Session
import mozilla.components.support.utils.ThreadUtils
import mozilla.components.ui.autocomplete.InlineAutocompleteEditText
import mozilla.components.ui.autocomplete.InlineAutocompleteEditText.AutocompleteResult
import org.mozilla.focus.R
import org.mozilla.focus.R.string.pref_key_homescreen_tips
import org.mozilla.focus.R.string.teaser
import org.mozilla.focus.ext.isSearch
import org.mozilla.focus.ext.requireComponents
import org.mozilla.focus.locale.LocaleAwareAppCompatActivity
import org.mozilla.focus.locale.LocaleAwareFragment
import org.mozilla.focus.menu.home.HomeMenu
import org.mozilla.focus.searchsuggestions.SearchSuggestionsViewModel
import org.mozilla.focus.searchsuggestions.ui.SearchSuggestionsFragment
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.tips.Tip
import org.mozilla.focus.tips.TipManager
import org.mozilla.focus.utils.AppConstants
import org.mozilla.focus.utils.Features
import org.mozilla.focus.utils.OneShotOnPreDrawListener
import org.mozilla.focus.utils.Settings
import org.mozilla.focus.utils.StatusBarUtils
import org.mozilla.focus.utils.SupportUtils
import org.mozilla.focus.utils.UrlUtils
import org.mozilla.focus.utils.ViewUtils
import org.mozilla.focus.whatsnew.WhatsNew
import java.util.Objects
import kotlin.coroutines.CoroutineContext
class FocusCrashException : Exception()
/**
* Fragment for displaying the URL input controls.
*/
// Refactoring the size and function count of this fragment is non-trivial at this point.
// Therefore we ignore those violations for now.
@Suppress("LargeClass", "TooManyFunctions")
class UrlInputFragment :
LocaleAwareFragment(),
View.OnClickListener,
SharedPreferences.OnSharedPreferenceChangeListener,
CoroutineScope {
companion object {
@JvmField
val FRAGMENT_TAG = "url_input"
private const val duckDuckGo = "DuckDuckGo"
private val ARGUMENT_ANIMATION = "animation"
private val ARGUMENT_X = "x"
private val ARGUMENT_Y = "y"
private val ARGUMENT_WIDTH = "width"
private val ARGUMENT_HEIGHT = "height"
private val ARGUMENT_SESSION_UUID = "sesssion_uuid"
private val ANIMATION_BROWSER_SCREEN = "browser_screen"
private val ANIMATION_DURATION = 200
private val TIPS_ALPHA = 0.65f
private lateinit var searchSuggestionsViewModel: SearchSuggestionsViewModel
@JvmStatic
fun createWithoutSession(): UrlInputFragment {
val arguments = Bundle()
val fragment = UrlInputFragment()
fragment.arguments = arguments
return fragment
}
@JvmStatic
fun createWithSession(session: Session, urlView: View): UrlInputFragment {
val arguments = Bundle()
arguments.putString(ARGUMENT_SESSION_UUID, session.id)
arguments.putString(ARGUMENT_ANIMATION, ANIMATION_BROWSER_SCREEN)
val screenLocation = IntArray(2)
urlView.getLocationOnScreen(screenLocation)
arguments.putInt(ARGUMENT_X, screenLocation[0])
arguments.putInt(ARGUMENT_Y, screenLocation[1])
arguments.putInt(ARGUMENT_WIDTH, urlView.width)
arguments.putInt(ARGUMENT_HEIGHT, urlView.height)
val fragment = UrlInputFragment()
fragment.arguments = arguments
return fragment
}
/**
* Create a new UrlInputFragment with a gradient background (and the Focus logo). This configuration
* is usually shown if there's no content to be shown below (e.g. the current website).
*/
@JvmStatic
fun createWithBackground(): UrlInputFragment {
val arguments = Bundle()
val fragment = UrlInputFragment()
fragment.arguments = arguments
return fragment
}
}
private var job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
private val shippedDomainsProvider = ShippedDomainsProvider()
private val customDomainsProvider = CustomDomainsProvider()
private var useShipped = false
private var useCustom = false
private var displayedPopupMenu: HomeMenu? = null
@Volatile
private var isAnimating: Boolean = false
private var session: Session? = null
private val isOverlay: Boolean
get() = session != null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
searchSuggestionsViewModel = ViewModelProviders.of(this).get(SearchSuggestionsViewModel::class.java)
PreferenceManager.getDefaultSharedPreferences(context)
.registerOnSharedPreferenceChangeListener(this)
// Get session from session manager if there's a session UUID in the fragment's arguments
arguments?.getString(ARGUMENT_SESSION_UUID)?.let { id ->
session = requireComponents.sessionManager.findSessionById(id)
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
childFragmentManager.beginTransaction()
.replace(searchViewContainer.id, SearchSuggestionsFragment.create())
.commit()
searchSuggestionsViewModel.selectedSearchSuggestion.observe(this, Observer {
val isSuggestion = searchSuggestionsViewModel.searchQuery.value != it
it?.let {
if (searchSuggestionsViewModel.alwaysSearch) {
onSearch(it, false, true)
} else {
onSearch(it, isSuggestion)
}
}
})
}
override fun onResume() {
super.onResume()
if (job.isCancelled) {
job = Job()
}
activity?.let {
val settings = Settings.getInstance(it.applicationContext)
useCustom = settings.shouldAutocompleteFromCustomDomainList()
useShipped = settings.shouldAutocompleteFromShippedDomainList()
shippedDomainsProvider.initialize(it.applicationContext)
customDomainsProvider.initialize(it.applicationContext)
}
StatusBarUtils.getStatusBarHeight(keyboardLinearLayout) {
adjustViewToStatusBarHeight(it)
}
}
override fun onPause() {
job.cancel()
super.onPause()
}
private fun updateTipsLabel() {
val context = context ?: return
val tip = TipManager.getNextTipIfAvailable(context)
updateSubtitle(tip)
}
private fun updateSubtitle(tip: Tip?) {
if (tip == null) {
showFocusSubtitle()
return
}
val tipText = String.format(tip.text, System.getProperty("line.separator"))
keyboardLinearLayout.homeViewTipsLabel.alpha = TIPS_ALPHA
if (tip.deepLink == null) {
homeViewTipsLabel.text = tipText
return
}
// Only make the second line clickable if applicable
val linkStartIndex =
if (tipText.contains("\n")) tipText.indexOf("\n") + 2
else 0
keyboardLinearLayout.homeViewTipsLabel.movementMethod = LinkMovementMethod()
homeViewTipsLabel.setText(tipText, TextView.BufferType.SPANNABLE)
val deepLinkAction = object : ClickableSpan() {
override fun onClick(p0: View) {
tip.deepLink.invoke()
}
}
val textWithDeepLink = SpannableString(tipText).apply {
setSpan(deepLinkAction, linkStartIndex, tipText.length, 0)
val colorSpan = ForegroundColorSpan(homeViewTipsLabel.currentTextColor)
setSpan(colorSpan, linkStartIndex, tipText.length, 0)
}
homeViewTipsLabel.text = textWithDeepLink
}
private fun showFocusSubtitle() {
keyboardLinearLayout.homeViewTipsLabel.text = getString(teaser)
keyboardLinearLayout.homeViewTipsLabel.alpha = 1f
keyboardLinearLayout.homeViewTipsLabel.setOnClickListener(null)
}
private fun adjustViewToStatusBarHeight(statusBarHeight: Int) {
val inputHeight = resources.getDimension(R.dimen.urlinput_height)
if (keyboardLinearLayout.layoutParams is ViewGroup.MarginLayoutParams) {
val marginParams = keyboardLinearLayout.layoutParams as ViewGroup.MarginLayoutParams
marginParams.topMargin = (inputHeight + statusBarHeight).toInt()
}
urlInputLayout.layoutParams.height = (inputHeight + statusBarHeight).toInt()
if (searchViewContainer.layoutParams is ViewGroup.MarginLayoutParams) {
val marginParams = searchViewContainer.layoutParams as ViewGroup.MarginLayoutParams
marginParams.topMargin = (inputHeight + statusBarHeight).toInt()
}
if (addToAutoComplete.layoutParams is ViewGroup.MarginLayoutParams) {
val marginParams = addToAutoComplete.layoutParams as ViewGroup.MarginLayoutParams
marginParams.topMargin = (inputHeight + statusBarHeight).toInt()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?):
View? = inflater.inflate(R.layout.fragment_urlinput, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
listOf(dismissView, clearView).forEach { it.setOnClickListener(this) }
urlView?.setOnFilterListener(::onFilter)
urlView?.setOnTextChangeListener(::onTextChange)
urlView?.imeOptions = urlView.imeOptions or ViewUtils.IME_FLAG_NO_PERSONALIZED_LEARNING
urlView?.inputType = urlView.inputType or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
if (urlInputContainerView != null) {
OneShotOnPreDrawListener(urlInputContainerView) {
animateFirstDraw()
true
}
}
if (isOverlay) {
keyboardLinearLayout?.visibility = View.GONE
} else {
backgroundView?.setBackgroundResource(R.drawable.background_gradient)
dismissView?.visibility = View.GONE
menuView?.visibility = View.VISIBLE
menuView?.setOnClickListener(this)
}
urlView?.setOnCommitListener(::onCommit)
val geckoViewAndDDG: Boolean =
Settings.getInstance(requireContext()).defaultSearchEngineName == duckDuckGo &&
AppConstants.isGeckoBuild
session?.let {
urlView?.setText(
if (it.isSearch &&
!geckoViewAndDDG &&
Features.SEARCH_TERMS_OR_URL
)
it.searchTerms else
it.url
)
clearView?.visibility = View.VISIBLE
searchViewContainer?.visibility = View.GONE
addToAutoComplete?.visibility = View.VISIBLE
}
addToAutoComplete.setOnClickListener {
val url = urlView?.text.toString()
addUrlToAutocomplete(url)
}
updateTipsLabel()
}
override fun applyLocale() {
if (isOverlay) {
activity?.supportFragmentManager
?.beginTransaction()
?.replace(
R.id.container,
UrlInputFragment.createWithSession(session!!, urlView),
UrlInputFragment.FRAGMENT_TAG)
?.commit()
} else {
activity?.supportFragmentManager
?.beginTransaction()
?.replace(
R.id.container,
UrlInputFragment.createWithBackground(),
UrlInputFragment.FRAGMENT_TAG)
?.commit()
}
}
fun onBackPressed(): Boolean {
if (isOverlay) {
animateAndDismiss()
return true
}
return false
}
override fun onStart() {
super.onStart()
activity?.let {
if (Settings.getInstance(it.applicationContext).shouldShowFirstrun()) return@onStart }
showKeyboard()
}
override fun onStop() {
super.onStop()
// Reset the keyboard layout to avoid a jarring animation when the view is started again. (#1135)
keyboardLinearLayout?.reset()
}
fun showKeyboard() {
ViewUtils.showKeyboard(urlView)
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
if (newConfig?.orientation != Configuration.ORIENTATION_UNDEFINED) {
//This is a hack to make the HomeMenu actually stick on top of the menuView (#3287)
displayedPopupMenu?.let {
it.dismiss()
OneShotOnPreDrawListener(menuView) {
showHomeMenu(menuView)
false
}
}
}
}
// This method triggers the complexity warning. However it's actually not that hard to understand.
@Suppress("ComplexMethod")
override fun onClick(view: View) {
when (view.id) {
R.id.clearView -> clear()
R.id.dismissView -> if (isOverlay) {
animateAndDismiss()
} else {
clear()
}
R.id.menuView -> showHomeMenu(view)
R.id.whats_new -> context?.let {
TelemetryWrapper.openWhatsNewEvent(WhatsNew.shouldHighlightWhatsNew(it))
WhatsNew.userViewedWhatsNew(it)
val url = SupportUtils.getSumoURLForTopic(it, SupportUtils.SumoTopic.WHATS_NEW)
val session = Session(url, source = Session.Source.MENU)
requireComponents.sessionManager.add(session, selected = true)
}
R.id.settings -> (activity as LocaleAwareAppCompatActivity).openPreferences()
R.id.help -> {
val session = Session(SupportUtils.HELP_URL, source = Session.Source.MENU)
requireComponents.sessionManager.add(session, selected = true)
}
else -> throw IllegalStateException("Unhandled view in onClick()")
}
}
private fun clear() {
urlView?.setText("")
urlView?.requestFocus()
}
private fun showHomeMenu(anchor: View) = context?.let {
displayedPopupMenu = HomeMenu(it, this)
displayedPopupMenu?.show(anchor)
displayedPopupMenu?.dismissListener = {
displayedPopupMenu = null
}
}
private fun addUrlToAutocomplete(url: String) {
var duplicateURL = false
val job = launch(IO) {
duplicateURL = CustomDomains.load(requireContext()).contains(url)
if (duplicateURL) return@launch
CustomDomains.add(requireContext(), url)
TelemetryWrapper.saveAutocompleteDomainEvent(TelemetryWrapper.AutoCompleteEventSource.QUICK_ADD)
}
job.invokeOnCompletion {
requireActivity().runOnUiThread {
val messageId =
if (!duplicateURL)
R.string.preference_autocomplete_add_confirmation
else
R.string.preference_autocomplete_duplicate_url_error
ViewUtils.showBrandedSnackbar(Objects.requireNonNull<View>(view), messageId, 0)
animateAndDismiss()
}
}
}
override fun onDetach() {
super.onDetach()
// On detach, the PopupMenu is no longer relevant to other content (e.g. BrowserFragment) so dismiss it.
// Note: if we don't dismiss the PopupMenu, its onMenuItemClick method references the old Fragment, which now
// has a null Context and will cause crashes.
displayedPopupMenu?.dismiss()
}
private fun animateFirstDraw() {
if (ANIMATION_BROWSER_SCREEN == arguments?.getString(ARGUMENT_ANIMATION)) {
playVisibilityAnimation(false)
}
}
private fun animateAndDismiss() {
ThreadUtils.assertOnUiThread()
if (isAnimating) {
// We are already animating some state change. Ignore all other requests.
return
}
// Don't allow any more clicks: dismissView is still visible until the animation ends,
// but we don't want to restart animations and/or trigger hiding again (which could potentially
// cause crashes since we don't know what state we're in). Ignoring further clicks is the simplest
// solution, since dismissView is about to disappear anyway.
dismissView?.isClickable = false
if (ANIMATION_BROWSER_SCREEN == arguments?.getString(ARGUMENT_ANIMATION)) {
playVisibilityAnimation(true)
} else {
dismiss()
}
}
/**
* This animation is quite complex. The 'reverse' flag controls whether we want to show the UI
* (false) or whether we are going to hide it (true). Additionally the animation is slightly
* different depending on whether this fragment is shown as an overlay on top of other fragments
* or if it draws its own background.
*/
// This method correctly triggers a complexity warning. This method is indeed very and too complex.
// However refactoring it is not trivial at this point so we ignore the warning for now.
@Suppress("ComplexMethod")
private fun playVisibilityAnimation(reverse: Boolean) {
if (isAnimating) {
// We are already animating, let's ignore another request.
return
}
isAnimating = true
val xyOffset = (if (isOverlay)
(urlInputContainerView?.layoutParams as FrameLayout.LayoutParams).bottomMargin
else
0).toFloat()
if (urlInputBackgroundView != null) {
val width = urlInputBackgroundView.width.toFloat()
val height = urlInputBackgroundView.height.toFloat()
val widthScale = if (isOverlay)
(width + 2 * xyOffset) / width
else
1f
val heightScale = if (isOverlay)
(height + 2 * xyOffset) / height
else
1f
if (!reverse) {
urlInputBackgroundView?.pivotX = 0f
urlInputBackgroundView?.pivotY = 0f
urlInputBackgroundView?.scaleX = widthScale
urlInputBackgroundView?.scaleY = heightScale
urlInputBackgroundView?.translationX = -xyOffset
urlInputBackgroundView?.translationY = -xyOffset
clearView?.alpha = 0f
}
// Let the URL input use the full width/height and then shrink to the actual size
urlInputBackgroundView.animate()
.setDuration(ANIMATION_DURATION.toLong())
.scaleX(if (reverse) widthScale else 1f)
.scaleY(if (reverse) heightScale else 1f)
.alpha((if (reverse && isOverlay) 0 else 1).toFloat())
.translationX(if (reverse) -xyOffset else 0f)
.translationY(if (reverse) -xyOffset else 0f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
if (reverse) {
clearView?.alpha = 0f
}
}
override fun onAnimationEnd(animation: Animator) {
if (reverse) {
if (isOverlay) {
dismiss()
}
} else {
clearView?.alpha = 1f
}
isAnimating = false
}
})
}
// We only need to animate the toolbar if we are an overlay.
if (isOverlay) {
val screenLocation = IntArray(2)
urlView?.getLocationOnScreen(screenLocation)
val leftDelta = arguments!!.getInt(ARGUMENT_X) - screenLocation[0] - urlView.paddingLeft
if (!reverse) {
urlView?.pivotX = 0f
urlView?.pivotY = 0f
urlView?.translationX = leftDelta.toFloat()
}
if (urlView != null) {
// The URL moves from the right (at least if the lock is visible) to it's actual position
urlView.animate()
.setDuration(ANIMATION_DURATION.toLong())
.translationX((if (reverse) leftDelta else 0).toFloat())
}
}
if (!reverse) {
clearView?.alpha = 0f
}
if (toolbarBackgroundView != null) {
val transitionDrawable = toolbarBackgroundView?.background as TransitionDrawable
if (reverse) {
transitionDrawable.reverseTransition(ANIMATION_DURATION)
toolbarBottomBorder?.visibility = View.VISIBLE
if (!isOverlay) {
dismissView?.visibility = View.GONE
menuView?.visibility = View.VISIBLE
}
} else {
transitionDrawable.startTransition(ANIMATION_DURATION)
toolbarBottomBorder?.visibility = View.GONE
}
}
}
private fun dismiss() {
// This method is called from animation callbacks. In the short time frame between the animation
// starting and ending the activity can be paused. In this case this code can throw an
// IllegalStateException because we already saved the state (of the activity / fragment) before
// this transaction is committed. To avoid this we commit while allowing a state loss here.
// We do not save any state in this fragment (It's getting destroyed) so this should not be a problem.
activity?.supportFragmentManager
?.beginTransaction()
?.remove(this)
?.commitAllowingStateLoss()
}
private fun onCommit() {
val input = if (urlView.autocompleteResult == null) {
urlView?.text.toString()
} else {
urlView.autocompleteResult!!.text.let {
if (it.isEmpty() || !URLUtil.isValidUrl(urlView?.text.toString())) {
urlView?.text.toString()
} else it
}
}
if (!input.trim { it <= ' ' }.isEmpty()) {
handleCrashTrigger(input)
ViewUtils.hideKeyboard(urlView)
if (handleL10NTrigger(input)) return
val (isUrl, url, searchTerms) = normalizeUrlAndSearchTerms(input)
openUrl(url, searchTerms)
if (urlView.autocompleteResult != null) {
TelemetryWrapper.urlBarEvent(isUrl, urlView.autocompleteResult!!)
}
}
}
// This isn't that complex, and is only used for l10n screenshots.
@Suppress("ComplexMethod")
private fun handleL10NTrigger(input: String): Boolean {
if (!AppConstants.isDevBuild) return false
var triggerHandled = true
when (input) {
"l10n:tip:1" -> updateSubtitle(Tip.createTrackingProtectionTip(requireContext()))
"l10n:tip:2" -> updateSubtitle(Tip.createHomescreenTip(requireContext()))
"l10n:tip:3" -> updateSubtitle(Tip.createDefaultBrowserTip(requireContext()))
"l10n:tip:4" -> updateSubtitle(Tip.createAutocompleteURLTip(requireContext()))
"l10n:tip:5" -> updateSubtitle(Tip.createOpenInNewTabTip(requireContext()))
"l10n:tip:6" -> updateSubtitle(Tip.createRequestDesktopTip(requireContext()))
"l10n:tip:7" -> updateSubtitle(Tip.createAllowlistTip(requireContext()))
else -> triggerHandled = false
}
if (triggerHandled) clear()
return triggerHandled
}
private fun handleCrashTrigger(input: String) {
if (input == "focus:crash") {
throw FocusCrashException()
}
}
private fun normalizeUrlAndSearchTerms(input: String): Triple<Boolean, String, String?> {
val isUrl = UrlUtils.isUrl(input)
val url = if (isUrl)
UrlUtils.normalize(input)
else
UrlUtils.createSearchUrl(context, input)
val searchTerms = if (isUrl)
null
else
input.trim { it <= ' ' }
return Triple(isUrl, url, searchTerms)
}
private fun onSearch(query: String, isSuggestion: Boolean = false, alwaysSearch: Boolean = false) {
if (alwaysSearch) {
openUrl(UrlUtils.createSearchUrl(context, query), query)
} else {
val searchTerms = if (UrlUtils.isUrl(query)) null else query
val searchUrl =
if (searchTerms != null) UrlUtils.createSearchUrl(context, searchTerms) else UrlUtils.normalize(query)
openUrl(searchUrl, searchTerms)
}
TelemetryWrapper.searchSelectEvent(isSuggestion)
}
private fun openUrl(url: String, searchTerms: String?) {
if (!searchTerms.isNullOrEmpty()) {
session?.searchTerms = searchTerms
}
val fragmentManager = requireActivity().supportFragmentManager
// Replace all fragments with a fresh browser fragment. This means we either remove the
// HomeFragment with an UrlInputFragment on top or an old BrowserFragment with an
// UrlInputFragment.
val browserFragment = fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG)
if (browserFragment != null && browserFragment is BrowserFragment && browserFragment.isVisible) {
// Reuse existing visible fragment - in this case we know the user is already browsing.
// The fragment might exist if we "erased" a browsing session, hence we need to check
// for visibility in addition to existence.
browserFragment.loadUrl(url)
// And this fragment can be removed again.
fragmentManager.beginTransaction()
.remove(this)
.commit()
} else {
val session = Session(url, source = Session.Source.USER_ENTERED)
if (!searchTerms.isNullOrEmpty()) {
session.searchTerms = searchTerms
}
requireComponents.sessionManager.add(session, selected = true)
}
}
private fun onFilter(searchText: String) {
onFilter(searchText, urlView)
}
@Suppress("ComplexMethod")
private fun onFilter(searchText: String, view: InlineAutocompleteEditText?) {
// If the UrlInputFragment has already been hidden, don't bother with filtering. Because of the text
// input architecture on Android it's possible for onFilter() to be called after we've already
// hidden the Fragment, see the relevant bug for more background:
// https://github.com/mozilla-mobile/focus-android/issues/441#issuecomment-293691141
if (!isVisible) {
return
}
view?.let {
var result: DomainAutocompleteResult? = null
if (useCustom) {
result = customDomainsProvider.getAutocompleteSuggestion(searchText)
}
if (useShipped && result == null) {
result = shippedDomainsProvider.getAutocompleteSuggestion(searchText)
}
if (result != null) {
view.applyAutocompleteResult(AutocompleteResult(
result.text, result.source, result.totalItems, { result.url }))
} else {
view.noAutocompleteResult()
}
}
}
private fun onTextChange(text: String, @Suppress("UNUSED_PARAMETER") autocompleteText: String) {
searchSuggestionsViewModel.setSearchQuery(text)
if (text.trim { it <= ' ' }.isEmpty()) {
clearView?.visibility = View.GONE
searchViewContainer?.visibility = View.GONE
addToAutoComplete?.visibility = View.GONE
if (!isOverlay) {
playVisibilityAnimation(true)
}
} else {
clearView?.visibility = View.VISIBLE
menuView?.visibility = View.GONE
if (!isOverlay && dismissView?.visibility != View.VISIBLE) {
playVisibilityAnimation(false)
dismissView?.visibility = View.VISIBLE
}
searchViewContainer?.visibility = View.VISIBLE
addToAutoComplete?.visibility = View.GONE
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == activity?.getString(pref_key_homescreen_tips)) { updateTipsLabel() }
}
}
|
mpl-2.0
|
d6d1023026e471b1c1a302eed2a781fd
| 35.687799 | 118 | 0.62815 | 5.177414 | false | false | false | false |
jraska/github-client
|
feature/identity/src/main/java/com/jraska/github/client/identity/internal/SessionIdProvider.kt
|
1
|
808
|
package com.jraska.github.client.identity.internal
import com.jraska.github.client.identity.SessionId
import com.jraska.github.client.time.TimeProvider
import org.threeten.bp.Duration
internal class SessionIdProvider(private val timeProvider: TimeProvider) {
private var lastQueriedTime = Long.MIN_VALUE
private var sessionId = SessionId.newSessionId()
private val lock = Any()
fun sessionId(): SessionId {
val elapsed = timeProvider.elapsed()
synchronized(lock) {
val inactivityTime = elapsed - lastQueriedTime
if (inactivityTime > SESSION_THRESHOLD_MS) {
sessionId = SessionId.newSessionId()
}
lastQueriedTime = elapsed
}
return sessionId
}
companion object {
internal val SESSION_THRESHOLD_MS = Duration.ofMinutes(15).toMillis()
}
}
|
apache-2.0
|
d4bb118ae84ff3d12a5ed50fb75ccd7c
| 26.862069 | 74 | 0.733911 | 4.391304 | false | false | false | false |
kotlin-graphics/uno-sdk
|
core/src/main/kotlin/uno/mousePole/mousePoles.kt
|
1
|
22282
|
//package uno.mousePole
//
////import com.jogamp.newt.event.KeyEvent
////import com.jogamp.newt.event.MouseEvent
//import gli_.has
//import gli_.hasnt
//import glm_.glm
//import glm_.mat4x4.Mat4
//import glm_.quat.Quat
//import glm_.vec2.Vec2d
//import glm_.vec2.Vec2i
//import glm_.vec3.Vec3
//import uno.mousePole.ViewPole.RotateMode as Rm
//import uno.mousePole.ViewPole.TargetOffsetDir as Tod
//import org.lwjgl.glfw.GLFW.*
//
///**
// * Created by elect on 17/03/17.
// */
//
///**
// * Created by elect on 17/03/17.
// */
//
//interface ViewProvider {
// /** Computes the camera matrix. */
// fun calcMatrix(res: Mat4 = Mat4()): Mat4
//}
//
///** Utility object containing the ObjectPole's position and orientation information. */
//class ObjectData(
// /** The world-space position of the object. */
// var position: Vec3,
// /** The world-space orientation of the object. */
// var orientation: Quat)
//
//private val axisVectors = arrayOf(
// Vec3(1, 0, 0),
// Vec3(0, 1, 0),
// Vec3(0, 0, 1))
//
//enum class Axis { X, Y, Z, MAX }
//enum class RotateMode { DUAL_AXIS, BIAXIAL, SPIN }
//
//
//fun calcRotationQuat(axis: Axis, radAngle: Float, res: Quat) = glm.angleAxis(radAngle, axisVectors[axis.ordinal], res)
//
///**
// * Mouse-based control over the orientation and position of an object.
// *
// * This Pole deals with three spaces: local, world, and view. Local refers to the coordinate system of vertices given
// * to the matrix that this Pole generates. World represents the \em output coordinate system. So vertices enter in
// * local and are transformed to world. Note that this does not have to actually be the real world-space. It could be
// * the space of the parent node in some object hierarchy, though there is a caveat below.
// *
// * View represents the space that vertices are transformed into by the ViewProvider's matrix.
// * The ViewProvider is given to this class's constructor. The assumption that this Pole makes when using the view space
// * matrix is that the matrix the ObjectPole generates will be right-multiplied by the view matrix given by the
// * ViewProvider. So it is assumed that there is no intermediate space between world and view.
// *
// * By defining these three spaces, it is possible to dictate orientation relative to these spaces.
// * The ViewProvider exists to allow transformations relative to the current camera.
// *
// * This Pole is given an action button, which it will listen for click events from. When the action button is held down
// * and the mouse moved, the object's orientation will change. The orientation will be relative to the view's
// * orientation if a ViewProvider was provided. If not, it will be relative to the world.
// *
// * If no modifier keys (shift, ctrl, alt) were held when the click was given, then the object will be oriented in both
// * the X and Y axes of the transformation space. If the CTRL key is held when the click was given, then the object will
// * only rotate around either the X or Y axis.
// * The selection is based on whether the X or the Y mouse coordinate is farthest from the initial position when
// * dragging started.
// * If the ALT key is held, then the object will rotate about the Z axis, and only the X position of the mouse affects
// * the object.
// */
//class ObjectPole
///**
// * Creates an object pole with a given initial position and orientation.
// *
// * @param po The starting position and orientation of the object in world space.
// * @param rotateScale The number of degrees to rotate the object per window space pixel
// * @param actionButton The mouse button to listen for. All other mouse buttons are ignored.
// * @param view An object that will compute a view matrix. This defines the view space that orientations
// * can be relative to. If it is NULL, then orientations will be relative to the world.
// */
//constructor(
// private var po: ObjectData,
// /** The scaling factor is the number of degrees to rotate the object per window space pixel.
// * The scale is the same for all mouse movements. */
// private var rotateScale: Float,
// private var actionButton: Short,
// private var view: ViewProvider?) : ViewProvider {
//
//
// private var initialPo = po
//
// // Used when rotating.
// private var rotateMode = RotateMode.DUAL_AXIS
// private var isDragging = false
//
// private var prevMousePos = Vec2i()
// private var startDragMousePos = Vec2i()
// private var startDragOrient = Quat()
//
//
// /** Generates the local-to-world matrix for this object. */
// @Synchronized override fun calcMatrix(res: Mat4): Mat4 {
//
// res put 1f
// res.set(3, po.position, 1f)
//
// res *= po.orientation to mat4[3]
//
// return res
// }
//
// /** Retrieves the current position and orientation of the object. */
// val posOrient get() = po
//
// /** Resets the object to the initial position/orientation. Will fail if currently dragging. */
// fun reset() {
// if (!isDragging) {
// po.position put initialPo.position
// po.orientation put initialPo.orientation
// }
// }
//
//
// /* Input Providers
// *
// * These functions provide input, since Poles cannot get input for themselves. */
//
// /**
// * Notifies the pole of a mouse button being pressed or released.
// *
// * @param event The mouse event */
// @Synchronized
// fun mousePressed(event: MouseEvent) {
//
// // Ignore button presses when dragging.
// if (!isDragging)
//
// if (event.button == actionButton) {
//
// rotateMode = when {
// event.isAltDown -> RotateMode.SPIN
// event.isControlDown -> RotateMode.BIAXIAL
// else -> RotateMode.DUAL_AXIS
// }
//
// prevMousePos.put(event.x, event.y)
// startDragMousePos.put(event.x, event.y)
// startDragOrient put po.orientation
//
// isDragging = true
// }
// }
//
// @Synchronized
// fun mouseReleased(event: MouseEvent) {
//
// // Ignore up buttons if not dragging.
// if (isDragging)
//
// if (event.button == actionButton) {
//
// mouseDragged(event)
//
// isDragging = false
// }
// }
//
// /** Notifies the pole that the mouse has moved to the given absolute position. */
// @Synchronized
// fun mouseDragged(event: MouseEvent) {
//
// if (isDragging) {
//
// val position = vec2i[0](event.x, event.y)
// val diff = position.minus(prevMousePos, vec2i[1])
//
// when (rotateMode) {
//
// RotateMode.DUAL_AXIS -> {
//
// val rot = calcRotationQuat(Axis.Y, glm.radians(diff.x * rotateScale), quat[0])
// calcRotationQuat(Axis.X, glm.radians(diff.y * rotateScale), quat[1]).times(rot, rot).normalizeAssign()
// rotateView(rot)
// }
//
// RotateMode.BIAXIAL -> {
//
// val initDiff = position.minus(startDragMousePos, vec2i[2])
//
// var axis = Axis.X
// var degAngle = initDiff.y * rotateScale
//
// if (glm.abs(initDiff.x) > glm.abs(initDiff.y)) {
// axis = Axis.Y
// degAngle = initDiff.x * rotateScale
// }
// val rot = calcRotationQuat(axis, glm.radians(degAngle), quat[0])
// rotateView(rot, true)
// }
//
// RotateMode.SPIN -> rotateView(calcRotationQuat(Axis.Z, glm.radians(-diff.x * rotateScale), quat[0]))
// }
// prevMousePos put position
// }
// }
//
// fun rotateWorld(rot: Quat, fromInitial: Boolean = false) {
//
// val fromInitial_ = if (isDragging) fromInitial else false
//
// val orient = if (fromInitial_) startDragOrient else po.orientation
// po.orientation = rot.times(orient, quat[2]).normalizeAssign()
// }
//
// fun rotateLocal(rot: Quat, fromInitial: Boolean = false) {
//
// val fromInitial_ = if (isDragging) fromInitial else false
//
// val orient = if (fromInitial_) startDragOrient else po.orientation
// po.orientation = orient.times(rot, quat[3]).normalizeAssign()
// }
//
// fun rotateView(rot: Quat, fromInitial: Boolean = false) {
//
// val fromInitial_ = if (isDragging) fromInitial else false
//
// if (view != null) {
//
// val viewQuat = view!!.calcMatrix(mat4[0]) to quat[4]
// val invViewQuat = viewQuat.conjugate(quat[5])
// val orient = if (fromInitial_) startDragOrient else po.orientation
//
// (rot.times(orient, po.orientation)).normalizeAssign()
//
// } else
// rotateWorld(rot, fromInitial_)
// }
//}
//
//
///** Utility object containing the ViewPole's view information. */
//class ViewData(
// /** The starting target position position. */
// var targetPos: Vec3,
// /** The initial orientation aroudn the target position. */
// var orient: Quat,
// /** The initial radius of the camera from the target point. */
// var radius: Float,
// /** The initial spin rotation of the "up" axis, relative to \a orient */
// var degSpinRotation: Float)
//
///** Utility object describing the scale of the ViewPole. */
//class ViewScale(
// /** The closest the radius to the target point can get. */
// var minRadius: Float,
// /** The farthest the radius to the target point can get. */
// var maxRadius: Float,
// /** The radius change to use when the SHIFT key isn't held while mouse wheel scrolling. */
// var largeRadiusDelta: Float,
// /** The radius change to use when the SHIFT key \em is held while mouse wheel scrolling. */
// var smallRadiusDelta: Float,
// /** The position offset to use when the SHIFT key isn't held while pressing a movement key. */
// var largePosOffset: Float,
// /** The position offset to use when the SHIFT key \em is held while pressing a movement key. */
// var smallPosOffset: Float,
// /** The number of degrees to rotate the view per window space pixel the mouse moves when dragging. */
// var rotationScale: Float)
//
///**
// * Mouse-based control over the orientation and position of the camera.
// *
// * This view controller is based on a target point, which is centered in the camera, and an orientation around that
// * target point that represents the camera. The Pole allows the user to rotate around this point, move closer to/farther
// * from it, and to move the point itself.
// *
// * This Pole is given a ViewData object that contains the initial viewing orientation, as well as a ViewScale that
// * represents how fast the various movements change the view, as well as its limitations.
// *
// * This Pole is given an action button, which it will listen for click events from. If the mouse button is clicked and
// * no modifiers are pressed, the the view will rotate around the object in both the view-local X and Y axes. If the CTRL
// * key is held, then it will rotate about the X or Y axes, based on how far the mouse is from the starting point in the
// * X or Y directions. If the ALT key is held, then the camera will spin in the view-local Z direction.
// *
// * Scrolling the mouse wheel up or down moves the camera closer or farther from the object, respectively.
// * The distance is taken from ViewScale::largeRadiusDelta. If the SHIFT key is held while scrolling, then the movement
// * will be the ViewScale::smallRadiusDelta value instead.
// *
// * The target point can be moved, relative to the current view, with the WASD keys. W/S move forward and backwards,
// * while A/D move left and right, respectively. Q and E move down and up, respectively. If the rightKeyboardCtrl
// * parameter of the constructor is set, then it uses the IJKLUO keys instead of WASDQE. The offset applied to the
// * position is ViewScale::largePosOffset; if SHIFT is held, then ViewScale::smallPosOffset is used instead.
// */
//class ViewPole
///**
// * Creates a view pole with the given initial target position, view definition, and action button.
// *
// * @param currView The starting state of the view.
// * @param viewScale The viewport definition to use.
// * @param actionButton The mouse button to listen for. All other mouse buttons are ignored.
// * \param bRightKeyboardCtrls If true, then it uses IJKLUO instead of WASDQE keys.
// */
//constructor(
// private var currView: ViewData,
// private var viewScale: ViewScale,
// private var actionButton: Int = GLFW_MOUSE_BUTTON_1,
// private var rightKeyboardCtrls: Boolean = false) : ViewProvider {
//
// private var initialView = currView
//
// //Used when rotating.
// var isDragging = false
// private set
// private var rotateMode = Rm.DUAL_AXIS_ROTATE
//
// private var degStartDragSpin = 0f
// private var startDragMouseLoc = Vec2i()
// private val startDragOrient = Quat()
//
//
// var rotationScale
// /** Gets the current scaling factor for orientation changes. */
// get() = viewScale.rotationScale
// /** Sets the scaling factor for orientation changes.
// *
// * The scaling factor is the number of degrees to rotate the view per window space pixel.
// * The scale is the same for all mouse movements. */
// set(value) {
// viewScale.rotationScale = value
// }
//
// /** Retrieves the current viewing information. */
// val view get() = currView
//
//
// /** Generates the world-to-camera matrix for the view. */
// @Synchronized override fun calcMatrix(res: Mat4): Mat4 {
//
// res put 1f
//
// // Remember: these transforms are in reverse order.
//
// /* In this space, we are facing in the correct direction. Which means that the camera point is directly behind
// * us by the radius number of units. */
// res.translateAssign(0f, 0f, -currView.radius)
//
// //Rotate the world to look in the right direction..
// val fullRotation = glm.angleAxis(currView.degSpinRotation, 0f, 0f, 1f, quat[6])
// fullRotation *= currView.orient
// res *= (fullRotation to mat4[1])
//
// // Translate the world by the negation of the lookat point, placing the origin at the lookat point.
// res.translateAssign(-currView.targetPos.x, -currView.targetPos.y, -currView.targetPos.z)
//
// return res
// }
//
// /** Resets the view to the initial view. Will fail if currently dragging. */
// fun reset() {
// if (!isDragging) currView = initialView
// }
//
// fun processXChange(xDiff: Int, clearY: Boolean = false) {
//
// val radAngleDiff = glm.radians(xDiff * viewScale.rotationScale)
//
// // Rotate about the world-space Y axis.
// glm.angleAxis(radAngleDiff, 0f, 1f, 0f, quat[7])
// startDragOrient.times(quat[8], currView.orient)
// }
//
// fun processYChange(yDiff: Int, clearXZ: Boolean = false) {
//
// val radAngleDiff = glm.radians(yDiff * viewScale.rotationScale)
//
// // Rotate about the local-space X axis.
// glm.angleAxis(radAngleDiff, 1f, 0f, 0f, quat[9])
// quat[9].times(startDragOrient, currView.orient)
// }
//
// fun processXYChange(xDiff: Int, yDiff: Int) {
//
// val radXAngleDiff = glm.radians(xDiff * viewScale.rotationScale)
// val radYAngleDiff = glm.radians(yDiff * viewScale.rotationScale)
//
// // Rotate about the world-space Y axis.
// glm.angleAxis(radXAngleDiff, 0f, 0f, 1f, quat[10])
// startDragOrient.times(quat[10], currView.orient)
// //Rotate about the local-space X axis.
// glm.angleAxis(radYAngleDiff, 1f, 0f, 0f, quat[11])
// quat[11].times(currView.orient, currView.orient)
// }
//
// fun processSpinAxis(xDiff: Int, yDiff: Int) {
//
// val degSpinDiff = xDiff * viewScale.rotationScale
// currView.degSpinRotation = degSpinDiff + degStartDragSpin
// }
//
// fun beginDragRotate(start: Vec2i, rotMode: RotateMode) {
//
// rotateMode = rotMode
//
// startDragMouseLoc put start
//
// degStartDragSpin = currView.degSpinRotation
//
// startDragOrient put currView.orient
//
// isDragging = true
// }
//
// fun onDragRotate(curr: Vec2i) {
//
// val diff = curr.minus(startDragMouseLoc, vec2i[3])
//
// when (rotateMode) {
//
// Rm.DUAL_AXIS_ROTATE -> processXYChange(diff.x, diff.y)
//
// Rm.BIAXIAL_ROTATE ->
// if (glm.abs(diff.x) > glm.abs(diff.y))
// processXChange(diff.x, true)
// else
// processYChange(diff.y, true)
//
// Rm.XZ_AXIS_ROTATE -> processXChange(diff.x)
//
// Rm.Y_AXIS_ROTATE -> processYChange(diff.y)
//
// Rm.SPIN_VIEW_AXIS -> processSpinAxis(diff.x, diff.y)
// }
// }
//
// fun endDragRotate(end: Vec2i, keepResult: Boolean = true) {
//
// if (keepResult)
// onDragRotate(end)
// else
// currView.orient put startDragOrient
//
// isDragging = false
// }
//
// fun moveCloser(largeStep: Boolean = true) {
//
// currView.radius -= if (largeStep) viewScale.largeRadiusDelta else viewScale.smallRadiusDelta
//
// if (currView.radius < viewScale.minRadius)
// currView.radius = viewScale.minRadius
// }
//
// fun moveAway(largeStep: Boolean = true) {
//
// currView.radius += if (largeStep) viewScale.largeRadiusDelta else viewScale.smallRadiusDelta
//
// if (currView.radius > viewScale.maxRadius)
// currView.radius = viewScale.maxRadius
// }
//
// /**
// * Input Providers
// *
// * These functions provide input, since Poles cannot get input for themselves. See \ref module_glutil_poles
// * "the Pole manual" for details. */
// @Synchronized
// fun mouseClick(button: Int, action: Int, mods: Int) {
// lastMods = mods
// if (action == GLFW_PRESS) {
// // Ignore all other button presses when dragging.
// if (!isDragging)
// if (button == actionButton)
// beginDragRotate(lastPos, when {
// ctrlDown -> Rm.BIAXIAL_ROTATE
// altDown -> Rm.SPIN_VIEW_AXIS
// else -> Rm.DUAL_AXIS_ROTATE
// })
// } else {
// // Ignore all other button releases when not dragging
// if (isDragging)
// if (button == actionButton)
// if (rotateMode == Rm.DUAL_AXIS_ROTATE || rotateMode == Rm.SPIN_VIEW_AXIS || rotateMode == Rm.BIAXIAL_ROTATE)
// endDragRotate(vec2i[4].apply { put(lastPos) })
// }
// }
//
// fun mouseMove(position: Vec2i) {
// if (isDragging)
// onDragRotate(vec2i[5].apply { put(position) })
// lastPos put position
// }
//
// @Synchronized
// fun mouseWheel(scroll: Vec2d) = if (scroll.y > 0) moveCloser(shiftUp) else moveAway(shiftUp)
//
// @Synchronized
// fun buttonPressed(event: KeyEvent) {
//
// val distance = if (event.isShiftDown) viewScale.largePosOffset else viewScale.smallPosOffset
//
// when (event.keyCode) {
//
// KeyEvent.VK_W -> offsetTargetPos(Tod.FORWARD, distance)
// KeyEvent.VK_K -> offsetTargetPos(Tod.BACKWARD, distance)
// KeyEvent.VK_L -> offsetTargetPos(Tod.RIGHT, distance)
// KeyEvent.VK_J -> offsetTargetPos(Tod.LEFT, distance)
// KeyEvent.VK_O -> offsetTargetPos(Tod.UP, distance)
// KeyEvent.VK_U -> offsetTargetPos(Tod.DOWN, distance)
// }
// }
//
// fun offsetTargetPos(dir: Tod, worldDistance: Float) {
//
// val offsetDir = offsets[dir.ordinal]
// offsetTargetPos(offsetDir.times(worldDistance, vec3[0]))
// }
//
// fun offsetTargetPos(cameraoffset: Vec3) {
//
// val currMat = calcMatrix(mat4[2])
// val orientation = currMat.to(quat[12])
//
// val invOrient = orientation.conjugate(quat[13])
// val worldOffset = invOrient.times(cameraoffset, vec3[1])
//
// currView.targetPos plusAssign worldOffset
// }
//
// fun keyPressed(key: Int, scancode: Int, action: Int, mods: Int) {
// lastMods = mods
// val distance = if (shiftDown) viewScale.smallPosOffset else viewScale.largePosOffset
// when (key) {
// GLFW_KEY_W -> offsetTargetPos(Tod.FORWARD, distance)
// GLFW_KEY_S -> offsetTargetPos(Tod.BACKWARD, distance)
// GLFW_KEY_D -> offsetTargetPos(Tod.RIGHT, distance)
// GLFW_KEY_A -> offsetTargetPos(Tod.LEFT, distance)
// GLFW_KEY_E -> offsetTargetPos(Tod.UP, distance)
// GLFW_KEY_Q -> offsetTargetPos(Tod.DOWN, distance)
// }
// }
//
// val offsets = arrayOf(
// Vec3(+0f, +1f, +0f),
// Vec3(+0f, -1f, +0f),
// Vec3(+0f, +0f, -1f),
// Vec3(+0f, +0f, +1f),
// Vec3(+1f, +0f, +0f),
// Vec3(-1f, +0f, +0f))
//
// enum class TargetOffsetDir { UP, DOWN, FORWARD, BACKWARD, RIGHT, LEFT }
//
// enum class RotateMode { DUAL_AXIS_ROTATE, BIAXIAL_ROTATE, XZ_AXIS_ROTATE, Y_AXIS_ROTATE, SPIN_VIEW_AXIS }
//
// var lastMods = 0
// val shiftUp get() = lastMods hasnt GLFW_MOD_SHIFT
// val shiftDown get() = lastMods has GLFW_MOD_SHIFT
// val ctrlDown get() = lastMods has GLFW_MOD_CONTROL
// val altDown get() = lastMods has GLFW_MOD_ALT
// val lastPos = Vec2i()
//}
//
//private val mat4 = Array(4, { Mat4() })
//private val vec2i = Array(2, { Vec2i() })
//private val vec3 = Array(2, { Vec3() })
//private val quat = Array(13, { Quat() })
|
mit
|
4d6d5790048a858e0b2ca0efd6f34ede
| 38.161687 | 130 | 0.613545 | 3.573697 | false | false | false | false |
ibaton/3House
|
mobile/src/main/java/treehou/se/habit/ui/adapter/MenuAdapter.kt
|
1
|
2438
|
package treehou.se.habit.ui.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import treehou.se.habit.R
import java.util.*
class MenuAdapter : RecyclerView.Adapter<MenuAdapter.MenuHolder>() {
private val items = ArrayList<MenuItem>()
private var listener: OnItemSelectListener = DummyListener()
inner class MenuHolder(view: View) : RecyclerView.ViewHolder(view) {
val lblName: TextView
val imgImage: ImageView
init {
lblName = view.findViewById<View>(R.id.lbl_label) as TextView
imgImage = view.findViewById<View>(R.id.img_menu) as ImageView
}
}
override fun onCreateViewHolder(parent: ViewGroup, position: Int): MenuHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.item_menu, parent, false)
return MenuHolder(itemView)
}
override fun onBindViewHolder(serverHolder: MenuHolder, position: Int) {
val item = items[position]
serverHolder.imgImage.setImageResource(item.resource)
serverHolder.lblName.text = item.label
serverHolder.itemView.setOnClickListener { v -> listener.itemClicked(item.id) }
}
override fun getItemCount(): Int {
return items.size
}
fun getItem(position: Int): MenuItem {
return items[position]
}
fun addItem(item: MenuItem) {
items.add(0, item)
notifyItemInserted(0)
}
fun removeItem(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
fun removeItem(item: MenuItem) {
val position = items.indexOf(item)
items.removeAt(position)
notifyItemRemoved(position)
}
fun clear() {
this.items.clear()
notifyDataSetChanged()
}
fun addAll(items: List<MenuItem>) {
for (item in items) {
this.items.add(0, item)
notifyItemRangeInserted(0, items.size)
}
}
fun setOnItemSelectListener(listener: OnItemSelectListener) {
this.listener = listener
}
internal inner class DummyListener : OnItemSelectListener {
override fun itemClicked(id: Int) {}
}
interface OnItemSelectListener {
fun itemClicked(id: Int)
}
}
|
epl-1.0
|
260ac9ea8cf45e8e193c785198300e96
| 25.791209 | 87 | 0.664479 | 4.448905 | false | false | false | false |
bbodi/KotlinReactSpringBootstrap
|
frontend/src/com/github/andrewoma/react/DomProperties.kt
|
1
|
14587
|
package com.github.andrewoma.react
import org.w3c.dom.Window
import org.w3c.dom.events.Event
// TODO
interface EventTarget {
val value: String
}
// TODO
interface DataTransfer {
}
// TODO
class Style {
}
interface SyntheticEvent {
var bubbles: Boolean
var cancelable: Boolean
var currentTarget: EventTarget
var defaultPrevented: Boolean
var eventPhase: Int
var nativeEvent: Event
var type: String
var timeStamp: Date
fun preventDefault(): Unit
fun stopPropagation(): Unit
}
interface ClipboardEvent : SyntheticEvent {
var clipboardData: DataTransfer
}
interface KeyboardEvent : SyntheticEvent {
var altKey: Boolean
var ctrlKey: Boolean
var charCode: Int
var key: String
var keyCode: Int
var locale: String
var location: Int
var metaKey: Boolean
var repeat: Boolean
var shiftKey: Boolean
var which: Int
}
interface FocusEvent : SyntheticEvent {
var relatedTarget: EventTarget
}
interface FormEvent : SyntheticEvent {
}
interface MouseEvent : SyntheticEvent {
var altKey: Boolean
var button: Int
var buttons: Int
var clientX: Int
var clientY: Int
var ctrlKey: Boolean
var pageX: Int
var pageY: Int
var relatedTarget: EventTarget
var screenX: Int
var screenY: Int
var shiftKey: Boolean
}
interface TouchEvent : SyntheticEvent {
var altKey: Boolean
var changedTouches: TouchEvent
var ctrlKey: Boolean
var metaKey: Boolean
var shiftKey: Boolean
var targetTouches: Any//DOMTouchList
var touches: Any//DOMTouchList
}
interface UIEvent : SyntheticEvent {
var detail: Int
var view: Window
}
interface WheelEvent {
var deltaX: Int
var deltaMode: Int
var deltaY: Int
var deltaZ: Int
}
open class ReactProperties {
open var key: String? by Property()
// it can be String or (DOM|ReactComponent<Any, Any>) -> Unit
open var ref: dynamic by Property()
var onCopy: ((event: ClipboardEvent) -> Unit)? by Property()
var onCut: ((event: ClipboardEvent) -> Unit)? by Property()
var onPaste: ((event: ClipboardEvent) -> Unit)? by Property()
var onKeyDown: ((event: KeyboardEvent) -> Unit)? by Property()
var onKeyPress: ((event: KeyboardEvent) -> Unit)? by Property()
var onKeyUp: ((event: KeyboardEvent) -> Unit)? by Property()
var onFocus: ((event: FocusEvent) -> Unit)? by Property()
var onBlur: ((event: FocusEvent) -> Unit)? by Property()
var onChange: ((event: FormEvent) -> Unit)? by Property()
var onInput: ((event: FormEvent) -> Unit)? by Property()
var onSubmit: ((event: FormEvent) -> Unit)? by Property()
var onClick: ((event: MouseEvent) -> Unit)? by Property()
var onDoubleClick: ((event: MouseEvent) -> Unit)? by Property()
var onDrag: ((event: MouseEvent) -> Unit)? by Property()
var onDragEnd: ((event: MouseEvent) -> Unit)? by Property()
var onDragEnter: ((event: MouseEvent) -> Unit)? by Property()
var onDragExit: ((event: MouseEvent) -> Unit)? by Property()
var onDragLeave: ((event: MouseEvent) -> Unit)? by Property()
var onDragOver: ((event: MouseEvent) -> Unit)? by Property()
var onDragStart: ((event: MouseEvent) -> Unit)? by Property()
var onDrop: ((event: MouseEvent) -> Unit)? by Property()
var onMouseDown: ((event: MouseEvent) -> Unit)? by Property()
var onMouseEnter: ((event: MouseEvent) -> Unit)? by Property()
var onMouseLeave: ((event: MouseEvent) -> Unit)? by Property()
var onMouseMove: ((event: MouseEvent) -> Unit)? by Property()
var onMouseUp: ((event: MouseEvent) -> Unit)? by Property()
var onTouchCancel: ((event: TouchEvent) -> Unit)? by Property()
var onTouchEnd: ((event: TouchEvent) -> Unit)? by Property()
var onTouchMove: ((event: TouchEvent) -> Unit)? by Property()
var onTouchStart: ((event: TouchEvent) -> Unit)? by Property()
var onScroll: ((event: UIEvent) -> Unit)? by Property()
var onWheel: ((event: WheelEvent) -> Unit)? by Property()
}
open class HtmlGlobalProperties : ReactProperties() {
override var key: String? by Property()
var accessKey: String? by Property()
var className: String? by Property()
var contentEditable: String? by Property()
var contextMenu: String? by Property()
var dir: String? by Property()
var draggable: Boolean? by Property()
var hidden: Boolean? by Property()
var id: String? by Property()
var lang: String? by Property()
var spellCheck: Boolean? by Property()
var role: String? by Property()
var scrollLeft: Int? by Property()
var scrollTop: Int? by Property()
var style: Style? by Property()
}
class FormProperties : HtmlGlobalProperties() {
var accept: String? by Property()
var action: String? by Property()
var autoCapitalize: String? by Property()
var autoComplete: String? by Property()
var encType: String? by Property()
var method: String? by Property()
var name: String? by Property()
var target: String? by Property()
}
open class InputProperties : HtmlGlobalProperties() {
var accept: String? by Property()
var alt: String? by Property()
var autoCapitalize: String? by Property()
var autoComplete: String? by Property()
var autoFocus: Boolean? by Property()
var checked: Any? by Property()
var defaultValue: Any? by Property()
var disabled: Boolean? by Property()
var form: String? by Property()
var height: Int? by Property()
var list: String? by Property()
var max: Int? by Property()
var maxLength: Int? by Property()
var min: Int? by Property()
var multiple: Boolean? by Property()
var name: String? by Property()
var pattern: String? by Property()
var placeholder: String? by Property()
var readOnly: Boolean? by Property()
var required: Boolean? by Property()
var size: Int? by Property()
var src: String? by Property()
var step: Int? by Property()
var type: InputType by Property()
var value: String? by Property()
var width: Int? by Property()
var formAction: String? by Property()
var formEncType: String? by Property()
var formMethod: String? by Property()
var formTarget: String? by Property()
}
object InputType {
val Text: InputType = js("'text'")
val Button: InputType = js("'button'")
val Color: InputType = js("'color'")
val Date: InputType = js("'date'")
val Datetime: InputType = js("'datetime'")
val Hidden: InputType = js("'hidden'")
val Number: InputType = js("'number'")
val Password: InputType = js("'password'")
val Textarea: InputType = js("'textarea'")
val Checkbox: InputType = js("'checkbox'")
val Select: InputType = js("'select'")
}
class IframeProperties : HtmlGlobalProperties() {
var allowFullScreen: Boolean? by Property()
var allowTransparency: Boolean? by Property()
var frameBorder: Int? by Property()
var height: Int? by Property()
var name: String? by Property()
var src: String? by Property()
var width: Int? by Property()
var marginHeight: String? by Property()
var marginWidth: String? by Property()
}
class AppletProperties : HtmlGlobalProperties() {
var alt: String? by Property()
}
class AreaProperties : HtmlGlobalProperties() {
var alt: String? by Property()
var href: String? by Property()
var rel: String? by Property()
var target: String? by Property()
}
class ImgProperties : HtmlGlobalProperties() {
var alt: String? by Property()
var height: Int? by Property()
var src: String? by Property()
var width: Int? by Property()
}
class ButtonProperties : HtmlGlobalProperties() {
var autoFocus: Boolean? by Property()
var disabled: Boolean? by Property()
var form: String? by Property()
var name: String? by Property()
var type: String? by Property()
var value: String? by Property()
}
class KeygenProperties : HtmlGlobalProperties() {
var autoFocus: Boolean? by Property()
var form: String? by Property()
var name: String? by Property()
}
class SelectProperties : HtmlGlobalProperties() {
var autoFocus: Boolean? by Property()
var disabled: Boolean? by Property()
var form: String? by Property()
var multiple: Boolean? by Property()
var name: String? by Property()
var required: Boolean? by Property()
var size: Int? by Property()
}
class TextareaProperties : HtmlGlobalProperties() {
var autoFocus: Boolean? by Property()
var form: String? by Property()
var maxLength: String? by Property()
var name: String? by Property()
var placeholder: String? by Property()
var readOnly: String? by Property()
var required: Boolean? by Property()
}
class AudioProperties : HtmlGlobalProperties() {
var autoPlay: Boolean? by Property()
var controls: Boolean? by Property()
var loop: Boolean? by Property()
var preload: String? by Property()
var src: String? by Property()
}
class VideoProperties : HtmlGlobalProperties() {
var autoPlay: Boolean? by Property()
var controls: Boolean? by Property()
var height: Int? by Property()
var loop: Boolean? by Property()
var poster: String? by Property()
var preload: String? by Property()
var src: String? by Property()
var width: Int? by Property()
}
class TableProperties : HtmlGlobalProperties() {
var cellPadding: Int? by Property()
var cellSpacing: Int? by Property()
}
class MetaProperties : HtmlGlobalProperties() {
var charSet: String? by Property()
var content: String? by Property()
var httpEquiv: String? by Property()
var name: String? by Property()
}
class ScriptProperties : HtmlGlobalProperties() {
var charSet: String? by Property()
var src: String? by Property()
var type: String? by Property()
}
class CommandProperties : HtmlGlobalProperties() {
var checked: Boolean? by Property()
var icon: String? by Property()
var radioGroup: String? by Property()
var type: String? by Property()
}
class TdProperties : HtmlGlobalProperties() {
var colSpan: Int? by Property()
var rowSpan: Int? by Property()
}
class ThProperties : HtmlGlobalProperties() {
var colSpan: Int? by Property()
var rowSpan: Int? by Property()
}
class ObjectProperties : HtmlGlobalProperties() {
var data: String? by Property()
var form: String? by Property()
var height: Int? by Property()
var name: String? by Property()
var type: String? by Property()
var width: Int? by Property()
var wmode: String? by Property()
}
class DelProperties : HtmlGlobalProperties() {
var dateTime: Date? by Property()
}
class InsProperties : HtmlGlobalProperties() {
var dateTime: Date? by Property()
}
class TimeProperties : HtmlGlobalProperties() {
var dateTime: Date? by Property()
}
class FieldsetProperties : HtmlGlobalProperties() {
var form: String? by Property()
var name: String? by Property()
}
class LabelProperties : HtmlGlobalProperties() {
var form: String? by Property()
var htmlFor: String? by Property()
}
class MeterProperties : HtmlGlobalProperties() {
var form: String? by Property()
var max: Int? by Property()
var min: Int? by Property()
var value: Int? by Property()
var high: Int? by Property()
var low: Int? by Property()
var optimum: Int? by Property()
}
class OutputProperties : HtmlGlobalProperties() {
var form: String? by Property()
var htmlFor: String? by Property()
var name: String? by Property()
}
class ProgressProperties : HtmlGlobalProperties() {
var form: String? by Property()
var max: Int? by Property()
var value: Int? by Property()
}
class CanvasProperties : HtmlGlobalProperties() {
var height: Int? by Property()
var width: Int? by Property()
}
class EmbedProperties : HtmlGlobalProperties() {
var height: Int? by Property()
var src: String? by Property()
var type: String? by Property()
var width: Int? by Property()
}
class AProperties : HtmlGlobalProperties() {
var href: String? by Property()
var rel: String? by Property()
var target: String? by Property()
}
class BaseProperties : HtmlGlobalProperties() {
var href: String? by Property()
var target: String? by Property()
}
class LinkProperties : HtmlGlobalProperties() {
var href: String? by Property()
var rel: String? by Property()
}
class TrackProperties : HtmlGlobalProperties() {
var label: String? by Property()
var src: String? by Property()
}
class BgsoundProperties : HtmlGlobalProperties() {
var loop: Boolean? by Property()
}
class MarqueeProperties : HtmlGlobalProperties() {
var loop: Boolean? by Property()
}
class MapProperties : HtmlGlobalProperties() {
var name: String? by Property()
}
class ParamProperties : HtmlGlobalProperties() {
var name: String? by Property()
var value: String? by Property()
}
class OptionProperties : HtmlGlobalProperties() {
var selected: Boolean? by Property()
var value: String? by Property()
}
class SourceProperties : HtmlGlobalProperties() {
var src: String? by Property()
var type: String? by Property()
}
class StyleProperties : HtmlGlobalProperties() {
var type: String? by Property()
var scoped: Boolean? by Property()
}
class MenuProperties : HtmlGlobalProperties() {
var type: String? by Property()
}
class LiProperties : HtmlGlobalProperties() {
var value: String? by Property()
}
class SvgProperties : ReactProperties() {
var id: String? by Property()
var cx: Int? by Property()
var cy: Int? by Property()
var d: Int? by Property()
var fill: String? by Property()
var fx: Int? by Property()
var fy: Int? by Property()
var gradientTransform: Any? by Property()
var gradientUnits: String? by Property()
var offset: Int? by Property()
var points: Any? by Property()
var r: Int? by Property()
var rx: Int? by Property()
var ry: Int? by Property()
var spreadMethod: String? by Property()
var stopColor: String? by Property()
var stopOpacity: Int? by Property()
var stroke: String? by Property()
var strokeLinecap: String? by Property()
var strokeWidth: Int? by Property()
var transform: String? by Property()
var version: Int? by Property()
var viewBox: Any? by Property()
var x1: Int? by Property()
var x2: Int? by Property()
var x: Int? by Property()
var y1: Int? by Property()
var y2: Int? by Property()
var y: Int? by Property()
}
|
mit
|
3d5170b9b85d0ca7d4c1f3abeb3d617d
| 29.014403 | 67 | 0.673751 | 4.048571 | false | false | false | false |
xu6148152/binea_project_for_android
|
SearchFilter/app/src/main/java/com/zepp/www/searchfilter/widget/ExpandedFilterView.kt
|
1
|
4679
|
package com.zepp.www.searchfilter.widget
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import com.zepp.www.searchfilter.R
import com.zepp.www.searchfilter.listener.CollapseListener
import com.zepp.www.searchfilter.model.Coord
import java.util.*
// Created by xubinggui on 02/11/2016.
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖镇楼 BUG辟易
class ExpandedFilterView : ViewGroup {
private var mPrevItem: View? = null
private var mPrevX: Int? = null
private var mPrevY: Int? = null
private var mPrevHeight = 0
private var mStartX = 0f
private var mStartY = 0f
internal var listener: CollapseListener? = null
internal var margin: Int = dpToPx(getDimen(R.dimen.margin))
internal val filters: LinkedHashMap<FilterItem, Coord> = LinkedHashMap()
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleRes: Int) : super(context, attrs, defStyleRes)
override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
if (!filters.isEmpty()) {
for (i in 0..childCount - 1) {
val child: View = getChildAt(i)
val coord: Coord? = filters[child]
if (coord != null) {
child.layout(coord.x, coord.y, coord.x + child.measuredWidth, coord.y + child.measuredHeight)
}
}
}
}
private fun canPlaceOnTheSameLine(filterItem: View): Boolean {
if (mPrevItem != null) {
val occupiedWidth: Int = mPrevX!! + mPrevItem!!.measuredWidth + margin + filterItem.measuredWidth
return occupiedWidth <= measuredWidth
}
return false
}
private fun calculateDesiredHeight(): Int {
var height: Int = mPrevHeight
if (filters.isEmpty()) {
for (i in 0..childCount - 1) {
val child: FilterItem = getChildAt(i) as FilterItem
child.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
if (mPrevItem == null) {
mPrevX = margin
mPrevY = margin
height = child.measuredHeight + margin
} else if (canPlaceOnTheSameLine(child)) {
mPrevX = mPrevX!! + mPrevItem!!.measuredWidth + margin / 2
} else {
mPrevX = margin
mPrevY = mPrevY!! + mPrevItem!!.measuredHeight + margin / 2
height += child.measuredHeight + margin / 2
}
mPrevItem = child
if (filters.size < childCount) {
filters.put(child, Coord(mPrevX!!, mPrevY!!))
}
}
height = if (height > 0) height + margin else 0
mPrevHeight = height
}
return mPrevHeight
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(calculateSize(widthMeasureSpec, LayoutParams.MATCH_PARENT),
calculateSize(heightMeasureSpec, calculateDesiredHeight()))
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mStartX = event.x
mStartY = event.y
}
MotionEvent.ACTION_MOVE -> {
if (event.y - mStartY < -20) {
listener?.collapse()
mStartX = 0f
mStartY = 0f
}
}
}
return true
}
}
|
mit
|
e46eb8533a2895c6bddfff29d310b164
| 34.363636 | 113 | 0.466895 | 4.227355 | false | false | false | false |
Zeyad-37/UseCases
|
usecases/src/main/java/com/zeyad/usecases/api/DataService.kt
|
2
|
14756
|
package com.zeyad.usecases.api
import android.util.Log
import com.jakewharton.rx.ReplayingShare
import com.zeyad.usecases.requests.FileIORequest
import com.zeyad.usecases.requests.GetRequest
import com.zeyad.usecases.requests.PostRequest
import com.zeyad.usecases.stores.DataStoreFactory
import com.zeyad.usecases.withCache
import com.zeyad.usecases.withDisk
import io.reactivex.*
import org.json.JSONException
import java.io.File
/**
* @author by ZIaDo on 5/9/17.
*/
internal class DataService(private val mDataStoreFactory: DataStoreFactory,
private val mPostExecutionThread: Scheduler?,
private val mBackgroundThread: Scheduler) : IDataService {
private val mPostThreadExist: Boolean = mPostExecutionThread != null
override fun <M> getList(getListRequest: GetRequest): Flowable<List<M>> {
var result: Flowable<List<M>>
try {
val dataClass = getListRequest.getTypedDataClass<M>()
val url = getListRequest.fullUrl
val simpleName = dataClass.simpleName
val shouldCache = getListRequest.cache
val dynamicGetList = mDataStoreFactory.dynamically(url, dataClass)
.dynamicGetList(url, getListRequest.idColumnName, dataClass,
getListRequest.persist, shouldCache)
result = if (withCache(shouldCache)) {
mDataStoreFactory.memory()!!.getAllItems(dataClass)
.doOnSuccess { Log.d("getList", CACHE_HIT + simpleName) }
.doOnError { Log.d("getList", CACHE_MISS + simpleName) }
.toFlowable()
.onErrorResumeNext { _: Throwable -> dynamicGetList }
} else {
dynamicGetList
}
} catch (e: IllegalAccessException) {
result = Flowable.error(e)
}
return result.compose(applySchedulers())
}
override fun <M> getObject(getRequest: GetRequest): Flowable<M> {
var result: Flowable<M>
try {
val itemId = getRequest.itemId
val dataClass = getRequest.getTypedDataClass<M>()
val shouldCache = getRequest.cache
val url = getRequest.fullUrl
val simpleName = dataClass.simpleName
val dynamicGetObject = mDataStoreFactory.dynamically(url, dataClass)
.dynamicGetObject(url, getRequest.idColumnName, itemId, dataClass,
getRequest.persist, shouldCache)
result = if (withCache(shouldCache)) {
mDataStoreFactory.memory()!!
.getItem<M>(itemId.toString(), dataClass)
.doOnSuccess { Log.d("getObject", CACHE_HIT + simpleName) }
.doOnError { Log.d("getObject", CACHE_MISS + simpleName) }
.toFlowable()
.onErrorResumeNext { _: Throwable -> dynamicGetObject }
} else {
dynamicGetObject
}
} catch (e: IllegalAccessException) {
result = Flowable.error(e)
}
return result.compose(applySchedulers())
}
override fun <M> patchObject(postRequest: PostRequest): Single<M> {
val result: Single<M> = try {
mDataStoreFactory.dynamically(postRequest.fullUrl, postRequest.requestType)
.dynamicPatchObject(postRequest.fullUrl, postRequest.idColumnName,
postRequest.getObjectBundle(), postRequest.requestType,
postRequest.getTypedResponseClass(), postRequest.persist,
postRequest.cache)
} catch (e: IllegalAccessException) {
Single.error(e)
} catch (e: JSONException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun <M> postObject(postRequest: PostRequest): Single<M> {
val result: Single<M> = try {
mDataStoreFactory.dynamically(postRequest.fullUrl, postRequest.requestType)
.dynamicPostObject(postRequest.fullUrl, postRequest.idColumnName,
postRequest.getObjectBundle(), postRequest.requestType,
postRequest.getTypedResponseClass(), postRequest.persist, postRequest.cache)
} catch (e: IllegalAccessException) {
Single.error(e)
} catch (e: JSONException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun <M> postList(postRequest: PostRequest): Single<M> {
val result: Single<M> = try {
mDataStoreFactory.dynamically(postRequest.fullUrl, postRequest.requestType)
.dynamicPostList(postRequest.fullUrl, postRequest.idColumnName,
postRequest.getArrayBundle(), postRequest.requestType,
postRequest.getTypedResponseClass(), postRequest.persist, postRequest.cache)
} catch (e: Exception) {
Single.error(e)
} catch (e: JSONException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun <M> putObject(postRequest: PostRequest): Single<M> {
val result: Single<M> = try {
mDataStoreFactory.dynamically(postRequest.fullUrl, postRequest.requestType)
.dynamicPutObject(postRequest.fullUrl, postRequest.idColumnName,
postRequest.getObjectBundle(), postRequest.requestType,
postRequest.getTypedResponseClass(), postRequest.persist, postRequest.cache)
} catch (e: IllegalAccessException) {
Single.error(e)
} catch (e: JSONException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun <M> putList(postRequest: PostRequest): Single<M> {
val result: Single<M> = try {
mDataStoreFactory.dynamically(postRequest.fullUrl, postRequest.requestType)
.dynamicPutList(postRequest.fullUrl, postRequest.idColumnName,
postRequest.getArrayBundle(), postRequest.requestType,
postRequest.getTypedResponseClass(), postRequest.persist, postRequest.cache)
} catch (e: IllegalAccessException) {
Single.error(e)
} catch (e: JSONException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun <M> deleteItemById(request: PostRequest): Single<M> {
return deleteCollectionByIds(request)
}
override fun <M> deleteCollectionByIds(deleteRequest: PostRequest): Single<M> {
val result: Single<M> = try {
mDataStoreFactory.dynamically(deleteRequest.fullUrl, deleteRequest.requestType)
.dynamicDeleteCollection(deleteRequest.fullUrl, deleteRequest.idColumnName,
deleteRequest.idType, deleteRequest.getArrayBundle(),
deleteRequest.requestType, deleteRequest.getTypedResponseClass<M>(),
deleteRequest.persist, deleteRequest.cache)
.compose(applySingleSchedulers())
} catch (e: IllegalAccessException) {
Single.error(e)
} catch (e: JSONException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun deleteAll(deleteRequest: PostRequest): Single<Boolean> {
val result: Single<Boolean> = try {
mDataStoreFactory.disk(deleteRequest.requestType)
.dynamicDeleteAll(deleteRequest.requestType)
} catch (e: IllegalAccessException) {
Single.error(e)
}
return result.compose {
if (mPostThreadExist)
it.subscribeOn(mBackgroundThread)
.observeOn(mPostExecutionThread!!).unsubscribeOn(mBackgroundThread)
else
it.subscribeOn(mBackgroundThread).unsubscribeOn(mBackgroundThread)
}
}
override fun <M> queryDisk(query: String, clazz: Class<M>): Single<List<M>> {
val result: Single<List<M>> = try {
mDataStoreFactory.disk(Any::class.java).queryDisk(query, clazz)
.compose(ReplayingShare.instance()).singleOrError()
} catch (e: IllegalAccessException) {
Single.error(e)
}
return result.compose(applySingleSchedulers())
}
override fun <M> getListOffLineFirst(getRequest: GetRequest): Flowable<List<M>> {
var result: Flowable<List<M>>
try {
val dataClass = getRequest.getTypedDataClass<M>()
val simpleName = dataClass.simpleName
val idColumnName = getRequest.idColumnName
val persist = getRequest.persist
val shouldCache = getRequest.cache
val withDisk = withDisk(persist)
val withCache = withCache(shouldCache)
val cloud = mDataStoreFactory.cloud(dataClass)
.dynamicGetList(getRequest.fullUrl, idColumnName, dataClass, persist, shouldCache)
val disk = mDataStoreFactory.disk(dataClass)
.dynamicGetList("", idColumnName, dataClass, persist, shouldCache)
.doOnNext { Log.d(GET_LIST_OFFLINE_FIRST, "Disk Hit $simpleName") }
.doOnError { throwable ->
Log.e(GET_LIST_OFFLINE_FIRST, "Disk Miss $simpleName",
throwable)
}
.flatMap { m -> if (m.isEmpty()) cloud else Flowable.just(m) }
.onErrorResumeNext { _: Throwable -> cloud }
result = when {
withCache -> mDataStoreFactory.memory()!!.getAllItems(dataClass)
.doOnSuccess { Log.d(GET_LIST_OFFLINE_FIRST, CACHE_HIT + simpleName) }
.doOnError { Log.d(GET_LIST_OFFLINE_FIRST, CACHE_MISS + simpleName) }
.toFlowable()
.onErrorResumeNext { _: Throwable -> if (withDisk) disk else cloud }
withDisk -> disk
else -> cloud
}
} catch (e: IllegalAccessException) {
result = Flowable.error(e)
}
return result.compose(ReplayingShare.instance()).compose(applySchedulers())
}
override fun <M> getObjectOffLineFirst(getRequest: GetRequest): Flowable<M> {
var result: Flowable<M>
try {
val itemId = getRequest.itemId
val dataClass = getRequest.getTypedDataClass<M>()
val idColumnName = getRequest.idColumnName
val simpleName = dataClass.simpleName
val persist = getRequest.persist
val shouldCache = getRequest.cache
val withDisk = withDisk(persist)
val withCache = withCache(shouldCache)
val cloud = mDataStoreFactory.cloud(dataClass)
.dynamicGetObject(getRequest.fullUrl, idColumnName, itemId, dataClass,
persist, shouldCache)
.doOnNext { Log.d(GET_OBJECT_OFFLINE_FIRST, "Cloud Hit $simpleName") }
val disk = mDataStoreFactory.disk(dataClass)
.dynamicGetObject("", idColumnName, itemId, dataClass, persist, shouldCache)
.doOnNext { Log.d(GET_OBJECT_OFFLINE_FIRST, "Disk Hit $simpleName") }
.doOnError { throwable ->
Log.e(GET_OBJECT_OFFLINE_FIRST, "Disk Miss $simpleName",
throwable)
}
.onErrorResumeNext { _: Throwable -> cloud }
result = when {
withCache -> mDataStoreFactory.memory()!!
.getItem<M>(itemId.toString(), dataClass)
.doOnSuccess { Log.d(GET_OBJECT_OFFLINE_FIRST, CACHE_HIT + simpleName) }
.doOnError { Log.d(GET_OBJECT_OFFLINE_FIRST, CACHE_MISS + simpleName) }
.toFlowable()
.onErrorResumeNext { _: Throwable -> if (withDisk) disk else cloud }
withDisk -> disk
else -> cloud
}
} catch (e: IllegalAccessException) {
result = Flowable.error(e)
}
return result.compose(ReplayingShare.instance()).compose(applySchedulers())
}
override fun <M> uploadFile(fileIORequest: FileIORequest): Single<M> {
return fileIORequest.dataClass?.let {
fileIORequest.keyFileMap?.let { it1 ->
mDataStoreFactory.cloud(it)
.dynamicUploadFile(fileIORequest.url, it1, fileIORequest.parameters,
fileIORequest.getTypedResponseClass<M>())
.compose(applySingleSchedulers())
}
}!!
}
override fun downloadFile(fileIORequest: FileIORequest): Single<File> {
return fileIORequest.dataClass?.let {
fileIORequest.file?.let { it1 ->
mDataStoreFactory.cloud(it)
.dynamicDownloadFile(fileIORequest.url, it1).compose(applySingleSchedulers())
}
}!!
}
/**
* Apply the default android schedulers to a observable
*
* @param <M> the current observable
* @return the transformed observable
</M> */
private fun <M> applySchedulers(): FlowableTransformer<M, M> {
return if (mPostThreadExist)
FlowableTransformer {
it.subscribeOn(mBackgroundThread).observeOn(mPostExecutionThread!!).unsubscribeOn(mBackgroundThread)
}
else
FlowableTransformer {
it.subscribeOn(mBackgroundThread).unsubscribeOn(mBackgroundThread)
}
}
private fun <M> applySingleSchedulers(): SingleTransformer<M, M> {
return if (mPostThreadExist)
SingleTransformer {
it.subscribeOn(mBackgroundThread).observeOn(mPostExecutionThread!!).unsubscribeOn(mBackgroundThread)
}
else
SingleTransformer {
it.subscribeOn(mBackgroundThread).unsubscribeOn(mBackgroundThread)
}
}
companion object {
private const val CACHE_HIT = "cache Hit "
private const val CACHE_MISS = "cache Miss "
private const val GET_LIST_OFFLINE_FIRST = "getListOffLineFirst"
private const val GET_OBJECT_OFFLINE_FIRST = "getObjectOffLineFirst"
}
}
|
apache-2.0
|
260c748557623c4f5eeab6ada33d0660
| 43.851064 | 116 | 0.590268 | 5.043062 | false | false | false | false |
smrehan6/WeatherForecast
|
app/src/main/java/me/smr/weatherforecast/viewmodels/ForecastViewModel.kt
|
1
|
1945
|
package me.smr.weatherforecast.viewmodels
import androidx.lifecycle.*
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import me.smr.weatherforecast.data.Repository
import me.smr.weatherforecast.fragments.ForecastFragment
import me.smr.weatherforecast.models.Forecast
import me.smr.weatherforecast.utils.Result
import javax.inject.Inject
@HiltViewModel
class ForecastViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val repository: Repository
) : ViewModel() {
private val _data = MutableLiveData<Result<List<Forecast>>>()
val data: LiveData<Result<List<Forecast>>> = _data
val isLoading: LiveData<Boolean> = Transformations.map(_data) { result ->
result is Result.Loading
}
init {
_data.postValue(Result.Loading)
val cityId: String? = savedStateHandle[ForecastFragment.ARG_CITY_ID]
cityId?.let {
viewModelScope.launch {
try {
val response = repository.fetchForecast(cityId)
val list = mutableListOf<Forecast>()
response.list.forEach {
list.add(Forecast().apply {
this.date = it.dt
this.temp = "${it.temp.min} - ${it.temp.max}"
this.img = it.weather[0].icon
this.weather = it.weather[0].description
})
}
_data.postValue(Result.Value(list))
} catch (e: Exception) {
e.printStackTrace()
_data.postValue(Result.Error(e))
}
}
} ?: run {
_data.postValue(Result.Error(IllegalArgumentException("${ForecastFragment.ARG_CITY_ID} not found")))
}
}
companion object {
const val TAG = "ForecastViewModel"
}
}
|
apache-2.0
|
73fff350c52467a5cdc9b4c752706988
| 33.140351 | 112 | 0.583548 | 4.899244 | false | false | false | false |
peervalhoegen/SudoQ
|
sudoq-app/sudoqmodel/src/test/java/de/sudoq/model/utility/persistence/sudokuType/SudokuTypeRepo.kt
|
1
|
1844
|
package de.sudoq.model.utility.persistence.sudokuType
/*class SudokuTypeRepo() : IRepo<SudokuType> {
private val typesDir: File = FileUtils.getFile("src","test", "resources", "persistence", "SudokuTypes");
override fun create(): SudokuType {
TODO("Not yet implemented")
}
override fun read(id: Int): SudokuType {
val st: SudokuTypes = SudokuTypes.values()[id]
return getSudokuType(st)
}
/**
* Gibt die Sudoku-Typdatei für den spezifizierten Typ zurück.
* @param type die Typ-Id
* @return die entsprechende Sudoku-Typdatei
*/
private fun getSudokuTypeFile(type: SudokuTypes): File {
return File(typesDir, "$type.xml");
}
/**
* Creates and returns a SudokuType subject to the specified Type Name.
* If the type cannot be mapped to a type null is returned.
*
* @param type Enum Type of the SudokuType to create.
* @return a [SudokuType] of null if type cannot be mapped
*/
private fun getSudokuType(type: SudokuTypes): SudokuType {
val f = getSudokuTypeFile(type)
if (!f.exists()) {
throw IllegalStateException("no sudoku type file found for $type")
}
val helper = XmlHelper()
try {
val t = SudokuTypeBE()
val xt = helper.loadXml(f)!!
t.fillFromXml(xt)
return SudokuTypeMapper.fromBE(t)
} catch (e: Exception) {
e.printStackTrace()
}
throw IllegalStateException("Something went wrong loading sudoku type for $type")
}
override fun update(t: SudokuType): SudokuType {
TODO("Not yet implemented")
}
override fun delete(id: Int) {
TODO("Not yet implemented")
}
override fun ids(): List<Int> {
TODO("Not yet implemented")
}
}*/
|
gpl-3.0
|
9854aa9b2d26b20883448ca5384608e5
| 28.253968 | 108 | 0.611835 | 4.283721 | false | false | false | false |
jk1/youtrack-idea-plugin
|
src/main/kotlin/com/github/jk1/ytplugin/rest/IssueJsonParser.kt
|
1
|
1162
|
package com.github.jk1.ytplugin.rest
import com.github.jk1.ytplugin.issues.model.*
import com.github.jk1.ytplugin.logger
import com.google.gson.JsonElement
object IssueJsonParser {
fun parseIssue(element: JsonElement, url: String) = parseSafe(element) { Issue(element, url) }
fun parseWorkItem(element: JsonElement) = parseSafe(element) { IssueWorkItem(element) }
fun parseWorkItemAttribute(element: JsonElement) = parseSafe(element) { WorkItemAttribute(element) }
fun parseCustomField(element: JsonElement) = parseSafe(element) { CustomField(element) }
fun parseComment(element: JsonElement) = parseSafe(element) { IssueComment(element) }
fun parseTag(element: JsonElement) = parseSafe(element) { IssueTag(element) }
fun parseAttachment(element: JsonElement, url: String) = parseSafe(element) { Attachment(element, url) }
private fun <T> parseSafe(element: JsonElement, parser: () -> T): T? {
return try {
parser.invoke()
} catch(e: Exception) {
logger.warn("YouTrack issue parse error. Offending element: $element")
logger.debug(e)
null
}
}
}
|
apache-2.0
|
e1854065523c8af11be419b69af26acf
| 35.34375 | 108 | 0.696213 | 3.96587 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/completion/RsPartialMacroArgumentCompletionProvider.kt
|
2
|
3615
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import org.rust.lang.RsLanguage
import org.rust.lang.core.macros.MacroExpansionContext.EXPR
import org.rust.lang.core.macros.MacroExpansionContext.STMT
import org.rust.lang.core.macros.MacroExpansionMode
import org.rust.lang.core.macros.decl.FragmentKind
import org.rust.lang.core.macros.decl.FragmentKind.*
import org.rust.lang.core.macros.decl.MacroGraphWalker
import org.rust.lang.core.macros.expansionContext
import org.rust.lang.core.macros.macroExpansionManager
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psiElement
import org.rust.openapiext.Testmark
/**
* Provides completion inside a macro argument (e.g. `foo!(/*caret*/)`) if the macro is NOT expanded
* successfully, i.e. [RsMacroCall.expansion] == null. If macro is expanded successfully,
* [RsFullMacroArgumentCompletionProvider] is used.
*/
object RsPartialMacroArgumentCompletionProvider : RsCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
fun addCompletions(fragment: RsCodeFragment, offset: Int) {
val element = fragment.findElementAt(offset) ?: return
rerunCompletion(parameters.withPosition(element, offset), result)
}
val project = parameters.originalFile.project
val position = parameters.position
val macroCall = position.ancestorStrict<RsMacroArgument>()?.ancestorStrict<RsMacroCall>() ?: return
val condition = macroCall.expansion != null &&
project.macroExpansionManager.macroExpansionMode is MacroExpansionMode.New &&
macroCall.expansionContext !in listOf(EXPR, STMT) // TODO remove after hygiene merge
if (condition) return
val bodyTextRange = macroCall.bodyTextRange ?: return
val macroCallBody = macroCall.macroBody ?: return
val macro = macroCall.resolveToMacro() ?: return
val graph = macro.graph ?: return
val offsetInArgument = parameters.offset - bodyTextRange.startOffset
Testmarks.Touched.hit()
val walker = MacroGraphWalker(project, graph, macroCallBody, offsetInArgument)
val fragmentDescriptors = walker.run().takeIf { it.isNotEmpty() } ?: return
val usedKinds = mutableSetOf<FragmentKind>()
for ((fragmentText, caretOffsetInFragment, kind) in fragmentDescriptors) {
if (kind in usedKinds) continue
val codeFragment = when (kind) {
Expr, Path -> RsExpressionCodeFragment(project, fragmentText, macroCall)
Stmt -> RsStatementCodeFragment(project, fragmentText, macroCall)
Ty -> RsTypeReferenceCodeFragment(project, fragmentText, macroCall)
else -> null
} ?: continue
addCompletions(codeFragment, caretOffsetInFragment)
usedKinds.add(kind)
}
}
override val elementPattern: ElementPattern<PsiElement>
get() = psiElement()
.withLanguage(RsLanguage)
.inside(psiElement<RsMacroArgument>())
object Testmarks {
object Touched : Testmark()
}
}
|
mit
|
2742d8b1a3d44111c2288f0f8e658f7e
| 42.035714 | 124 | 0.723928 | 4.65251 | false | false | false | false |
charleskorn/batect
|
app/src/unitTest/kotlin/batect/config/NamedObjectMapSpec.kt
|
1
|
6663
|
/*
Copyright 2017-2020 Charles Korn.
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 batect.config
import batect.testutils.on
import batect.testutils.withMessage
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.hasSize
import com.natpryce.hamkrest.isEmpty
import com.natpryce.hamkrest.throws
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object NamedObjectMapSpec : Spek({
describe("a set of named objects") {
describe("creating a set of named objects") {
on("creating an empty set") {
val set = NamedObjectMapImplementation()
it("has no entries") {
assertThat(set.entries, isEmpty)
}
it("has no keys") {
assertThat(set.keys, isEmpty)
}
it("has no values") {
assertThat(set.values, isEmpty)
}
it("has a size of 0") {
assertThat(set.size, equalTo(0))
}
it("reports that it is empty") {
assertThat(set.isEmpty(), equalTo(true))
}
}
on("creating a set with a single item") {
val thing = Thing("the_thing")
val set = NamedObjectMapImplementation(thing)
it("has one entry") {
val entries = set.entries
assertThat(entries, hasSize(equalTo(1)))
assertThat(entries.map { it.key }.toSet(), equalTo(setOf(thing.name)))
assertThat(entries.map { it.value }.toSet(), equalTo(setOf(thing)))
}
it("has one key") {
assertThat(set.keys, equalTo(setOf(thing.name)))
}
it("has one value") {
assertThat(set.values.toList(), equalTo(listOf(thing)))
}
it("has a size of 1") {
assertThat(set.size, equalTo(1))
}
it("reports that it is not empty") {
assertThat(set.isEmpty(), equalTo(false))
}
it("reports that it contains the item's name") {
assertThat(set.containsKey(thing.name), equalTo(true))
}
it("reports that it contains the item") {
assertThat(set.containsValue(thing), equalTo(true))
}
it("returns the item when accessing it by name") {
assertThat(set[thing.name], equalTo(thing))
}
}
on("creating a set with two items with different names") {
val thing1 = Thing("thing-1")
val thing2 = Thing("thing-2")
val set = NamedObjectMapImplementation(thing1, thing2)
it("has two entries") {
val entries = set.entries
assertThat(entries, hasSize(equalTo(2)))
assertThat(entries.map { it.key }.toSet(), equalTo(setOf(thing1.name, thing2.name)))
assertThat(entries.map { it.value }.toSet(), equalTo(setOf(thing1, thing2)))
}
it("has two keys") {
assertThat(set.keys, equalTo(setOf(thing1.name, thing2.name)))
}
it("has two values") {
assertThat(set.values.toList(), equalTo(listOf(thing1, thing2)))
}
it("has a size of 2") {
assertThat(set.size, equalTo(2))
}
it("reports that it is not empty") {
assertThat(set.isEmpty(), equalTo(false))
}
it("reports that it contains the items' names") {
assertThat(set.containsKey(thing1.name), equalTo(true))
assertThat(set.containsKey(thing2.name), equalTo(true))
}
it("reports that it contains the items") {
assertThat(set.containsValue(thing1), equalTo(true))
assertThat(set.containsValue(thing2), equalTo(true))
}
it("returns the items when accessing them by name") {
assertThat(set[thing1.name], equalTo(thing1))
assertThat(set[thing2.name], equalTo(thing2))
}
}
on("creating a set with two items with the same name") {
it("fails with an appropriate error message") {
val itemName = "the-item"
val item1 = Thing(itemName)
val item2 = Thing(itemName)
assertThat({ NamedObjectMapImplementation(item1, item2) }, throws(withMessage("Cannot create a NamedObjectMapImplementation where a thing name is used more than once. Duplicated thing names: $itemName")))
}
}
on("creating a set with four items with each name duplicated") {
it("fails with an appropriate error message") {
val itemName1 = "item-name-1"
val itemName2 = "item-name-2"
val item1 = Thing(itemName1)
val item2 = Thing(itemName1)
val item3 = Thing(itemName2)
val item4 = Thing(itemName2)
assertThat({ NamedObjectMapImplementation(item1, item2, item3, item4) }, throws(withMessage("Cannot create a NamedObjectMapImplementation where a thing name is used more than once. Duplicated thing names: $itemName1, $itemName2")))
}
}
}
}
})
private class NamedObjectMapImplementation(contents: Iterable<Thing>) : NamedObjectMap<Thing>("thing", contents) {
constructor(vararg contents: Thing) : this(contents.asIterable())
override fun nameFor(value: Thing): String = value.name
}
private data class Thing(val name: String)
|
apache-2.0
|
6673307c492a43d85ff5f48882c2216a
| 37.738372 | 251 | 0.542548 | 4.961281 | false | false | false | false |
petropavel13/2photo-android
|
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/views/PostItemView.kt
|
1
|
4474
|
package com.github.petropavel13.twophoto.views
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.request.ImageRequest
import com.github.petropavel13.twophoto.R
import com.github.petropavel13.twophoto.model.Post
/**
* Created by petropavel on 25/03/15.
*/
class PostItemView: RelativeLayout {
companion object {
val LAYOUT_RESOURCE = R.layout.post_grid_item_layout
@SuppressWarnings("deprecation")
private fun setBackgroundDrawablePreJellyBean(view: View?, drawable: GradientDrawable) {
view?.setBackgroundDrawable(drawable)
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private fun setBackgroundDrawableJellyBean(view: View?, drawable: GradientDrawable) {
view?.background = drawable
}
}
constructor(ctx: Context): super(ctx) { }
constructor(ctx: Context, attrs: AttributeSet): super(ctx, attrs) { }
constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int): super(ctx, attrs, defStyleAttr) { }
constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int): super(ctx, attrs, defStyleAttr, defStyleRes) { }
private var titleTextView: TextView? = null
private var authorTextView: TextView? = null
private var faceImageView: SimpleDraweeView? = null
private var attributesLayout: LinearLayout? = null
private var commentsCountTextView: TextView? = null
private var ratingTextView: TextView? = null
private var bgColor = 0xFF202020.toInt()
private var borderColor = 0xFF444444.toInt()
override fun onFinishInflate() {
super.onFinishInflate()
titleTextView = findViewById(R.id.post_item_title_text_view) as? TextView
authorTextView = findViewById(R.id.post_item_author_text_view) as? TextView
faceImageView = findViewById(R.id.post_item_face_image_view) as? SimpleDraweeView
attributesLayout = findViewById(R.id.post_item_attributes_layout) as? LinearLayout
commentsCountTextView = findViewById(R.id.post_item_comments_count_text_view) as? TextView
ratingTextView = findViewById(R.id.post_item_rating_text_view) as? TextView
bgColor = resources.getColor(R.color.post_item_bg_color)
borderColor = resources.getColor(R.color.post_item_border_color)
with(GradientDrawable()){
setColor(bgColor)
setStroke(1, borderColor)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackgroundDrawableJellyBean(this@PostItemView, this)
} else {
setBackgroundDrawablePreJellyBean(this@PostItemView, this)
}
}
with(GradientDrawable()){
setColor(bgColor)
setStroke(1, borderColor)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackgroundDrawableJellyBean(attributesLayout, this)
} else {
setBackgroundDrawablePreJellyBean(attributesLayout, this)
}
}
}
private var _post = Post()
private var request: ImageRequest? = null
var post: Post
get() = _post
set(newValue) {
_post = newValue
request = ImageRequest.fromUri(newValue.face_image_url)
faceImageView?.controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.build()
val color = Color.parseColor(_post.color)
titleTextView?.text = newValue.title
titleTextView?.setTextColor(color)
authorTextView?.text = "by ${newValue.author.name}"
commentsCountTextView?.text = newValue.number_of_comments.toString()
ratingTextView?.text = "${newValue.rating}%"
}
fun unloadEntryImage() {
faceImageView?.setImageURI(null)
}
fun loadEntryImage() {
faceImageView?.controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.build()
}
}
|
mit
|
706a5d52dcbbb93fd5e9b3904852843b
| 34.228346 | 137 | 0.67747 | 4.593429 | false | false | false | false |
androidx/androidx
|
compose/material/material/samples/src/main/java/androidx/compose/material/samples/SurfaceSamples.kt
|
3
|
2574
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.style.TextAlign
@Sampled
@Composable
fun SurfaceSample() {
Surface(
color = MaterialTheme.colors.background
) {
Text("Text color is `onBackground`")
}
}
@OptIn(ExperimentalMaterialApi::class)
@Sampled
@Composable
fun ClickableSurfaceSample() {
var count by remember { mutableStateOf(0) }
Surface(
onClick = { count++ },
color = MaterialTheme.colors.background
) {
Text("Clickable surface Text with `onBackground` color and count: $count")
}
}
@OptIn(ExperimentalMaterialApi::class)
@Sampled
@Composable
fun SelectableSurfaceSample() {
var selected by remember { mutableStateOf(false) }
Surface(
selected = selected,
onClick = { selected = !selected },
color = MaterialTheme.colors.background
) {
Text(
text = if (selected) "Selected" else "Not Selected",
textAlign = TextAlign.Center
)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Sampled
@Composable
fun ToggleableSurfaceSample() {
var checked by remember { mutableStateOf(false) }
Surface(
checked = checked,
onCheckedChange = { checked = !checked },
color = if (checked) {
MaterialTheme.colors.primary
} else {
MaterialTheme.colors.background
}
) {
Text(
text = if (checked) "ON" else "OFF",
textAlign = TextAlign.Center
)
}
}
|
apache-2.0
|
48416b51121f14f28e0d273c9637c229
| 27.6 | 82 | 0.693473 | 4.515789 | false | false | false | false |
androidx/androidx
|
room/room-runtime/src/main/java/androidx/room/MultiInstanceInvalidationService.kt
|
3
|
4999
|
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import android.app.Service
import android.os.RemoteCallbackList
import android.content.Intent
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import androidx.room.Room.LOG_TAG
/**
* A [Service] for remote invalidation among multiple [InvalidationTracker] instances.
* This service runs in the main app process. All the instances of [InvalidationTracker]
* (potentially in other processes) has to connect to this service.
*
* The intent to launch it can be specified by
* [RoomDatabase.Builder.setMultiInstanceInvalidationServiceIntent], although the service is
* defined in the manifest by default so there should be no need to override it in a normal
* situation.
*/
@ExperimentalRoomApi
class MultiInstanceInvalidationService : Service() {
internal var maxClientId = 0
internal val clientNames = mutableMapOf<Int, String>()
internal val callbackList: RemoteCallbackList<IMultiInstanceInvalidationCallback> =
object : RemoteCallbackList<IMultiInstanceInvalidationCallback>() {
override fun onCallbackDied(
callback: IMultiInstanceInvalidationCallback,
cookie: Any
) {
clientNames.remove(cookie as Int)
}
}
private val binder: IMultiInstanceInvalidationService.Stub =
object : IMultiInstanceInvalidationService.Stub() {
// Assigns a client ID to the client.
override fun registerCallback(
callback: IMultiInstanceInvalidationCallback,
name: String?
): Int {
if (name == null) {
return 0
}
synchronized(callbackList) {
val clientId = ++maxClientId
// Use the client ID as the RemoteCallbackList cookie.
return if (callbackList.register(callback, clientId)) {
clientNames[clientId] = name
clientId
} else {
--maxClientId
0
}
}
}
// Explicitly removes the client.
// The client can die without calling this. In that case, callbackList
// .onCallbackDied() can take care of removal.
override fun unregisterCallback(
callback: IMultiInstanceInvalidationCallback,
clientId: Int
) {
synchronized(callbackList) {
callbackList.unregister(callback)
clientNames.remove(clientId)
}
}
// Broadcasts table invalidation to other instances of the same database file.
// The broadcast is not sent to the caller itself.
override fun broadcastInvalidation(clientId: Int, tables: Array<out String>) {
synchronized(callbackList) {
val name = clientNames[clientId]
if (name == null) {
Log.w(LOG_TAG, "Remote invalidation client ID not registered")
return
}
val count = callbackList.beginBroadcast()
try {
for (i in 0 until count) {
val targetClientId = callbackList.getBroadcastCookie(i) as Int
val targetName = clientNames[targetClientId]
if (clientId == targetClientId || name != targetName) {
// Skip if this is the caller itself or broadcast is for another
// database.
continue
}
try {
callbackList.getBroadcastItem(i).onInvalidation(tables)
} catch (e: RemoteException) {
Log.w(LOG_TAG, "Error invoking a remote callback", e)
}
}
} finally {
callbackList.finishBroadcast()
}
}
}
}
override fun onBind(intent: Intent): IBinder {
return binder
}
}
|
apache-2.0
|
5a521a09bd1646a09c336b8b5fc8d59f
| 39.983607 | 96 | 0.562312 | 5.579241 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.