repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ingokegel/intellij-community
|
plugins/kotlin/idea/tests/testData/wordSelection/Statements/3.kt
|
13
|
455
|
fun main(args : Array<String>) {
for (i in 1..100) {
when {
i%3 == 0 -> {print("Fizz"); continue;}
i%5 == 0 -> {print("Buzz"); continue;}
(i%3 != 0 && i%5 != 0) -> {print(i); continue;}
else -> println()
}
}
}
fun foo() : Unit {
println() {
println()
<selection> pr<caret>intln()
</selection> println()
}
println(array(1, 2, 3))
println()
}
|
apache-2.0
|
6450b3223b55f51fe8393d900d71187b
| 18 | 59 | 0.417582 | 3.321168 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/StatementConverter.kt
|
4
|
11944
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.j2k
import com.intellij.psi.*
import org.jetbrains.kotlin.j2k.ast.*
import java.util.*
interface StatementConverter {
fun convertStatement(statement: PsiStatement, codeConverter: CodeConverter): Statement
}
interface SpecialStatementConverter {
fun convertStatement(statement: PsiStatement, codeConverter: CodeConverter): Statement?
}
fun StatementConverter.withSpecialConverter(specialConverter: SpecialStatementConverter): StatementConverter {
return object: StatementConverter {
override fun convertStatement(statement: PsiStatement, codeConverter: CodeConverter): Statement
= specialConverter.convertStatement(statement, codeConverter) ?: [email protected](statement, codeConverter)
}
}
class DefaultStatementConverter : JavaElementVisitor(), StatementConverter {
private var _codeConverter: CodeConverter? = null
private var result: Statement = Statement.Empty
private val codeConverter: CodeConverter get() = _codeConverter!!
private val converter: Converter get() = codeConverter.converter
override fun convertStatement(statement: PsiStatement, codeConverter: CodeConverter): Statement {
this._codeConverter = codeConverter
result = Statement.Empty
statement.accept(this)
return result
}
override fun visitAssertStatement(statement: PsiAssertStatement) {
val descriptionExpr = statement.assertDescription
val condition = codeConverter.convertExpression(statement.assertCondition)
result = if (descriptionExpr == null) {
MethodCallExpression.buildNonNull(null, "assert", ArgumentList.withNoPrototype(condition))
}
else {
val description = codeConverter.convertExpression(descriptionExpr)
val lambda = LambdaExpression(null, Block.of(description).assignNoPrototype())
MethodCallExpression.buildNonNull(null, "assert", ArgumentList.withNoPrototype(condition, lambda))
}
}
override fun visitBlockStatement(statement: PsiBlockStatement) {
val block = codeConverter.convertBlock(statement.codeBlock)
result = MethodCallExpression.buildNonNull(null, "run", ArgumentList.withNoPrototype(LambdaExpression(null, block).assignNoPrototype()))
}
override fun visitBreakStatement(statement: PsiBreakStatement) {
result = if (statement.labelIdentifier == null) {
BreakStatement(Identifier.Empty)
}
else {
BreakStatement(converter.convertIdentifier(statement.labelIdentifier))
}
}
override fun visitContinueStatement(statement: PsiContinueStatement) {
result = if (statement.labelIdentifier == null) {
ContinueStatement(Identifier.Empty)
}
else {
ContinueStatement(converter.convertIdentifier(statement.labelIdentifier))
}
}
override fun visitDeclarationStatement(statement: PsiDeclarationStatement) {
result = DeclarationStatement(statement.declaredElements.map {
when (it) {
is PsiLocalVariable -> codeConverter.convertLocalVariable(it)
is PsiClass -> converter.convertClass(it)
else -> Element.Empty //what else can be here?
}
})
}
override fun visitDoWhileStatement(statement: PsiDoWhileStatement) {
val condition = statement.condition
val expression = if (condition?.type != null)
codeConverter.convertExpression(condition, condition.type)
else
codeConverter.convertExpression(condition)
result = DoWhileStatement(expression, codeConverter.convertStatementOrBlock(statement.body), statement.isInSingleLine())
}
override fun visitExpressionStatement(statement: PsiExpressionStatement) {
result = codeConverter.convertExpression(statement.expression)
}
override fun visitExpressionListStatement(statement: PsiExpressionListStatement) {
result = ExpressionListStatement(codeConverter.convertExpressionsInList(statement.expressionList.expressions.asList()))
}
override fun visitForStatement(statement: PsiForStatement) {
result = ForConverter(statement, codeConverter).execute()
}
override fun visitForeachStatement(statement: PsiForeachStatement) {
val iterator = codeConverter.convertExpression(statement.iteratedValue, null, Nullability.NotNull)
val iterationParameter = statement.iterationParameter
result = ForeachStatement(iterationParameter.declarationIdentifier(),
if (codeConverter.settings.specifyLocalVariableTypeByDefault) codeConverter.typeConverter.convertVariableType(iterationParameter) else null,
iterator,
codeConverter.convertStatementOrBlock(statement.body),
statement.isInSingleLine())
}
override fun visitIfStatement(statement: PsiIfStatement) {
val condition = statement.condition
val expression = codeConverter.convertExpression(condition, PsiType.BOOLEAN)
result = IfStatement(expression,
codeConverter.convertStatementOrBlock(statement.thenBranch),
codeConverter.convertStatementOrBlock(statement.elseBranch),
statement.isInSingleLine())
}
override fun visitLabeledStatement(statement: PsiLabeledStatement) {
val statementConverted = codeConverter.convertStatement(statement.statement)
val identifier = converter.convertIdentifier(statement.labelIdentifier)
result = if (statementConverted is ForConverter.WhileWithInitializationPseudoStatement) {
// special case - if our loop gets converted to while with initialization we should move the label to the loop
val labeledLoop = LabeledStatement(identifier, statementConverted.loop).assignPrototype(statement)
ForConverter.WhileWithInitializationPseudoStatement(statementConverted.initialization, labeledLoop, statementConverted.kind)
}
else {
LabeledStatement(identifier, statementConverted)
}
}
override fun visitSwitchLabelStatement(statement: PsiSwitchLabelStatement) {
result = if (statement.isDefaultCase)
ElseWhenEntrySelector()
else
ValueWhenEntrySelector(codeConverter.convertExpression(statement.caseValue))
}
override fun visitSwitchStatement(statement: PsiSwitchStatement) {
result = SwitchConverter(codeConverter).convert(statement)
}
override fun visitSynchronizedStatement(statement: PsiSynchronizedStatement) {
result = SynchronizedStatement(codeConverter.convertExpression(statement.lockExpression),
codeConverter.convertBlock(statement.body))
}
override fun visitThrowStatement(statement: PsiThrowStatement) {
result = ThrowStatement(codeConverter.convertExpression(statement.exception))
}
override fun visitTryStatement(tryStatement: PsiTryStatement) {
val tryBlock = tryStatement.tryBlock
val catchesConverted = convertCatches(tryStatement)
val finallyConverted = codeConverter.convertBlock(tryStatement.finallyBlock)
val resourceList = tryStatement.resourceList
if (resourceList != null) {
val variables = resourceList.filterIsInstance<PsiResourceVariable>()
if (variables.isNotEmpty()) {
result = convertTryWithResources(tryBlock, variables, catchesConverted, finallyConverted)
return
}
}
result = TryStatement(codeConverter.convertBlock(tryBlock), catchesConverted, finallyConverted)
}
private fun convertCatches(tryStatement: PsiTryStatement): List<CatchStatement> {
val catches = ArrayList<CatchStatement>()
for ((block, parameter) in tryStatement.catchBlocks.zip(tryStatement.catchBlockParameters)) {
val blockConverted = codeConverter.convertBlock(block)
val annotations = converter.convertAnnotations(parameter)
val parameterType = parameter.type
val types = (parameterType as? PsiDisjunctionType)?.disjunctions ?: listOf(parameterType)
for (t in types) {
val convertedType = codeConverter.typeConverter.convertType(t, Nullability.NotNull)
val convertedParameter = FunctionParameter(parameter.declarationIdentifier(),
convertedType,
FunctionParameter.VarValModifier.None,
annotations,
Modifiers.Empty).assignPrototype(parameter)
catches.add(CatchStatement(convertedParameter, blockConverted).assignNoPrototype())
}
}
return catches
}
private fun convertTryWithResources(tryBlock: PsiCodeBlock?, resourceVariables: List<PsiResourceVariable>, catchesConverted: List<CatchStatement>, finallyConverted: Block): Statement {
val wrapResultStatement: (Expression) -> Statement = { it }
val converterForBody = codeConverter
var block = converterForBody.convertBlock(tryBlock)
var expression: Expression = Expression.Empty
for (variable in resourceVariables.asReversed()) {
val parameter = LambdaParameter(Identifier.withNoPrototype(variable.name!!), null).assignNoPrototype()
val parameterList = ParameterList(listOf(parameter), lPar = null, rPar = null).assignNoPrototype()
val lambda = LambdaExpression(parameterList, block)
expression = MethodCallExpression.buildNonNull(codeConverter.convertExpression(variable.initializer), "use", ArgumentList.withNoPrototype(lambda))
expression.assignNoPrototype()
block = Block.of(expression).assignNoPrototype()
}
if (catchesConverted.isEmpty() && finallyConverted.isEmpty) {
return wrapResultStatement(expression)
}
block = Block(listOf(wrapResultStatement(expression)), LBrace().assignPrototype(tryBlock?.lBrace), RBrace().assignPrototype(tryBlock?.rBrace), true)
return TryStatement(block.assignPrototype(tryBlock), catchesConverted, finallyConverted)
}
override fun visitWhileStatement(statement: PsiWhileStatement) {
val condition = statement.condition
val expression = if (condition?.type != null)
codeConverter.convertExpression(condition, condition.type)
else
codeConverter.convertExpression(condition)
result = WhileStatement(expression, codeConverter.convertStatementOrBlock(statement.body), statement.isInSingleLine())
}
override fun visitReturnStatement(statement: PsiReturnStatement) {
val returnValue = statement.returnValue
val methodReturnType = codeConverter.methodReturnType
val expression = if (returnValue != null && methodReturnType != null)
codeConverter.convertExpression(returnValue, methodReturnType)
else
codeConverter.convertExpression(returnValue)
result = ReturnStatement(expression)
}
override fun visitEmptyStatement(statement: PsiEmptyStatement) {
result = Statement.Empty
}
}
fun CodeConverter.convertStatementOrBlock(statement: PsiStatement?): Statement {
return if (statement is PsiBlockStatement)
convertBlock(statement.codeBlock)
else
convertStatement(statement)
}
|
apache-2.0
|
5635e72779f3f8f9ad36193a0e74700f
| 46.967871 | 188 | 0.698342 | 6.059868 | false | false | false | false |
NikAshanin/Design-Patterns-In-Swift-Compare-Kotlin
|
Creational/AbstractFactory/AbstractFactory.kt
|
1
|
821
|
// Implementation
interface Button
class OSXButton: Button
class WinButton: Button
abstract class ButtonFactory {
abstract fun makeButton(): Button
companion object {
inline fun <reified T: Button> createFactory(): ButtonFactory = when (T::class) {
OSXButton::class -> OSXFactory()
WinButton::class -> WinFactory()
else -> throw IllegalArgumentException()
}
}
}
class OSXFactory: ButtonFactory() {
override fun makeButton(): Button = OSXButton()
}
class WinFactory: ButtonFactory() {
override fun makeButton(): Button = WinButton()
}
// Usage
fun main(args: Array<String>) {
val buttonFactory = ButtonFactory.createFactory<OSXButton>()
val button = buttonFactory.makeButton()
println("Created button: $button")
}
|
mit
|
ac8be89a1c5d154e01fa49e52032fa4d
| 21.833333 | 89 | 0.658952 | 4.561111 | false | false | false | false |
android/nowinandroid
|
core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/NewsResourceCardList.kt
|
1
|
2586
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.ui
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
/**
* Extension function for displaying a [List] of [NewsResourceCardExpanded] backed by a generic
* [List] [T].
*
* [newsResourceMapper] maps type [T] to a [NewsResource]
* [isBookmarkedMapper] maps type [T] to whether the [NewsResource] is bookmarked
* [onToggleBookmark] defines the action invoked when a user wishes to bookmark an item
* [onItemClick] optional parameter for action to be performed when the card is clicked. The
* default action launches an intent matching the card.
*/
fun <T> LazyListScope.newsResourceCardItems(
items: List<T>,
newsResourceMapper: (item: T) -> NewsResource,
isBookmarkedMapper: (item: T) -> Boolean,
onToggleBookmark: (item: T) -> Unit,
onItemClick: ((item: T) -> Unit)? = null,
itemModifier: Modifier = Modifier,
) = items(
items = items,
key = { newsResourceMapper(it).id },
itemContent = { item ->
val newsResource = newsResourceMapper(item)
val launchResourceIntent =
Intent(Intent.ACTION_VIEW, Uri.parse(newsResource.url))
val context = LocalContext.current
NewsResourceCardExpanded(
newsResource = newsResource,
isBookmarked = isBookmarkedMapper(item),
onToggleBookmark = { onToggleBookmark(item) },
onClick = {
when (onItemClick) {
null -> ContextCompat.startActivity(context, launchResourceIntent, null)
else -> onItemClick(item)
}
},
modifier = itemModifier
)
},
)
|
apache-2.0
|
958e017260576596f70e22d237275380
| 37.597015 | 95 | 0.697216 | 4.489583 | false | false | false | false |
wengelef/KotlinMVVM
|
app/src/main/java/com/wengelef/kotlinmvvmtest/main/MainViewModel.kt
|
1
|
1143
|
package com.wengelef.kotlinmvvmtest.main
import android.databinding.BaseObservable
import android.view.View
import rx.Observable
import rx.subjects.PublishSubject
import javax.inject.Inject
class MainViewModel @Inject constructor() : BaseObservable() {
private val simpleClicks = PublishSubject.create<View>()
private val lessSimpleClicks = PublishSubject.create<View>()
private val evenLessSimpleClicks = PublishSubject.create<View>()
fun getSimpleButtonText(): String = "Simple"
val lessSimpleButtonText = "Less Simple"
fun getEvenLessSimpleButtonText(): String = "Even Less Simple"
fun onSimpleClicks(view: View) {
simpleClicks.onNext(view)
}
fun onLessSimpleClicks(view: View) {
lessSimpleClicks.onNext(view)
}
fun onEvenLessSimpleClicks(view: View) {
evenLessSimpleClicks.onNext(view)
}
fun getSimpleFragmentEvents(): Observable<View> = simpleClicks.asObservable()
fun getLessSimpleFragmentEvents(): Observable<View> = lessSimpleClicks.asObservable()
fun getEvenLessSimpleFragmentEvents(): Observable<View> = evenLessSimpleClicks.asObservable()
}
|
apache-2.0
|
5e52016c40ed5b4eb09e6d95d725339d
| 32.647059 | 97 | 0.755031 | 4.802521 | false | false | false | false |
mobilesolutionworks/works-controller-android
|
example-app/src/main/java/com/mobilesolutionworks/android/controller/samples/ui/activity/main/MainActivityController.kt
|
1
|
2003
|
package com.mobilesolutionworks.android.controller.samples.ui.activity.main
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import com.mobilesolutionworks.android.app.controller.HostWorksController
import com.mobilesolutionworks.android.app.controller.WorksControllerManager
import com.mobilesolutionworks.android.controller.samples.databinding.CellDemoItemBinding
import com.mobilesolutionworks.android.controller.samples.ui.databinding.DataBinding
import java.util.*
/**
* Created by yunarta on 17/3/17.
*/
class MainActivityController(manager: WorksControllerManager) : HostWorksController<MainActivity>(manager) {
private var mAdapter: DemoItemAdapter? = null
override fun onCreate(arguments: Bundle?) {
super.onCreate(arguments)
mAdapter = DemoItemAdapter()
}
fun onItemSelected(item: DemoItem) {
context.startActivity(item.intent)
}
val adapter: RecyclerView.Adapter<*>?
get() = mAdapter
private inner class DemoItemAdapter : DataBinding.SingleTypeAdapter<Void, CellDemoItemBinding>() {
private val mItems: MutableList<DemoItem>
override fun getItemLayout(): Int = R.layout.cell_demo_item
init {
val packageName = context.packageName
mItems = ArrayList<DemoItem>()
mItems.add(DemoItem(getString(R.string.demo1_title), getString(R.string.demo1_subtitle), Intent(packageName + ".action.DEMO1")))
mItems.add(DemoItem(getString(R.string.demo2_title), getString(R.string.demo2_subtitle), Intent(packageName + ".action.DEMO2")))
}
override fun onBindViewHolder(holder: DataBinding.ViewHolder<Void, CellDemoItemBinding>, position: Int) {
val binding = holder.binding
binding.item = mItems[position]
binding.controller = this@MainActivityController
}
override fun getItemCount(): Int {
return mItems.size
}
}
}
|
apache-2.0
|
89b0794cfc7151b663eb7c9c3070b459
| 34.140351 | 140 | 0.718422 | 4.701878 | false | false | false | false |
GunoH/intellij-community
|
platform/build-scripts/src/org/jetbrains/intellij/build/impl/TraceFileUploader.kt
|
7
|
4731
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package org.jetbrains.intellij.build.impl
import com.fasterxml.jackson.jr.ob.JSON
import org.jetbrains.intellij.build.toUrlWithTrailingSlash
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
open class TraceFileUploader(serverUrl: String, token: String?) {
private val serverUrl = toUrlWithTrailingSlash(serverUrl)
private val serverAuthToken = token
protected open fun log(message: String) {}
fun upload(file: Path, metadata: Map<String, String>) {
log("Preparing to upload $file to $serverUrl")
if (!Files.exists(file)) {
throw RuntimeException("The file $file does not exist")
}
val id = uploadMetadata(getFullMetadata(file, metadata))
log("Performed metadata upload. Import id is: $id")
val response = uploadFile(file, id)
log("Performed file upload. Server answered: $response")
}
private fun uploadMetadata(metadata: Map<String, String>): String {
val postUrl = "${serverUrl}import"
log("Posting to url $postUrl")
val conn = URL(postUrl).openConnection() as HttpURLConnection
conn.doInput = true
conn.doOutput = true
conn.useCaches = false
conn.instanceFollowRedirects = true
conn.requestMethod = "POST"
val metadataContent = JSON.std.asString(metadata)
log("Uploading metadata: $metadataContent")
val content = metadataContent.toByteArray(StandardCharsets.UTF_8)
conn.setRequestProperty("User-Agent", "TraceFileUploader")
conn.setRequestProperty("Connection", "Keep-Alive")
conn.setRequestProperty("Accept", "text/plain;charset=UTF-8")
conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name())
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8")
if (serverAuthToken != null) {
conn.setRequestProperty("Authorization", "Bearer $serverAuthToken")
}
conn.setRequestProperty("Content-Length", content.size.toString())
conn.setFixedLengthStreamingMode(content.size)
conn.outputStream.use { it.write(content) }
// Get the response
val code = conn.responseCode
if (code == 200 || code == 201 || code == 202 || code == 204) {
return readPlainMetadata(conn)
}
else {
throw readError(conn, code)
}
}
private fun uploadFile(file: Path, id: String): String {
val postUrl = "${serverUrl}import/${URLEncoder.encode(id, StandardCharsets.UTF_8)}/upload/tr-single"
log("Posting to url $postUrl")
val connection = URL(postUrl).openConnection() as HttpURLConnection
connection.doInput = true
connection.doOutput = true
connection.useCaches = false
connection.requestMethod = "POST"
connection.setRequestProperty("User-Agent", "TraceFileUploader")
connection.setRequestProperty("Connection", "Keep-Alive")
connection.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name())
connection.setRequestProperty("Content-Type", "application/octet-stream")
if (serverAuthToken != null) {
connection.setRequestProperty("Authorization", "Bearer $serverAuthToken")
}
val size = Files.size(file)
connection.setRequestProperty("Content-Length", size.toString())
connection.setFixedLengthStreamingMode(size)
connection.outputStream.use {
Files.copy(file, it)
}
// Get the response
return readBody(connection)
}
}
private fun getFullMetadata(file: Path, metadata: Map<String, String>): Map<String, String> {
val map = LinkedHashMap(metadata)
map.put("internal.upload.file.name", file.fileName.toString())
map.put("internal.upload.file.path", file.toString())
map.put("internal.upload.file.size", Files.size(file).toString())
return map
}
private fun readBody(connection: HttpURLConnection): String {
return connection.inputStream.use { it.readAllBytes().toString(Charsets.UTF_8) }
}
private fun readError(connection: HttpURLConnection, code: Int): Exception {
val body = readBody(connection)
return IOException("Unexpected code from server: $code body: $body")
}
private fun readPlainMetadata(connection: HttpURLConnection): String {
val body = readBody(connection).trim()
if (body.startsWith('{')) {
val `object` = JSON.std.mapFrom(body)
return (`object` as Map<*, *>).get("id") as String
}
try {
return body.toLong().toString()
}
catch (ignored: NumberFormatException) {
}
throw IOException("Server returned neither import json nor id: $body")
}
|
apache-2.0
|
57291a5ba65c9fe72fbb35f39693a511
| 36.555556 | 120 | 0.72416 | 4.231664 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt
|
4
|
3742
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.isFunctionTypeOrSubtype
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME
internal class FunctionsHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) :
AfterAnalysisHighlightingVisitor(holder, bindingContext) {
override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (expression.operationReference.getIdentifier() != null) {
expression.getResolvedCall(bindingContext)?.let { resolvedCall ->
highlightCall(expression.operationReference, resolvedCall)
}
}
super.visitBinaryExpression(expression)
}
override fun visitCallExpression(expression: KtCallExpression) {
val callee = expression.calleeExpression
val resolvedCall = expression.getResolvedCall(bindingContext)
if (callee is KtReferenceExpression && callee !is KtCallExpression && resolvedCall != null) {
highlightCall(callee, resolvedCall)
}
super.visitCallExpression(expression)
}
private fun highlightCall(callee: PsiElement, resolvedCall: ResolvedCall<out CallableDescriptor>) {
val calleeDescriptor = resolvedCall.resultingDescriptor
val extensions = KotlinHighlightingVisitorExtension.EP_NAME.extensionList
(extensions.firstNotNullOfOrNull { extension ->
extension.highlightCall(callee, resolvedCall)
} ?: when {
calleeDescriptor.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME -> KEYWORD
calleeDescriptor.isDynamic() -> DYNAMIC_FUNCTION_CALL
calleeDescriptor is FunctionDescriptor && calleeDescriptor.isSuspend -> SUSPEND_FUNCTION_CALL
resolvedCall is VariableAsFunctionResolvedCall -> {
val container = calleeDescriptor.containingDeclaration
val containedInFunctionClassOrSubclass = container is ClassDescriptor && container.defaultType.isFunctionTypeOrSubtype
if (containedInFunctionClassOrSubclass)
VARIABLE_AS_FUNCTION_CALL
else
VARIABLE_AS_FUNCTION_LIKE_CALL
}
calleeDescriptor is ConstructorDescriptor -> CONSTRUCTOR_CALL
calleeDescriptor !is FunctionDescriptor -> null
calleeDescriptor.extensionReceiverParameter != null -> EXTENSION_FUNCTION_CALL
DescriptorUtils.isTopLevelDeclaration(calleeDescriptor) -> PACKAGE_FUNCTION_CALL
else -> FUNCTION_CALL
})?.let { key ->
highlightName(callee, key)
}
}
}
|
apache-2.0
|
a3a6a6eb41085af051a6c5a0b26506a8
| 50.260274 | 158 | 0.74666 | 5.652568 | false | false | false | false |
ledboot/Toffee
|
app/src/main/java/com/ledboot/toffee/ComposeActivity.kt
|
1
|
778
|
package com.ledboot.toffee
import android.os.Bundle
import android.widget.FrameLayout
import android.widget.TextView
import com.ledboot.toffee.base.BaseActivity
/**
* Created by Gwynn on 17/10/31.
*/
class ComposeActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val root = FrameLayout(this)
root.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
val txt = TextView(this)
txt.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
root.addView(txt)
txt.text = "ComposeActivity"
setContentView(root)
}
}
|
apache-2.0
|
d96e4d8621a51901cb2b3c9c681e7903
| 30.16 | 130 | 0.737789 | 4.471264 | false | false | false | false |
DemonWav/MinecraftDev
|
src/main/kotlin/com/demonwav/mcdev/facet/LibraryPresentationProviders.kt
|
1
|
2414
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.util.get
import com.demonwav.mcdev.util.localFile
import com.demonwav.mcdev.util.manifest
import com.intellij.framework.library.LibraryVersionProperties
import com.intellij.openapi.roots.libraries.LibraryKind
import com.intellij.openapi.roots.libraries.LibraryPresentationProvider
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.VirtualFile
import java.util.jar.Attributes.Name.IMPLEMENTATION_TITLE
import java.util.jar.Attributes.Name.IMPLEMENTATION_VERSION
abstract class ManifestLibraryPresentationProvider(kind: LibraryKind, private val title: String, private val startsWith: Boolean = false)
: LibraryPresentationProvider<LibraryVersionProperties>(kind) {
final override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
for (classesRoot in classesRoots) {
val manifest = classesRoot.manifest ?: continue
val title = manifest[IMPLEMENTATION_TITLE] ?: continue
if (startsWith) {
if (!title.startsWith(this.title)) {
continue
}
} else {
if (title != this.title) {
continue
}
}
val version = manifest[IMPLEMENTATION_VERSION] ?: continue
return LibraryVersionProperties(version)
}
return null
}
}
abstract class MavenLibraryPresentationProvider(kind: LibraryKind, private val groupId: String, private val artifactId: String)
: LibraryPresentationProvider<LibraryVersionProperties>(kind) {
private val propertiesPath = "META-INF/maven/$groupId/$artifactId/pom.properties"
final override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
for (classesRoot in classesRoots) {
val file = classesRoot.localFile
val properties = JarUtil.loadProperties(file, propertiesPath) ?: continue
if (properties["groupId"] != groupId || properties["artifactId"] != artifactId) {
continue
}
val version = properties["version"] as? String ?: continue
return LibraryVersionProperties(version)
}
return null
}
}
|
mit
|
09f9f6ce6a4db513c0247e4abde8512b
| 33.485714 | 137 | 0.681856 | 5.060797 | false | false | false | false |
Scavi/BrainSqueeze
|
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day15RambunctiousRecitation.kt
|
1
|
1203
|
package com.scavi.brainsqueeze.adventofcode
import kotlin.math.abs
class Day15RambunctiousRecitation {
private class Rolling(value: Int) {
private var pos = 0
private val numbers = intArrayOf(-1, -1)
init {
add(value)
}
fun add(value: Int) {
numbers[pos++ % this.numbers.size] = value
}
fun isFirstTime() = numbers[1] == -1
fun diff() = abs(numbers[0] - numbers[1])
}
fun solve(input: String, iterations: Int = 2020): Int {
val cache = linkedMapOf<Int, Rolling>()
val numbers = input.split(",").map { it.toInt() }
var last = Rolling(0)
for (i in numbers.indices) {
last = Rolling(i + 1)
cache[numbers[i]] = last
}
var lastSpoken = -1
for (i in numbers.size + 1 until iterations + 1) {
lastSpoken = if (last.isFirstTime()) 0 else last.diff()
if (lastSpoken in cache) {
last = cache[lastSpoken]!!
last.add(i)
} else {
last = Rolling(i)
cache[lastSpoken] = last
}
}
return lastSpoken
}
}
|
apache-2.0
|
2a66a2f6060e6791496ede1f3ab1ef39
| 26.976744 | 67 | 0.509559 | 4.091837 | false | false | false | false |
hkokocin/androidKit
|
library/src/test/java/com/github/hkokocin/androidkit/widget/TextChangeListenerTest.kt
|
1
|
818
|
package com.github.hkokocin.androidkit.widget
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.then
import org.junit.Test
internal class TextChangeListenerTest {
@Test
fun delegatesBeforeTextChangedEvents() {
val callback: (CharSequence, Int, Int, Int) -> Unit = mock()
val classToTest = TextChangeListener(beforeChanged = callback)
classToTest.beforeTextChanged("string", 1, 2, 3)
then(callback).should().invoke("string", 1, 2, 3)
}
@Test
fun delegatesOnTextChangedEvents() {
val callback: (CharSequence, Int, Int, Int) -> Unit = mock()
val classToTest = TextChangeListener(onChanged = callback)
classToTest.onTextChanged("string", 1, 2, 3)
then(callback).should().invoke("string", 1, 2, 3)
}
}
|
mit
|
4df31cc02ac7f2ff55f3f5f487a95e5a
| 27.241379 | 70 | 0.676039 | 4.194872 | false | true | false | false |
phylame/jem
|
imabw/src/main/kotlin/jem/imabw/ui/AttributePane.kt
|
1
|
8107
|
/*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.imabw.ui
import javafx.fxml.FXML
import javafx.fxml.FXMLLoader
import javafx.fxml.Initializable
import javafx.scene.control.*
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.AnchorPane
import jclp.io.flobOf
import jclp.io.subMime
import jclp.setting.getDouble
import jclp.text.textOf
import jem.*
import jem.imabw.*
import mala.App
import mala.App.tr
import mala.ixin.clearAnchorConstraints
import java.net.URL
import java.util.*
class AttributePane(val chapter: Chapter) : AnchorPane() {
private val variantPane = object : VariantPane(chapter.attributes, "attributes") {
override fun availableKeys() = Attributes.names
override fun ignoredKeys() = listOf(TITLE, COVER, INTRO)
override fun getItemType(key: String) = Attributes.getType(key)
override fun getDefaultValue(key: String) =
JemSettings.getValue(key) ?: Attributes.getDefault(key) ?: ""
override fun isMultiValues(key: String): Boolean = when (key) {
in JemSettings.multipleAttrs.split(Attributes.VALUE_SEPARATOR) -> true
else -> false
}
override fun getItemTitle(key: String) = Attributes.getTitle(key) ?: key.capitalize()
override fun getAvailableValues(key: String): List<String> {
return when (key) {
STATE -> JemSettings.states.split(';').filter { it.isNotEmpty() }
GENRE -> JemSettings.genres.split(';').filter { it.isNotEmpty() }
else -> emptyList()
}
}
override fun dialogNewTitle() = App.tr("d.newAttribute.title")
}
private var cover = chapter.cover
set(value) {
isChanged = true
field = value
}
private var isChanged: Boolean = false
private val viewController: AttributeViewController
val isModified: Boolean get() = isChanged || variantPane.isModified
init {
val loader = FXMLLoader(App.assets.resourceFor("ui/AttributePane.fxml"))
val root = loader.load<SplitPane>().apply { clearAnchorConstraints() }
viewController = loader.getController()
initView()
loadCover()
loadIntro()
children += root
}
fun syncVariants() {
variantPane.syncVariants()
if (cover == null) {
chapter.attributes.remove(COVER)
} else {
chapter.cover = cover
}
viewController.introEditor.text.let {
if (it.isEmpty()) {
chapter.attributes.remove(INTRO)
} else {
chapter.intro = textOf(it)
}
}
}
fun storeState() {
variantPane.storeState()
viewController.storeState()
}
private fun initView() {
with(viewController) {
coverView.imageProperty().addListener { _, _, image ->
if (image == null) {
saveButton.isDisable = true
removeButton.isDisable = true
coverInfo.text = ""
} else {
saveButton.isDisable = false
removeButton.isDisable = false
val type = cover?.mimeType?.let { ", ${subMime(it).toUpperCase()}" } ?: ""
coverInfo.text = "${image.width.toInt()}x${image.height.toInt()}$type"
}
}
openButton.setOnAction {
selectOpenImage(tr("d.selectCover.title"), scene.window)?.let { file ->
file.inputStream().use { Image(it) }.let { img ->
if (img.isError) {
debug(tr("d.selectCover.title"), tr("d.openCover.error", file), img.exception, scene.window)
} else {
cover = flobOf(file)
coverView.image = img
}
}
}
}
saveButton.setOnAction {
val cover = cover!!
val title = tr("d.saveCover.title")
selectSaveFile(title, "cover.${subMime(cover.mimeType)}", scene.window)?.let {
saveFlob(title, cover, it, scene.window)
}
}
removeButton.setOnAction {
cover = null
loadCover()
}
attributeTitle.content = variantPane
introEditor.textProperty().addListener { _ -> isChanged = true }
}
}
private fun loadCover() {
with(viewController) {
coverView.image = cover?.let {
it.openStream().use { Image(it) }
}
}
}
private fun loadIntro() {
chapter.intro?.let { text ->
with(LoadTextTask(text, App.tr("jem.loadText.hint", chapter.title))) {
setOnSucceeded {
viewController.introEditor.text = value
isChanged = false
hideProgress()
}
Imabw.submit(this)
}
}
}
}
internal class AttributeViewController : Initializable {
@FXML
lateinit var root: SplitPane
@FXML
lateinit var coverTitle: TitledPane
@FXML
lateinit var coverAlt: Label
@FXML
lateinit var coverView: ImageView
@FXML
lateinit var coverInfo: Label
@FXML
lateinit var makeButton: Button
@FXML
lateinit var openButton: Button
@FXML
lateinit var saveButton: Button
@FXML
lateinit var removeButton: Button
@FXML
lateinit var vSplit: SplitPane
@FXML
lateinit var attributeTitle: TitledPane
@FXML
lateinit var introTitle: TitledPane
@FXML
lateinit var introEditor: TextArea
override fun initialize(location: URL?, resources: ResourceBundle?) {
coverTitle.text = tr("d.editAttribute.cover.title")
coverAlt.text = tr("d.editAttribute.cover.alt")
coverInfo.text = ""
makeButton.text = tr("ui.button.make")
makeButton.isDisable = true
openButton.text = tr("ui.button.open")
saveButton.text = tr("ui.button.save")
removeButton.text = tr("ui.button.remove")
attributeTitle.text = tr("d.editAttribute.attributes.title")
introTitle.text = tr("d.editAttribute.intro.title")
introEditor.promptText = tr("d.editAttribute.intro.hint")
coverView.imageProperty().addListener { _, _, image ->
if (image != null) {
coverView.fitWidth = minOf(UISettings.minCoverWidth, image.width)
}
}
val settings = UISettings
settings.getDouble("dialog.attributes.split.0.position")?.let {
root.setDividerPosition(0, it)
}
settings.getDouble("dialog.attributes.split.1.position")?.let {
vSplit.setDividerPosition(0, it)
}
}
fun storeState() {
val settings = UISettings
settings["dialog.attributes.split.0.position"] = root.dividerPositions.first()
settings["dialog.attributes.split.1.position"] = vSplit.dividerPositions.first()
}
}
|
apache-2.0
|
0e0b4065d20b1be0051f6a11183bfd36
| 30.558233 | 120 | 0.565437 | 4.74371 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/views/selector/StandardRoundSelector.kt
|
1
|
2173
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.views.selector
import android.content.Context
import android.util.AttributeSet
import android.view.View
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.databinding.SelectorItemImageDetailsBinding
import de.dreier.mytargets.shared.models.augmented.AugmentedStandardRound
class StandardRoundSelector @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SelectorBase<AugmentedStandardRound, SelectorItemImageDetailsBinding>(
context,
attrs,
R.layout.selector_item_image_details,
STANDARD_ROUND_REQUEST_CODE
) {
private val standardRoundDAO = ApplicationInstance.db.standardRoundDAO()
override fun bindView(item: AugmentedStandardRound) {
view.name.text = item.standardRound.name
view.details.visibility = View.VISIBLE
view.details.text = item.getDescription(context)
view.image.setImageDrawable(item.targetDrawable)
}
fun setItemId(standardRoundId: Long?) {
var standardRound = standardRoundDAO.loadStandardRoundOrNull(standardRoundId!!)
// If the round has been removed, choose default one
if (standardRound == null || standardRoundDAO.loadRoundTemplates(standardRound.id).isEmpty()) {
standardRound = standardRoundDAO.loadStandardRound(32L)
}
setItem(
AugmentedStandardRound(
standardRound,
standardRoundDAO.loadRoundTemplates(standardRound.id).toMutableList()
)
)
}
companion object {
const val STANDARD_ROUND_REQUEST_CODE = 10
}
}
|
gpl-2.0
|
650bae5f9a0befda5c76fc104d4f3a87
| 34.048387 | 103 | 0.730787 | 4.883146 | false | false | false | false |
deso88/TinyGit
|
src/main/kotlin/hamburg/remme/tinygit/git/GitRemote.kt
|
1
|
2617
|
package hamburg.remme.tinygit.git
import hamburg.remme.tinygit.domain.Branch
import hamburg.remme.tinygit.domain.Repository
private val remoteGetUrl = arrayOf("remote", "get-url", "origin")
private val remoteSetUrl = arrayOf("remote", "set-url", "origin")
private val remoteGetPushUrl = arrayOf("remote", "get-url", "--push", "origin")
private val remoteSetPushUrl = arrayOf("remote", "set-url", "--push", "origin")
private val remoteAdd = arrayOf("remote", "add", "origin")
private val remoteRemove = arrayOf("remote", "remove", "origin")
private val push = arrayOf("push")
private val pushForce = arrayOf("push", "--force")
private val pushDelete = arrayOf("push", "--delete", "origin")
private val upstream = arrayOf("--set-upstream", "origin")
fun gitGetUrl(repository: Repository): String {
val response = git(repository, *remoteGetUrl).trim()
if (response.startsWith(fatalSeparator)) return ""
return response
}
fun gitSetUrl(repository: Repository, url: String) {
git(repository, *remoteSetUrl, url)
}
fun gitGetPushUrl(repository: Repository): String {
val response = git(repository, *remoteGetPushUrl).trim()
if (response.startsWith(fatalSeparator)) return ""
return response
}
fun gitSetPushUrl(repository: Repository, url: String) {
git(repository, *remoteSetPushUrl, url)
}
fun gitAddRemote(repository: Repository, url: String) {
git(repository, *remoteAdd, url)
}
fun gitRemoveRemote(repository: Repository) {
git(repository, *remoteRemove)
}
fun gitPush(repository: Repository, force: Boolean) {
var response = git(repository, *if (force) pushForce else push).trim()
if (response.contains("$fatalSeparator.*no upstream branch".toRegex(setOf(IC, G)))) {
val name = "${fatalSeparator}The current branch (.+) has no upstream branch\\..*".toRegex(setOf(IC, G)).matchEntire(response)!!.groupValues[1]
response = git(repository, *if (force) pushForce else push, *upstream, name).trim()
} else if (response.contains("$fatalSeparator.*does not match.*the name of your current branch".toRegex(setOf(IC, G)))) {
val head = gitHead(repository)
response = git(repository, *if (force) pushForce else push, *upstream, head.name).trim()
}
if (response.contains("$errorSeparator.*tip of your current branch is behind".toRegex(setOf(IC, G)))) throw BranchBehindException()
else if (response.contains("$fatalSeparator.*timed out".toRegex(setOf(IC, G)))) throw TimeoutException()
}
fun gitPushDelete(repository: Repository, branch: Branch) {
git(repository, *pushDelete, branch.name.substringAfter("origin/"))
}
|
bsd-3-clause
|
2cb2915109ce91b065c29a6a3557ceaa
| 42.616667 | 150 | 0.716851 | 3.859882 | false | false | false | false |
neilellis/kontrol
|
common/src/main/kotlin/File_SCP.kt
|
1
|
1456
|
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* 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 kontrol.common
import net.schmizz.sshj.SSHClient
import java.io.File
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
fun File.scp(host: String? = "localhost", user: String = "root", path: String = "~/", retry: Int = 3) {
if (host == null) {
return
}
val ssh: SSHClient = SSHClient();
ssh.addHostKeyVerifier { a, b, c -> true };
for ( i in 1..retry) {
try {
ssh.connect(host);
ssh use {
ssh.authPublickey(user);
ssh.newSCPFileTransfer()?.upload(this.getAbsolutePath(), path)
}
} catch (e: Exception) {
println("Retrying for the $i time to scp to $user@$host/$path - ${e.getMessage()}")
Thread.sleep(100)
}
return
}
}
|
apache-2.0
|
10dab35870ec4b284ab39881db2fc319
| 29.978723 | 103 | 0.624313 | 3.831579 | false | false | false | false |
paplorinc/intellij-community
|
platform/platform-impl/src/org/jetbrains/io/bufferToChars.kt
|
6
|
1464
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.io
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufUtil
import io.netty.util.CharsetUtil
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.CharacterCodingException
import java.nio.charset.CharsetDecoder
import java.nio.charset.StandardCharsets
fun ByteBuf.readIntoCharBuffer(byteCount: Int = readableBytes(), charBuffer: CharBuffer) {
val decoder = CharsetUtil.decoder(StandardCharsets.UTF_8)
if (nioBufferCount() == 1) {
decodeString(decoder, internalNioBuffer(readerIndex(), byteCount), charBuffer)
}
else {
val buffer = alloc().heapBuffer(byteCount)
try {
buffer.writeBytes(this, readerIndex(), byteCount)
decodeString(decoder, buffer.internalNioBuffer(0, byteCount), charBuffer)
}
finally {
buffer.release()
}
}
}
private fun decodeString(decoder: CharsetDecoder, src: ByteBuffer, dst: CharBuffer) {
try {
var cr = decoder.decode(src, dst, true)
if (!cr.isUnderflow) {
cr.throwException()
}
cr = decoder.flush(dst)
if (!cr.isUnderflow) {
cr.throwException()
}
}
catch (x: CharacterCodingException) {
throw IllegalStateException(x)
}
}
fun writeIntAsAscii(value: Int, buffer: ByteBuf) {
ByteBufUtil.writeAscii(buffer, StringBuilder().append(value))
}
|
apache-2.0
|
6ffdae63a585a900d3d8c4f56492eae1
| 28.897959 | 140 | 0.727459 | 3.914439 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/codeInsight/handlers/superDeclarations/KotlinSuperDeclarationsInfoService.kt
|
2
|
4134
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.fir.codeInsight.handlers.superDeclarations
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.util.EditSourceUtil
import com.intellij.openapi.editor.Editor
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.psi.*
object KotlinSuperDeclarationsInfoService {
fun getForDeclarationAtCaret(file: KtFile, editor: Editor): KotlinSuperDeclarationsInfo? {
val element = file.findElementAt(editor.caretModel.offset) ?: return null
val declaration = PsiTreeUtil.getParentOfType<KtDeclaration>(
element,
KtNamedFunction::class.java,
KtClass::class.java,
KtProperty::class.java,
KtObjectDeclaration::class.java
) ?: return null
return getForDeclaration(declaration)
}
fun getForDeclaration(declaration: KtDeclaration): KotlinSuperDeclarationsInfo? {
@OptIn(KtAllowAnalysisOnEdt::class)
return allowAnalysisOnEdt {
analyze(declaration) {
val symbol = declaration.getSymbol()
// TODO add navigation to expect declarations here
createList(symbol)
}
}
}
fun navigateToSuperDeclaration(info: KotlinSuperDeclarationsInfo, editor: Editor) {
when (info.superDeclarations.size) {
0 -> {
}
1 -> {
val navigatable = EditSourceUtil.getDescriptor(info.superDeclarations[0])
if (navigatable != null && navigatable.canNavigate()) {
navigatable.navigate(true)
}
}
else -> {
val popupTitle = getPopupTitle(info.kind)
val superDeclarationsArray = PsiUtilCore.toPsiElementArray(info.superDeclarations)
val popup = NavigationUtil.getPsiElementPopup(superDeclarationsArray, popupTitle)
popup.showInBestPositionFor(editor)
}
}
}
@Nls
private fun getPopupTitle(declarationKind: KotlinSuperDeclarationsInfo.DeclarationKind): String =
when (declarationKind) {
KotlinSuperDeclarationsInfo.DeclarationKind.CLASS -> KotlinBundle.message("goto.super.chooser.class.title")
KotlinSuperDeclarationsInfo.DeclarationKind.PROPERTY -> KotlinBundle.message("goto.super.chooser.property.title")
KotlinSuperDeclarationsInfo.DeclarationKind.FUNCTION -> KotlinBundle.message("goto.super.chooser.function.title")
}
private fun KtAnalysisSession.createList(symbol: KtSymbol): KotlinSuperDeclarationsInfo? = when (symbol) {
is KtCallableSymbol -> KotlinSuperDeclarationsInfo(
symbol.getDirectlyOverriddenSymbols().mapNotNull { it.psi },
when (symbol) {
is KtPropertySymbol -> KotlinSuperDeclarationsInfo.DeclarationKind.PROPERTY
else -> KotlinSuperDeclarationsInfo.DeclarationKind.FUNCTION
}
)
is KtClassOrObjectSymbol -> KotlinSuperDeclarationsInfo(
symbol.superTypes.mapNotNull { (it as? KtNonErrorClassType)?.classSymbol?.psi },
KotlinSuperDeclarationsInfo.DeclarationKind.CLASS,
)
else -> null
}
}
|
apache-2.0
|
15a898a0ecb98d9ea7af657f9a02d51c
| 44.944444 | 158 | 0.704886 | 5.432326 | false | false | false | false |
google/intellij-community
|
platform/platform-tests/testSrc/com/intellij/ide/RecentProjectManagerTest.kt
|
3
|
16389
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide
import com.intellij.configurationStore.deserializeInto
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Test
class RecentProjectManagerTest {
companion object {
@ClassRule
@JvmField
val appRule = ApplicationRule()
}
@Test
fun `ignore projects in additionalInfo if not in recentPaths`() {
val manager = RecentProjectsManagerBase()
val element = JDOMUtil.load("""
<application>
<component name="RecentDirectoryProjectsManager">
<option name="recentPaths">
<list>
<option value="/home/WebstormProjects/untitled" />
<option value="/home/WebstormProjects/conference-data" />
</list>
</option>
<option name="pid" value="" />
<option name="additionalInfo">
<map>
<entry key="/home/WebstormProjects/conference-data">
<value>
<RecentProjectMetaInfo>
<option name="build" value="WS-191.8026.39" />
<option name="productionCode" value="WS" />
<option name="projectOpenTimestamp" value="1572355647642" />
<option name="buildTimestamp" value="1564385774770" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/WebstormProjects/new-react-app-for-testing">
<value>
<RecentProjectMetaInfo>
<option name="build" value="WS-191.8026.39" />
<option name="productionCode" value="WS" />
<option name="projectOpenTimestamp" value="1571662310725" />
<option name="buildTimestamp" value="1564385807237" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/WebstormProjects/untitled">
<value>
<RecentProjectMetaInfo>
<option name="build" value="WS-191.8026.39" />
<option name="productionCode" value="WS" />
<option name="projectOpenTimestamp" value="1574357146611" />
<option name="buildTimestamp" value="1564385803063" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/WebstormProjects/untitled2">
<value>
<RecentProjectMetaInfo>
<option name="build" value="WS-191.8026.39" />
<option name="productionCode" value="WS" />
<option name="projectOpenTimestamp" value="1574416340298" />
<option name="buildTimestamp" value="1564385805606" />
</RecentProjectMetaInfo>
</value>
</entry>
</map>
</option>
</component>
</application>
""".trimIndent())
val state = RecentProjectManagerState()
element.getChild("component")!!.deserializeInto(state)
manager.loadState(state)
assertThat(manager.state.additionalInfo.keys.joinToString("\n")).isEqualTo("""
/home/WebstormProjects/conference-data
/home/WebstormProjects/untitled
""".trimIndent())
@Suppress("DEPRECATION")
assertThat(manager.state.recentPaths).isEmpty()
}
@Test
fun `use order of recentPaths`() {
val manager = RecentProjectsManagerBase()
val element = JDOMUtil.load("""
<application>
<component name="RecentDirectoryProjectsManager">
<option name="recentPaths">
<list>
<option value="/home/boo/Documents/macosSwiftApp" />
<option value="/home/boo/Downloads/tester" />
<option value="/home/boo/Downloads/RLBasicsWithSwift" />
<option value="/home/boo/Documents/iOSSwiftTabbedApp" />
<option value="/home/boo/Downloads/xcode83betaswift-2 copy" />
<option value="/home/boo/Downloads/iOS" />
<option value="/home/boo/Downloads/SwiftTabbedApp" />
<option value="/home/boo/Documents/NewProjBridging" />
<option value="/home/boo/Documents/BasicOc" />
<option value="/home/boo/Documents/test_performance/LotOfPods" />
<option value="/home/boo/Documents/AllTargetsXcode11" />
<option value="/home/boo/Documents/BasicSwift" />
<option value="/home/boo/Downloads/WordPress-iOS" />
<option value="/home/boo/Documents/iosSingleSwift" />
<option value="/home/boo/Downloads/CocoaConferences 2" />
<option value="/home/boo/Documents/AllTargetsXcode103" />
<option value="/home/boo/Documents/newproj201924" />
<option value="/home/boo/Documents/BrightFuturesTestProj" />
<option value="/home/boo/Documents/GoogleTestTests" />
</list>
</option>
<option name="pid" value="" />
<option name="additionalInfo">
<map>
<entry key="/home/boo/Documents/AllTargetsXcode103">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1572464701329" />
<option name="buildTimestamp" value="1572424192550" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/AllTargetsXcode11">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1574080992714" />
<option name="buildTimestamp" value="1572424187281" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/BasicOc">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1574684942778" />
<option name="buildTimestamp" value="1573809737599" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/BasicSwift">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1573756936051" />
<option name="buildTimestamp" value="1572424142023" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/BrightFuturesTestProj">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1572429822369" />
<option name="buildTimestamp" value="1572424166312" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/GoogleTestTests">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.6817.17" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1571921596983" />
<option name="buildTimestamp" value="1569327129141" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/NewProjBridging">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1574771900633" />
<option name="buildTimestamp" value="1573809725318" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/iOSSwiftTabbedApp">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1575896734989" />
<option name="buildTimestamp" value="1573809763448" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/iosSingleSwift">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1573049774371" />
<option name="buildTimestamp" value="1572424145779" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/macosSwiftApp">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1579175388001" />
<option name="buildTimestamp" value="1573809737924" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/newSingleViewXC103eap">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.6817.17" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1571314481851" />
<option name="buildTimestamp" value="1569327149819" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/newproj201924">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1572431637302" />
<option name="buildTimestamp" value="1572424176426" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Documents/test_performance/LotOfPods">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1574684915629" />
<option name="buildTimestamp" value="1573809737599" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/CocoaConferences 2">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1572529865352" />
<option name="buildTimestamp" value="1572424181156" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/RLBasicsWithSwift">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1576074883019" />
<option name="buildTimestamp" value="1573809726760" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/SwiftTabbedApp">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1574783065457" />
<option name="buildTimestamp" value="1573809754773" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/WordPress-iOS">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.40" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1573740056455" />
<option name="buildTimestamp" value="1572424172238" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/iOS">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1575745861387" />
<option name="buildTimestamp" value="1573809773068" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/tester">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1576075411776" />
<option name="buildTimestamp" value="1573809726760" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="/home/boo/Downloads/xcode83betaswift-2 copy">
<value>
<RecentProjectMetaInfo>
<option name="build" value="OC-192.7142.54" />
<option name="productionCode" value="OC" />
<option name="binFolder" value="/app/bin" />
<option name="projectOpenTimestamp" value="1575896694506" />
<option name="buildTimestamp" value="1573809763448" />
</RecentProjectMetaInfo>
</value>
</entry>
</map>
</option>
</component>
</application>
""".trimIndent())
val state = RecentProjectManagerState()
element.getChild("component")!!.deserializeInto(state)
manager.loadState(state)
assertThat(manager.getRecentPaths()).containsExactly("/home/boo/Documents/macosSwiftApp",
"/home/boo/Downloads/tester",
"/home/boo/Downloads/RLBasicsWithSwift",
"/home/boo/Documents/iOSSwiftTabbedApp",
"/home/boo/Downloads/xcode83betaswift-2 copy",
"/home/boo/Downloads/iOS",
"/home/boo/Downloads/SwiftTabbedApp",
"/home/boo/Documents/NewProjBridging",
"/home/boo/Documents/BasicOc",
"/home/boo/Documents/test_performance/LotOfPods",
"/home/boo/Documents/AllTargetsXcode11",
"/home/boo/Documents/BasicSwift",
"/home/boo/Downloads/WordPress-iOS",
"/home/boo/Documents/iosSingleSwift",
"/home/boo/Downloads/CocoaConferences 2",
"/home/boo/Documents/AllTargetsXcode103",
"/home/boo/Documents/newproj201924",
"/home/boo/Documents/BrightFuturesTestProj",
"/home/boo/Documents/GoogleTestTests")
}
}
|
apache-2.0
|
2db74b04f7d9ae386916f0d345102a39
| 43.177898 | 120 | 0.57441 | 4.568999 | false | true | false | false |
sakki54/RLGdx
|
src/main/kotlin/com/brekcel/RLGdx/text/TextMap.kt
|
1
|
1887
|
//=====Copyright 2017 Clayton Breckel=====//
package com.brekcel.RLGdx.text
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.utils.Disposable
/** A class that acts as a Font handler. Contains the font texture and some characteristics about it. */
internal class TextMap : Disposable {
/** The width, in px, of each character */
val charWidth: Int
/** The height, in px, of each character */
val charHeight: Int
/** The width, in characters, of the image */
val charsWide: Int
/** The height, in characters, of the image */
val charsHigh: Int
/** Total number of characters. Equal to charsWidth * charsHeight */
val numChars: Int
/** The texture that contains the font */
val tex: Texture
/** 2D array of TextureRegions that makes up the font */
val texts: Array<Array<TextureRegion>>
/**
* Creates a new TextMap
* @param image A file that contains a bitmapfont. Used as Gdx.files.internal(image) to load font.
* @param charWidth The width (in pixels) of each character
* @param charHeight The height (in pixels) of each character
*/
constructor(image: FileHandle, charWidth: Int = 8, charHeight: Int = 8) {
tex = Texture(image)
this.charsWide = tex.width / charWidth
this.charsHigh = tex.height / charHeight
this.charWidth = charWidth
this.charHeight = charHeight
numChars = charWidth * charHeight
texts = TextureRegion.split(tex, charWidth, charHeight)
}
/**
* Returns the TextureRegion that contains the given char
* @param c The Char that you want the TextureRegion of
*/
fun getTex(c: Char): TextureRegion {
val x = c.toInt() / charsWide
val y = c.toInt() % charsHigh
return texts[x][y]
}
/** Disposes all unmanaged resources. In this case just the texture */
override fun dispose() {
tex.dispose()
}
}
|
mit
|
13f55ebee43e2970e43a59378a9a8b15
| 28.968254 | 104 | 0.714361 | 3.678363 | false | false | false | false |
customerly/Customerly-Android-SDK
|
customerly-android-sdk/src/main/java/io/customerly/entity/chat/ClyMessage.kt
|
1
|
13447
|
package io.customerly.entity.chat
/*
* Copyright (C) 2017 Customerly
*
* 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.
*/
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Spanned
import android.text.SpannedString
import android.view.WindowManager
import android.widget.TextView
import io.customerly.Customerly
import io.customerly.activity.ClyAppCompatActivity
import io.customerly.alert.showClyAlertMessage
import io.customerly.api.ClyApiRequest
import io.customerly.api.ENDPOINT_CONVERSATION_DISCARD
import io.customerly.entity.ERROR_CODE__GENERIC
import io.customerly.entity.clySendError
import io.customerly.entity.ping.ClyFormDetails
import io.customerly.sxdependencies.annotations.SXIntDef
import io.customerly.sxdependencies.annotations.SXUiThread
import io.customerly.utils.ClyActivityLifecycleCallback
import io.customerly.utils.ggkext.*
import io.customerly.utils.htmlformatter.fromHtml
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
/**
* Created by Gianni on 11/09/16.
* Project: Customerly Android SDK
*/
@SuppressLint("ConstantLocale")
private val TIME_FORMATTER = SimpleDateFormat("HH:mm", Locale.getDefault())
private val DATE_FORMATTER = SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG)
internal const val CONVERSATIONID_UNKNOWN_FOR_MESSAGE = -1L
private const val CSTATE_COMPLETED = 1
private const val CSTATE_SENDING = 0
private const val CSTATE_FAILED = -1
private const val CSTATE_PENDING = -2
@SXIntDef(CSTATE_COMPLETED, CSTATE_FAILED, CSTATE_SENDING, CSTATE_PENDING)
@Retention(AnnotationRetention.SOURCE)
private annotation class CState
@Throws(JSONException::class)
internal fun JSONObject.parseMessage() : ClyMessage {
return ClyMessage.Human.Server(
writerUserid = this.optTyped(name = "user_id", fallback = 0L),
writerAccountId = this.optTyped(name = "account_id", fallback = 0L),
writerAccountName = this.optTyped<JSONObject>(name = "account")?.optTyped(name = "name"),
id = this.optTyped(name = "conversation_message_id", fallback = 0L),
conversationId = this.optTyped(name = "conversation_id", fallback = CONVERSATIONID_UNKNOWN_FOR_MESSAGE),
content = this.optTyped(name = "content", fallback = ""),
attachments = this.optSequenceOpt<JSONObject>(name = "attachments")
?.map { it?.nullOnException { json -> json.parseAttachment() } }
?.requireNoNulls()
?.toList()?.toTypedArray() ?: emptyArray(),
contentAbstract = fromHtml(this.optTyped(name = "abstract", fallback = "")),
sentDatetime = this.optTyped(name = "sent_date", fallback = 0L),
seenDate = this.optTyped(name = "seen_date", fallback = 0L),
richMailLink = if (this.optTyped(name = "rich_mail", fallback = 0) == 0) {
null
} else {
this.optTyped<String>(name = "rich_mail_link")
},
discarded = this.optTyped("discarded", 0) == 1,
cState = CSTATE_COMPLETED)
}
internal fun JSONObject.parseMessagesList() : ArrayList<ClyMessage> {
return this.optArrayList<JSONObject, ClyMessage>(name = "messages", map = { it.parseMessage() }) ?: ArrayList(0)
}
internal sealed class ClyMessage(
internal val writer : ClyWriter,
internal val id : Long,
internal val conversationId : Long,
internal val content : String,
internal val attachments : Array<ClyAttachment> = emptyArray(),
internal val contentAbstract : Spanned = when {
content.isNotEmpty() -> fromHtml(message = content)
attachments.isNotEmpty() -> SpannedString("[Attachment]")
else -> SpannedString("")
},
@STimestamp internal val sentDatetime : Long = System.currentTimeMillis().msAsSeconds,
@STimestamp private val seenDate : Long = sentDatetime,
internal val richMailLink : String? = null,
@CState private var cState : Int = CSTATE_SENDING,
internal var discarded: Boolean = false) {
internal sealed class Bot(messageId: Long, conversationId: Long, content: String)
: ClyMessage(writer = ClyWriter.Bot, conversationId = conversationId, id = messageId, content = content, cState = CSTATE_COMPLETED) {
internal class Text(conversationId: Long, messageId: Long, content: String)
: ClyMessage.Bot(conversationId = conversationId, messageId = messageId, content = content)
internal sealed class Form(conversationId: Long, messageId: Long, content: String)
: ClyMessage.Bot(conversationId = conversationId, messageId = messageId, content = content) {
internal class Profiling(conversationId: Long, messageId: Long, internal val form: ClyFormDetails)
: Bot.Form(conversationId = conversationId, messageId = messageId, content = form.label.takeIf { it.isNotEmpty() } ?: form.hint ?: "")
internal class AskEmail(conversationId: Long, messageId: Long, val pendingMessage: Human.UserLocal? = null)
: Bot.Form(messageId = messageId, content = "", conversationId = conversationId)
}
}
internal sealed class Human(
writer: ClyWriter,
id : Long = 0,
conversationId : Long,
content : String,
attachments : Array<ClyAttachment>,
contentAbstract : Spanned = when {
content.isNotEmpty() -> fromHtml(message = content)
attachments.isNotEmpty() -> SpannedString("[Attachment]")
else -> SpannedString("")
},
@STimestamp sentDatetime : Long = System.currentTimeMillis().msAsSeconds,
@STimestamp seenDate : Long = sentDatetime,
richMailLink : String? = null,
@CState cState : Int,
discarded: Boolean = false
): ClyMessage(
writer = writer,
id = id,
conversationId = conversationId,
content = content,
attachments = attachments,
contentAbstract = contentAbstract,
sentDatetime = sentDatetime,
seenDate = seenDate,
richMailLink = richMailLink,
cState = cState,
discarded = discarded
) {
internal class Server(writerUserid : Long = 0,
writerAccountId : Long = 0,
writerAccountName : String? = null,
id : Long = 0,
conversationId : Long,
content : String,
attachments : Array<ClyAttachment>,
contentAbstract : Spanned = when {
content.isNotEmpty() -> fromHtml(message = content)
attachments.isNotEmpty() -> SpannedString("[Attachment]")
else -> SpannedString("")
},
@STimestamp sentDatetime : Long = System.currentTimeMillis().msAsSeconds,
@STimestamp seenDate : Long = sentDatetime,
richMailLink : String? = null,
discarded: Boolean = false,
@CState cState : Int) : Human(
writer = ClyWriter.Real.from(userId = writerUserid, accountId = writerAccountId, name = writerAccountName),
id = id,
conversationId = conversationId,
content = content,
attachments = attachments,
contentAbstract = contentAbstract,
sentDatetime = sentDatetime,
seenDate = seenDate,
richMailLink = richMailLink,
discarded = discarded,
cState = cState)
internal class UserLocal(
userId : Long = -1,
conversationId : Long,
content : String,
attachments : Array<ClyAttachment>)
: ClyMessage.Human(
writer = ClyWriter.Real.User(userId = userId, name = null),
conversationId = conversationId,
content = content,
attachments = attachments,
cState = when(userId) {
-1L -> CSTATE_PENDING
else -> CSTATE_SENDING
})
}
internal val dateString: String = DATE_FORMATTER.format(Date(this.sentDatetime.secondsAsMs))
internal val timeString: String = TIME_FORMATTER.format(Date(this.sentDatetime.secondsAsMs))
private var contentSpanned : Spanned? = null
internal val isNotSeen: Boolean
get() = this.writer.isAccount && this.seenDate == 0L
internal val isStateSending: Boolean
get() = this.cState == CSTATE_SENDING
internal val isStatePending: Boolean
get() = this.cState == CSTATE_PENDING
internal val isStateFailed: Boolean
get() = this.cState == CSTATE_FAILED
internal fun setStateSending() {
this.cState = CSTATE_SENDING
}
internal fun setStateFailed() {
this.cState = CSTATE_FAILED
}
internal fun isSentSameDay(of : ClyMessage) : Boolean
= this.sentDatetime / (/*1000**/60 * 60 * 24) == of.sentDatetime / (/*1000**/60 * 60 * 24)
internal fun getContentSpanned(tv: TextView, pImageClickableSpan : (Activity, String)->Unit): Spanned {
var spanned = this.contentSpanned
if(spanned == null) {
spanned = fromHtml(message = this.content, tv = tv, pImageClickableSpan = pImageClickableSpan)
this.contentSpanned = spanned
}
return spanned
}
fun toConversation(): ClyConversation {
return ClyConversation(id = this.conversationId, lastMessage = this.toConvLastMessage())
}
fun toConvLastMessage() : ClyConvLastMessage {
return ClyConvLastMessage(message = this.contentAbstract, date = this.sentDatetime, writer = this.writer, discarded = this.discarded)
}
override fun equals(other: Any?): Boolean {
return this === other || (this.javaClass == other?.javaClass && this.id == (other as ClyMessage).id)
}
override fun hashCode(): Int {
return id.hashCode()
}
fun postDisplay() {
Handler(Looper.getMainLooper()).post {
val currentActivity: Activity? = ClyActivityLifecycleCallback.getLastDisplayedActivity()
if (currentActivity != null && Customerly.isEnabledActivity(activity = currentActivity)) {
this.displayNow(activity = currentActivity)
} else {
Customerly.postOnActivity = { activity ->
this.displayNow(activity = activity)
true
}
}
}
}
@SXUiThread
private fun displayNow(activity: Activity, retryOnFailure: Boolean = true) {
try {
when (activity) {
is ClyAppCompatActivity -> activity.onNewSocketMessages(messages = arrayListOf(this))
else -> {
try {
activity.showClyAlertMessage(message = this)
Customerly.log(message = "Last message alert successfully displayed")
} catch (changedActivityWhileExecuting: WindowManager.BadTokenException) {
if(retryOnFailure) {
ClyActivityLifecycleCallback.getLastDisplayedActivity()
?.takeIf { Customerly.isEnabledActivity(activity = it) }
?.let {
this.displayNow(activity = it, retryOnFailure = false)
}
}
}
}
}
} catch (exception: Exception) {
Customerly.log(message = "A generic error occurred Customerly while displaying a last message alert")
clySendError(errorCode = ERROR_CODE__GENERIC, description = "Generic error in Customerly while displaying a last message alert", throwable = exception)
}
}
internal fun discard(context: Context) {
ClyApiRequest<Any>(
context = context,
endpoint = ENDPOINT_CONVERSATION_DISCARD,
requireToken = true,
jsonObjectConverter = { it })
.p(key = "conversation_ids", value = JSONArray().also { ja -> ja.put(this.conversationId) })
.start()
this.discarded = true
}
}
|
apache-2.0
|
b20b54962c1feca2154e163f9ff908ab
| 43.088525 | 163 | 0.611066 | 5.167948 | false | false | false | false |
allotria/intellij-community
|
plugins/ide-features-trainer/src/training/learn/lesson/general/refactorings/ExtractMethodCocktailSortLesson.kt
|
1
|
3187
|
// 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 training.learn.lesson.general.refactorings
import com.intellij.CommonBundle
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.actions.BaseRefactoringAction
import com.intellij.ui.UIBundle
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import javax.swing.JDialog
class ExtractMethodCocktailSortLesson(private val sample: LessonSample)
: KLesson("Extract method", LessonsBundle.message("extract.method.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit
get() = {
prepareSample(sample)
val extractMethodDialogTitle = RefactoringBundle.message("extract.method.title")
lateinit var startTaskId: TaskContext.TaskId
task("ExtractMethod") {
startTaskId = taskId
text(LessonsBundle.message("extract.method.invoke.action", action(it)))
triggerByUiComponentAndHighlight(false, false) { dialog: JDialog ->
dialog.title == extractMethodDialogTitle
}
restoreIfModifiedOrMoved()
test { actions(it) }
}
// Now will be open the first dialog
val okButtonText = CommonBundle.getOkButtonText()
val yesButtonText = CommonBundle.getYesButtonText().dropMnemonic()
val replaceFragmentDialogTitle = RefactoringBundle.message("replace.fragment")
task {
text(LessonsBundle.message("extract.method.start.refactoring", strong(okButtonText)))
// Wait until the first dialog will gone but we st
stateCheck {
val ui = previous.ui ?: return@stateCheck false
!ui.isShowing && insideRefactoring()
}
restoreByUi(delayMillis = defaultRestoreDelay)
test(waitEditorToBeReady = false) {
dialog(extractMethodDialogTitle) {
button(okButtonText).click()
}
}
}
task {
text(LessonsBundle.message("extract.method.confirm.several.replaces", strong(yesButtonText)))
// Wait until the third dialog
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { dialog: JDialog ->
dialog.title == replaceFragmentDialogTitle
}
restoreState(restoreId = startTaskId) {
!insideRefactoring()
}
test(waitEditorToBeReady = false) {
dialog(extractMethodDialogTitle) {
button(yesButtonText).click()
}
}
}
task {
text(LessonsBundle.message("extract.method.second.fragment"))
stateCheck {
previous.ui?.isShowing?.not() ?: true
}
test(waitEditorToBeReady = false) {
dialog(replaceFragmentDialogTitle) {
button(UIBundle.message("replace.prompt.replace.button").dropMnemonic()).click()
}
}
}
}
private fun insideRefactoring() = Thread.currentThread().stackTrace.any {
it.className.contains(BaseRefactoringAction::class.java.simpleName)
}
}
|
apache-2.0
|
e4664ec90d99588c89edaddea23c4698
| 35.632184 | 140 | 0.682146 | 5.156958 | false | false | false | false |
allotria/intellij-community
|
plugins/git4idea/src/git4idea/index/GitStageManager.kt
|
2
|
2273
|
// 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 git4idea.index
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.impl.LineStatusTrackerSettingListener
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.vcs.commit.CommitMode
import com.intellij.vcs.commit.CommitModeManager
import git4idea.GitVcs
import git4idea.config.GitVcsApplicationSettings
internal class CommitModeListener(val project: Project) : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
ApplicationManager.getApplication().assertIsDispatchThread()
if (isStagingAreaAvailable(project)) {
GitStageTracker.getInstance(project).updateTrackerState()
}
invokeLater {
// Notify LSTM after CLM to let it save current partial changelists state
ApplicationManager.getApplication().messageBus.syncPublisher(LineStatusTrackerSettingListener.TOPIC).settingsUpdated()
}
}
}
internal class GitStageStartupActivity : StartupActivity.Background {
override fun runActivity(project: Project) {
if (isStagingAreaAvailable(project)) {
GitStageTracker.getInstance(project) // initialize tracker
}
}
}
fun stageLineStatusTrackerRegistryOption() = Registry.get("git.enable.stage.line.status.tracker")
fun enableStagingArea(enabled: Boolean) {
val applicationSettings = GitVcsApplicationSettings.getInstance()
if (enabled == applicationSettings.isStagingAreaEnabled) return
applicationSettings.isStagingAreaEnabled = enabled
ApplicationManager.getApplication().messageBus.syncPublisher(CommitModeManager.SETTINGS).settingsChanged()
}
fun canEnableStagingArea() = CommitModeManager.isNonModalInSettings()
fun isStagingAreaAvailable(project: Project): Boolean {
val commitMode = CommitModeManager.getInstance(project).getCurrentCommitMode()
return commitMode is CommitMode.ExternalCommitMode &&
commitMode.vcs.keyInstanceMethod == GitVcs.getKey()
}
|
apache-2.0
|
1cd666f742d2ee51ea18961f95f28241
| 40.345455 | 140 | 0.813022 | 5.107865 | false | false | false | false |
F43nd1r/acra-backend
|
acrarium/src/main/kotlin/com/faendir/acra/ui/component/InstallationView.kt
|
1
|
2313
|
/*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.component
import com.faendir.acra.service.AvatarService
import com.faendir.acra.ui.ext.stringProperty
import com.vaadin.flow.component.AttachEvent
import com.vaadin.flow.component.DetachEvent
import com.vaadin.flow.component.Tag
import com.vaadin.flow.component.dependency.JsModule
import com.vaadin.flow.component.littemplate.LitTemplate
import com.vaadin.flow.server.StreamRegistration
import com.vaadin.flow.server.StreamResource
import com.vaadin.flow.server.StreamResourceRegistry
import com.vaadin.flow.server.VaadinSession
/**
* @author lukas
* @since 23.04.19
*/
@Tag("acrarium-image-with-label")
@JsModule("./elements/image-with-label.ts")
class InstallationView(private val avatarService: AvatarService) : LitTemplate() {
private var resource: StreamResource? = null
private var registration: StreamRegistration? = null
private var image by stringProperty("image")
private var label by stringProperty("label")
fun setInstallationId(installationId: String) {
resource = avatarService.getAvatar(installationId)
image = StreamResourceRegistry.getURI(resource).toASCIIString()
label = installationId
if (parent.isPresent) {
register()
}
}
override fun onAttach(attachEvent: AttachEvent) {
if (resource != null) {
register()
}
super.onAttach(attachEvent)
}
private fun register() {
registration = VaadinSession.getCurrent().resourceRegistry.registerResource(resource)
}
override fun onDetach(detachEvent: DetachEvent) {
super.onDetach(detachEvent)
registration?.unregister()
}
}
|
apache-2.0
|
9da04f2c5a2804c1314afee9c0bd52b7
| 33.537313 | 93 | 0.733247 | 4.197822 | false | false | false | false |
genonbeta/TrebleShot
|
app/src/main/java/org/monora/uprotocol/client/android/ApplicationGlideModule.kt
|
1
|
7001
|
/*
* 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
import android.content.Context
import android.content.pm.ApplicationInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import android.util.Size
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoader.LoadData
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.signature.ObjectKey
import org.monora.uprotocol.client.android.content.removeId
import java.io.FileInputStream
import java.io.FileNotFoundException
/**
* created by: Veli
* date: 28.03.2018 17:29
*/
@GlideModule
class ApplicationGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
super.registerComponents(context, glide, registry)
registry.append(
ApplicationInfo::class.java,
Drawable::class.java,
AppIconModelLoaderFactory(context)
)
registry.append(
Uri::class.java,
Bitmap::class.java,
AlbumArtModelLoaderFactory(context)
)
}
internal class AlbumArtDataFetcher(val context: Context, val model: Uri) : DataFetcher<Bitmap> {
override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in Bitmap>) {
try {
if (Build.VERSION.SDK_INT >= 29) {
callback.onDataReady(
context.contentResolver.loadThumbnail(model, Size(500, 500), null)
)
} else {
val cursor = context.contentResolver.query(
model, arrayOf(MediaStore.Audio.Albums.ALBUM_ART), null, null, null,
) ?: throw FileNotFoundException("Could not query the uri: $model")
cursor.use {
if (it.moveToFirst()) {
val albumArtIndex = it.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)
val albumArt = it.getString(albumArtIndex) ?: throw FileNotFoundException(
"The file path was empty"
)
FileInputStream(albumArt).use { inputStream ->
val artData = inputStream.readBytes()
callback.onDataReady(BitmapFactory.decodeByteArray(artData, 0, artData.size))
}
} else {
throw FileNotFoundException("No row returned after query")
}
}
}
} catch (e: Exception) {
callback.onLoadFailed(e)
} catch (ignored: Throwable) {
callback.onLoadFailed(Exception())
}
}
override fun cleanup() {
// Empty Implementation
}
override fun cancel() {
// Empty Implementation
}
override fun getDataClass(): Class<Bitmap> {
return Bitmap::class.java
}
override fun getDataSource(): DataSource {
return DataSource.LOCAL
}
}
internal class AlbumArtModelLoader(private val context: Context) : ModelLoader<Uri, Bitmap> {
override fun buildLoadData(uri: Uri, width: Int, height: Int, options: Options): LoadData<Bitmap> {
return LoadData(ObjectKey(uri), AlbumArtDataFetcher(context, uri))
}
override fun handles(uri: Uri): Boolean {
try {
return MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI == uri.removeId()
} catch (ignored: Throwable) { }
return false
}
}
internal class AlbumArtModelLoaderFactory(
private val context: Context,
) : ModelLoaderFactory<Uri, Bitmap> {
override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Uri, Bitmap> {
return AlbumArtModelLoader(context)
}
override fun teardown() {
// Empty Implementation.
}
}
internal class AppIconDataFetcher(val context: Context, val model: ApplicationInfo) : DataFetcher<Drawable> {
override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in Drawable>) {
callback.onDataReady(context.packageManager.getApplicationIcon(model))
}
override fun cleanup() {
// Empty Implementation
}
override fun cancel() {
// Empty Implementation
}
override fun getDataClass(): Class<Drawable> {
return Drawable::class.java
}
override fun getDataSource(): DataSource {
return DataSource.LOCAL
}
}
internal class AppIconModelLoader(private val context: Context) : ModelLoader<ApplicationInfo, Drawable> {
override fun buildLoadData(
applicationInfo: ApplicationInfo, width: Int, height: Int, options: Options,
): LoadData<Drawable> {
return LoadData(ObjectKey(applicationInfo), AppIconDataFetcher(context, applicationInfo))
}
override fun handles(applicationInfo: ApplicationInfo): Boolean {
return true
}
}
internal class AppIconModelLoaderFactory(
private val context: Context,
) : ModelLoaderFactory<ApplicationInfo, Drawable> {
override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<ApplicationInfo, Drawable> {
return AppIconModelLoader(context)
}
override fun teardown() {
// Empty Implementation.
}
}
}
|
gpl-2.0
|
5569e661cb9a074cb43fe65856c1ef80
| 36.037037 | 113 | 0.634 | 5.128205 | false | false | false | false |
DeflatedPickle/Quiver
|
foldertree/src/main/kotlin/com/deflatedpickle/quiver/foldertree/FolderTreePlugin.kt
|
1
|
2426
|
/* Copyright (c) 2020-2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.foldertree
import com.athaydes.kunion.Union
import com.deflatedpickle.haruhi.api.plugin.Plugin
import com.deflatedpickle.haruhi.api.plugin.PluginType
import com.deflatedpickle.haruhi.event.EventProgramFinishSetup
import com.deflatedpickle.quiver.Quiver
import com.deflatedpickle.quiver.backend.event.EventOpenPack
import com.deflatedpickle.quiver.backend.event.EventSearchFolder
import com.deflatedpickle.quiver.filewatcher.event.EventFileSystemUpdate
import com.deflatedpickle.quiver.frontend.widget.SearchToolbar
import java.awt.BorderLayout
import java.io.File
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.TreePath
import kotlin.io.path.ExperimentalPathApi
@OptIn(ExperimentalPathApi::class)
@Suppress("unused")
@Plugin(
value = "$[name]",
author = "$[author]",
version = "$[version]",
description = """
<br>
Provides a panel on which a given file can be configured
""",
type = PluginType.COMPONENT,
component = Component::class,
dependencies = [
"deflatedpickle@file_panel#>=1.0.0",
"deflatedpickle@file_watcher"
]
)
object FolderTreePlugin {
private val toolbar = SearchToolbar(Union.U2.ofA(FolderTree))
init {
EventProgramFinishSetup.addListener {
Component.add(this.toolbar, BorderLayout.NORTH)
}
EventOpenPack.addListener {
FolderTree.refreshAll()
}
EventFileSystemUpdate.addListener {
// Waiting until Haruhi updates events to have sources
if (it.isDirectory || !it.exists()) {
FolderTree.refreshAll()
}
}
EventSearchFolder.addListener {
var parent: File? = it.parentFile
val selectPath = mutableListOf(it)
while (parent != null) {
selectPath.add(0, parent)
parent = if (parent.path != Quiver.packDirectory!!.path) {
parent.parentFile
} else {
null
}
}
// This selects the right folder, but not visually
FolderTree.selectionPath = TreePath(
selectPath.map { file ->
DefaultMutableTreeNode(file)
}.toTypedArray()
)
}
}
}
|
mit
|
cc485957d369ca125f4ca6691cd156de
| 30.102564 | 74 | 0.640973 | 4.612167 | false | false | false | false |
grover-ws-1/http4k
|
http4k-core/src/test/kotlin/org/http4k/util/testClocks.kt
|
1
|
595
|
package org.http4k.util
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneId.systemDefault
object TickingClock : Clock() {
private var ticks = 0L
override fun withZone(zone: ZoneId?): Clock = this
override fun getZone(): ZoneId = systemDefault()
override fun instant(): Instant = Instant.ofEpochMilli(0).plusSeconds(ticks++)
}
object FixedClock : Clock() {
override fun withZone(zone: ZoneId?): Clock = this
override fun getZone(): ZoneId = systemDefault()
override fun instant(): Instant = Instant.ofEpochMilli(0)
}
|
apache-2.0
|
83f51a875bba545285e11bf1b0f8b349
| 23.833333 | 82 | 0.722689 | 4.103448 | false | false | false | false |
agoda-com/Kakao
|
sample/src/main/kotlin/com/agoda/sample/ViewPager2Activity.kt
|
1
|
1566
|
package com.agoda.sample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
class ViewPager2Activity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_pager2)
val pager = findViewById<ViewPager2>(R.id.pager)
val adapter = ScreenSlidePagerAdapter(this, (0..5).map { SimpleFragment(it) })
pager.offscreenPageLimit = 1
pager.adapter = adapter
}
private inner class ScreenSlidePagerAdapter(fragmentActivity: FragmentActivity, val pages: List<Fragment>)
: FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int = pages.size
override fun createFragment(position: Int): Fragment = pages[position]
}
}
class SimpleFragment(private val number: Int) : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.simple_fragment, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<TextView>(R.id.text).text = number.toString()
}
}
|
apache-2.0
|
76ef6693ab0c64a6ddec0593806a2511
| 33.043478 | 110 | 0.737548 | 4.77439 | false | false | false | false |
leafclick/intellij-community
|
java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt
|
1
|
11872
|
// 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.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.util.PsiUtil
import org.jetbrains.annotations.NonNls
/**
* Checks package accessibility according to JLS 7 "Packages and Modules".
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a>
* @see <a href="http://openjdk.java.net/jeps/261">JEP 261: Module System</a>
*/
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName(): String = "Java Platform Module System"
override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null
override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false)
private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
val index = ProjectFileIndex.getInstance(useFile.project)
if (useVFile == null || !index.isInLibrarySource(useVFile)) {
if (targetFile != null && targetFile.isPhysical) {
return checkAccess(targetFile, useFile, targetPackageName, quick)
}
else if (useVFile != null) {
val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName)
if (target != null) {
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
if (dirs.isEmpty()) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorBundle.message("package.not.found", target.qualifiedName))
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return when {
error == null -> null
dirs.size == 1 -> error
dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null
else -> error
}
}
}
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
val useModule = JavaModuleGraphUtil.findDescriptorByElement(place)
if (targetModule != null) {
if (targetModule == useModule) {
return null
}
val targetName = targetModule.name
val useName = useModule?.name ?: "ALL-UNNAMED"
val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) }
if (useModule == null) {
val origin = targetModule.containingFile?.virtualFile
if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) {
return null // a target is not on the mandatory module path
}
var isRoot = !targetName.startsWith("java.") || inAddedModules(module, targetName) || hasUpgrade(module, targetName, packageName, place)
if (!isRoot) {
val root = JavaPsiFacade.getInstance(place.project).findModule("java.se", module.moduleWithLibrariesScope)
isRoot = root == null || JavaModuleGraphUtil.reads(root, targetModule)
}
if (!isRoot) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorBundle.message("module.access.not.in.graph", packageName, targetName),
listOf(AddModulesOptionFix(module, targetName)))
}
}
if (!(targetModule is LightJavaModule ||
JavaModuleGraphUtil.exports(targetModule, packageName, useModule) ||
module != null && inAddedExports(module, targetName, packageName, useName))) {
if (quick) return ERR
val fixes = when {
packageName.isEmpty() -> emptyList()
targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName))
targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName))
else -> emptyList()
}
return when (useModule) {
null -> ErrorWithFixes(
JavaErrorBundle.message("module.access.from.unnamed", packageName, targetName), fixes)
else -> ErrorWithFixes(
JavaErrorBundle.message("module.access.from.named", packageName, targetName, useName), fixes)
}
}
if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return when {
quick -> ERR
PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes(
JavaErrorBundle.message("module.access.does.not.read", packageName, targetName, useName),
listOf(AddRequiresDirectiveFix(useModule, targetName)))
else -> ErrorWithFixes(
JavaErrorBundle.message("module.access.bad.name", packageName, targetName))
}
}
}
else if (useModule != null) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorBundle.message("module.access.to.unnamed", packageName, useModule.name))
}
return null
}
private fun hasUpgrade(module: Module, targetName: String, packageName: String, place: PsiFileSystemItem): Boolean {
if (PsiJavaModule.UPGRADEABLE.contains(targetName)) {
val target = JavaPsiFacade.getInstance(module.project).findPackage(packageName)
if (target != null) {
val useVFile = place.virtualFile
if (useVFile != null) {
val index = ModuleRootManager.getInstance(module).fileIndex
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
return dirs.asSequence().any { index.getOrderEntryForFile(it.virtualFile) !is JdkOrderEntry }
}
}
}
return false
}
private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
if (options.isEmpty()) return false
val prefix = "${targetName}/${packageName}="
return optionValues(options, "--add-exports")
.filter { it.startsWith(prefix) }
.map { it.substring(prefix.length) }
.flatMap { it.splitToSequence(",") }
.any { it == useName }
}
private fun inAddedModules(module: Module, moduleName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
return optionValues(options, "--add-modules")
.flatMap { it.splitToSequence(",") }
.any { it == moduleName || it == "ALL-SYSTEM" || it == "ALL-MODULE-PATH" }
}
private fun optionValues(options: List<String>, name: String) =
if (options.isEmpty()) emptySequence()
else {
var useValue = false
options.asSequence()
.map {
when {
it == name -> { useValue = true; "" }
useValue -> { useValue = false; it }
it.startsWith(name) && it[name.length] == '=' -> it.substring(name.length + 1)
else -> ""
}
}
.filterNot { it.isEmpty() }
}
private abstract class CompilerOptionFix(private val module: Module) : IntentionAction {
@NonNls override fun getFamilyName() = "dfd4a2c1-da18-4651-9aa8-d7d31cae10be" // random string; not visible
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (isAvailable(project, editor, file)) {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList()
update(options)
JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options)
PsiManager.getInstance(project).dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
}
protected abstract fun update(options: MutableList<String>)
override fun startInWriteAction() = true
}
private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) {
private val qualifier = "${targetName}/${packageName}"
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports ${qualifier}=${useName}")
override fun update(options: MutableList<String>) {
var idx = -1; var candidate = -1; var offset = 0
for ((i, option) in options.withIndex()) {
if (option.startsWith("--add-exports")) {
if (option.length == 13) { candidate = i + 1 ; offset = 0 }
else if (option[13] == '=') { candidate = i; offset = 14 }
}
if (i == candidate && option.startsWith(qualifier, offset)) {
val qualifierEnd = qualifier.length + offset
if (option.length == qualifierEnd || option[qualifierEnd] == '=') {
idx = i
}
}
}
when (idx) {
-1 -> options += listOf("--add-exports", "${qualifier}=${useName}")
else -> options[idx] = "${options[idx].trimEnd(',')},${useName}"
}
}
}
private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) {
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules ${moduleName}")
override fun update(options: MutableList<String>) {
var idx = -1
for ((i, option) in options.withIndex()) {
if (option.startsWith("--add-modules")) {
if (option.length == 13) idx = i + 1
else if (option[13] == '=') idx = i
}
}
when (idx) {
-1 -> options += listOf("--add-modules", moduleName)
options.size -> options += moduleName
else -> {
val value = options[idx]
options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}"
}
}
}
}
}
|
apache-2.0
|
a3bbf08ce223acdc7b02e1dec446b46e
| 43.973485 | 151 | 0.666526 | 4.694346 | false | false | false | false |
leafclick/intellij-community
|
platform/workspaceModel-core/test/testUtils.kt
|
1
|
3823
|
// 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.workspace.api
import org.jetbrains.annotations.TestOnly
import org.junit.Assert
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class TestEntityTypesResolver: EntityTypesResolver {
private val pluginPrefix = "PLUGIN___"
override fun getPluginId(clazz: Class<*>): String? = pluginPrefix + clazz.name
override fun resolveClass(name: String, pluginId: String?): Class<*> {
Assert.assertEquals(pluginPrefix + name, pluginId)
return javaClass.classLoader.loadClass(name)
}
}
fun verifySerializationRoundTrip(storage: TypedEntityStorage): ByteArray {
storage as ProxyBasedEntityStorage
fun assertEntityDataEquals(expected: EntityData, actual: EntityData) {
Assert.assertEquals(expected.id, actual.id)
Assert.assertEquals(expected.unmodifiableEntityType, actual.unmodifiableEntityType)
Assert.assertEquals(expected.properties, actual.properties)
Assert.assertEquals(expected.entitySource, actual.entitySource)
}
fun assertEntityDataSetEquals(expected: Set<EntityData>, actual: Set<EntityData>) {
Assert.assertEquals(expected.size, actual.size)
val sortedExpected = expected.sortedBy { it.id }
val sortedActual = actual.sortedBy { it.id }
for ((expectedData, actualData) in sortedExpected.zip(sortedActual)) {
assertEntityDataEquals(expectedData, actualData)
}
}
fun assertStorageEquals(expected: ProxyBasedEntityStorage, actual: ProxyBasedEntityStorage) {
Assert.assertEquals(expected.referrers.keys, actual.referrers.keys)
for (key in expected.referrers.keys) {
Assert.assertEquals(expected.referrers.getValue(key).toSet(), actual.referrers.getValue(key).toSet())
}
Assert.assertEquals(expected.entityById.keys, actual.entityById.keys)
for (id in expected.entityById.keys) {
assertEntityDataEquals(expected.entityById.getValue(id), actual.entityById.getValue(id))
}
Assert.assertEquals(expected.entitiesBySource.keys, actual.entitiesBySource.keys)
for (source in expected.entitiesBySource.keys) {
assertEntityDataSetEquals(expected.entitiesBySource.getValue(source), actual.entitiesBySource.getValue(source))
}
Assert.assertEquals(expected.entitiesByType.keys, actual.entitiesByType.keys)
for (type in expected.entitiesByType.keys) {
assertEntityDataSetEquals(expected.entitiesByType.getValue(type), actual.entitiesByType.getValue(type))
}
Assert.assertEquals(expected.entitiesByPersistentIdHash.keys, actual.entitiesByPersistentIdHash.keys)
for (idHash in expected.entitiesByPersistentIdHash.keys) {
assertEntityDataSetEquals(expected.entitiesByPersistentIdHash.getValue(idHash), actual.entitiesByPersistentIdHash.getValue(idHash))
}
}
val serializer = KryoEntityStorageSerializer(
TestEntityTypesResolver())
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, storage)
val byteArray = stream.toByteArray()
val deserialized = serializer.deserializeCache(ByteArrayInputStream(byteArray)) as ProxyBasedEntityStorage
assertStorageEquals(storage, deserialized)
return byteArray
}
@TestOnly
fun TypedEntityStorage.toGraphViz(): String {
this as ProxyBasedEntityStorage
val sb = StringBuilder()
sb.appendln("digraph G {")
val visited = mutableSetOf<Long>()
for ((id, refs) in referrers) {
visited.add(id)
for (ref in refs) {
visited.add(ref)
sb.appendln(""" "${entityById.getValue(ref)}" -> "${entityById.getValue(id)}";""")
}
}
for ((id, data) in entityById) {
if (!visited.contains(id)) {
sb.appendln(""" "$data";""")
}
}
sb.appendln("}")
return sb.toString()
}
|
apache-2.0
|
eca94536d972b53f7c1934b06b884732
| 35.066038 | 140 | 0.756474 | 4.567503 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/synchronized/sync.kt
|
2
|
866
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
// FULL_JDK
import java.util.concurrent.*
import java.util.concurrent.atomic.*
fun thread(block: ()->Unit ) {
val thread = object: Thread() {
override fun run() {
block()
}
}
thread.start()
}
fun box() : String {
val mtref = AtomicInteger()
val cdl = CountDownLatch(11)
for(i in 0..10) {
thread {
var current = 0
do {
current = synchronized(mtref) {
val v = mtref.get() + 1
if(v < 100)
mtref.set(v+1)
v
}
}
while(current < 100)
cdl.countDown()
}
}
cdl.await()
return if(mtref.get() == 100) "OK" else mtref.get().toString()
}
|
apache-2.0
|
269eb921e8f4b709df8e5a4531886c04
| 21.205128 | 72 | 0.497691 | 3.798246 | false | false | false | false |
Nunnery/MythicDrops
|
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/language/command/MythicGiveUnidentifiedMessages.kt
|
1
|
2270
|
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.settings.language.command
import com.squareup.moshi.JsonClass
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command.GiveUnidentifiedMessages
import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString
import org.bukkit.configuration.ConfigurationSection
@JsonClass(generateAdapter = true)
data class MythicGiveUnidentifiedMessages internal constructor(
override val receiverSuccess: String = "",
override val receiverFailure: String = "",
override val senderSuccess: String = "",
override val senderFailure: String = ""
) : GiveUnidentifiedMessages {
companion object {
fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicGiveUnidentifiedMessages(
configurationSection.getNonNullString("receiver-success"),
configurationSection.getNonNullString("receiver-failure"),
configurationSection.getNonNullString("sender-success"),
configurationSection.getNonNullString("sender-failure")
)
}
}
|
mit
|
4d072a0fce0f88f8b5e5d627704749b8
| 50.590909 | 114 | 0.770925 | 5.033259 | false | true | false | false |
thanksmister/androidthings-mqtt-alarm-panel
|
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/utils/SoundUtils.kt
|
1
|
2840
|
package com.thanksmister.iot.mqtt.alarmpanel.utils
import android.content.Context
import android.content.ContextWrapper
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Handler
import android.os.HandlerThread
import com.thanksmister.iot.mqtt.alarmpanel.R
import timber.log.Timber
import java.lang.IllegalStateException
import android.media.AudioDeviceInfo
import android.media.AudioTrack
import java.io.IOException
class SoundUtils(base: Context) : ContextWrapper(base) {
private var speaker: MediaPlayer? = null
private var playing: Boolean = false
private var repeating: Boolean = false
private val soundThread: HandlerThread = HandlerThread("buttonSound");
private var soundHandler: Handler? = null
private var audioOutputDevice: AudioDeviceInfo? = null
private var audioTrack: AudioTrack? = null
fun init(){
Timber.d("init")
soundThread.start();
soundHandler = Handler(soundThread.looper);
val am = getSystemService(Context.AUDIO_SERVICE) as AudioManager
am.setStreamVolume(AudioManager.STREAM_ALARM, am.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0)
}
fun destroyBuzzer() {
Timber.d("destroyBuzzer")
soundHandler?.post(Runnable { soundHandler?.removeCallbacks(repeatAudioRunnable) })
soundHandler?.post(Runnable { soundHandler?.removeCallbacks(streamAudioRunnable) })
stopBuzzerRepeat()
}
fun playBuzzerOnButtonPress() {
Timber.d("playBuzzerOnButtonPress")
if (repeating) {
stopBuzzerRepeat()
}
soundHandler?.post(streamAudioRunnable);
}
private val streamAudioRunnable = Runnable {
val speaker = MediaPlayer.create(applicationContext, R.raw.beep7)
speaker.setOnCompletionListener { mp ->
mp.stop()
mp.release()
playing = false
}
speaker.start()
playing = true
}
private val repeatAudioRunnable = Runnable {
Timber.d("repeatAudioRunnable")
if(repeating) {
speaker = MediaPlayer.create(applicationContext, R.raw.beep7_loop)
speaker?.isLooping = true
speaker?.start()
}
}
private fun stopBuzzerRepeat() {
Timber.d("stopBuzzerRepeat")
repeating = false
soundHandler?.removeCallbacks(repeatAudioRunnable);
try {
if(speaker != null) {
speaker?.isLooping = true
speaker?.stop()
speaker?.release()
}
} catch (e: IllegalStateException) {
Timber.e(e.message)
}
speaker = null
}
fun playBuzzerRepeat() {
Timber.d("playBuzzerRepeat")
repeating = true
soundHandler?.post(repeatAudioRunnable);
}
}
|
apache-2.0
|
93ec18433addfa27aed3104db44e0161
| 29.880435 | 106 | 0.65669 | 4.863014 | false | false | false | false |
smmribeiro/intellij-community
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/SdkDataService.kt
|
4
|
4135
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ModuleSdkData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.model.project.ProjectSdkData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.util.DisposeAwareProjectChange
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.roots.ProjectRootManager
class ProjectSdkDataService : AbstractProjectDataService<ProjectSdkData, Project?>() {
override fun getTargetDataKey() = ProjectSdkData.KEY
override fun importData(
toImport: Collection<DataNode<ProjectSdkData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
if (toImport.isEmpty() || projectData == null) return
require(toImport.size == 1) { String.format("Expected to get a single project but got %d: %s", toImport.size, toImport) }
if (!ExternalSystemApiUtil.isOneToOneMapping(project, projectData, modelsProvider.modules)) return
for (sdkDataNode in toImport) {
ExternalSystemApiUtil.executeProjectChangeAction(object : DisposeAwareProjectChange(project) {
override fun execute() {
importProjectSdk(project, sdkDataNode.data)
}
})
}
}
private fun importProjectSdk(project: Project, sdkData: ProjectSdkData) {
val sdkName = sdkData.sdkName ?: return
val projectJdkTable = ProjectJdkTable.getInstance()
val sdk = projectJdkTable.findJdk(sdkName)
val projectRootManager = ProjectRootManager.getInstance(project)
val projectSdk = projectRootManager.projectSdk
if (projectSdk == null) {
projectRootManager.projectSdk = sdk
}
}
}
class ModuleSdkDataService : AbstractProjectDataService<ModuleSdkData, Project?>() {
override fun getTargetDataKey() = ModuleSdkData.KEY
override fun importData(
toImport: Collection<DataNode<ModuleSdkData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
if (toImport.isEmpty() || projectData == null) return
val useDefaultsIfCan = ExternalSystemApiUtil.isOneToOneMapping(project, projectData, modelsProvider.modules)
for (sdkDataNode in toImport) {
val moduleNode = sdkDataNode.getParent(ModuleData::class.java) ?: continue
val module = moduleNode.getUserData(AbstractModuleDataService.MODULE_KEY) ?: continue
importModuleSdk(module, sdkDataNode.data, modelsProvider, useDefaultsIfCan)
}
}
private fun importModuleSdk(
module: Module,
sdkData: ModuleSdkData,
modelsProvider: IdeModifiableModelsProvider,
useDefaultsIfCan: Boolean
) {
val moduleSdkName = sdkData.sdkName
val projectJdkTable = ProjectJdkTable.getInstance()
val sdk = moduleSdkName?.let { projectJdkTable.findJdk(moduleSdkName) }
val modifiableRootModel = modelsProvider.getModifiableRootModel(module)
if (modifiableRootModel.sdk != null) return
val projectRootManager = ProjectRootManager.getInstance(module.project)
val projectSdk = projectRootManager.projectSdk
when {
useDefaultsIfCan && sdk == projectSdk -> modifiableRootModel.inheritSdk()
moduleSdkName == null && sdk == null -> modifiableRootModel.inheritSdk()
sdk == null -> modifiableRootModel.setInvalidSdk(moduleSdkName, ExternalSystemBundle.message("unknown.sdk.type"))
else -> modifiableRootModel.sdk = sdk
}
}
}
|
apache-2.0
|
2a544013d74e6761b1b203259ba2f77b
| 43.956522 | 140 | 0.775333 | 5.030414 | false | false | false | false |
smmribeiro/intellij-community
|
platform/statistics/src/com/intellij/internal/statistic/eventLog/events/BaseEventFields.kt
|
1
|
10492
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.eventLog.events
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.utils.StatisticsUtil
import com.intellij.internal.statistic.utils.getPluginInfo
import org.jetbrains.annotations.NonNls
import kotlin.reflect.KProperty
sealed class EventField<T> {
abstract val name: String
abstract fun addData(fuData: FeatureUsageData, value: T)
infix fun with(data: T): EventPair<T> = EventPair(this, data)
}
abstract class PrimitiveEventField<T> : EventField<T>() {
abstract val validationRule: List<String>
}
abstract class ListEventField<T> : EventField<List<T>>() {
abstract val validationRule: List<String>
}
data class EventPair<T>(val field: EventField<T>, val data: T) {
fun addData(featureUsageData: FeatureUsageData) = field.addData(featureUsageData, data)
}
abstract class StringEventField(override val name: String) : PrimitiveEventField<String?>() {
override fun addData(fuData: FeatureUsageData, value: String?) {
if (value != null) {
fuData.addData(name, value)
}
}
data class ValidatedByAllowedValues(@NonNls override val name: String,
val allowedValues: List<String>) : StringEventField(name) {
override val validationRule: List<String>
get() = listOf("{enum:${allowedValues.joinToString("|")}}")
}
data class ValidatedByEnum(@NonNls override val name: String, @NonNls val enumRef: String) : StringEventField(name) {
override val validationRule: List<String>
get() = listOf("{enum#$enumRef}")
}
data class ValidatedByCustomRule(@NonNls override val name: String,
@NonNls val customRuleId: String) : StringEventField(name) {
override val validationRule: List<String>
get() = listOf("{util#$customRuleId}")
}
data class ValidatedByRegexp(@NonNls override val name: String, @NonNls val regexpRef: String) : StringEventField(name) {
override val validationRule: List<String>
get() = listOf("{regexp#$regexpRef}")
}
data class ValidatedByInlineRegexp(@NonNls override val name: String, @NonNls val regexp: String) : StringEventField(name) {
override val validationRule: List<String>
get() = listOf("{regexp:$regexp}")
}
}
data class IntEventField(override val name: String) : PrimitiveEventField<Int>() {
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
override fun addData(fuData: FeatureUsageData, value: Int) {
fuData.addData(name, value)
}
}
data class RegexpIntEventField(override val name: String, @NonNls val regexp: String) : PrimitiveEventField<Int>() {
override val validationRule: List<String>
get() = listOf("{regexp:$regexp}")
override fun addData(fuData: FeatureUsageData, value: Int) {
fuData.addData(name, value)
}
}
data class RoundedIntEventField(override val name: String) : PrimitiveEventField<Int>() {
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
override fun addData(fuData: FeatureUsageData, value: Int) {
fuData.addData(name, StatisticsUtil.roundToPowerOfTwo(value))
}
}
data class LongEventField(override val name: String): PrimitiveEventField<Long>() {
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
override fun addData(fuData: FeatureUsageData, value: Long) {
fuData.addData(name, value)
}
}
data class RoundedLongEventField(override val name: String): PrimitiveEventField<Long>() {
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
override fun addData(fuData: FeatureUsageData, value: Long) {
fuData.addData(name, StatisticsUtil.roundToPowerOfTwo(value))
}
}
data class FloatEventField(override val name: String): PrimitiveEventField<Float>() {
override val validationRule: List<String>
get() = listOf("{regexp#float}")
override fun addData(fuData: FeatureUsageData, value: Float) {
fuData.addData(name, value)
}
}
data class DoubleEventField(override val name: String): PrimitiveEventField<Double>() {
override val validationRule: List<String>
get() = listOf("{regexp#float}")
override fun addData(fuData: FeatureUsageData, value: Double) {
fuData.addData(name, value)
}
}
data class BooleanEventField(override val name: String): PrimitiveEventField<Boolean>() {
override val validationRule: List<String>
get() = listOf("{enum#boolean}")
override fun addData(fuData: FeatureUsageData, value: Boolean) {
fuData.addData(name, value)
}
}
data class AnonymizedEventField(override val name: String): PrimitiveEventField<String?>() {
override val validationRule: List<String>
get() = listOf("{regexp#hash}")
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addAnonymizedValue(name, value)
}
}
data class EnumEventField<T : Enum<*>>(override val name: String,
private val enumClass: Class<T>,
private val transform: (T) -> String): PrimitiveEventField<T>() {
override fun addData(fuData: FeatureUsageData, value: T) {
fuData.addData(name, transform(value))
}
override val validationRule: List<String>
get() = listOf("{enum:${enumClass.enumConstants.joinToString("|", transform = transform)}}")
}
data class LongListEventField(override val name: String): ListEventField<Long>() {
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
override fun addData(fuData: FeatureUsageData, value: List<Long>) {
fuData.addListLongData(name, value)
}
}
abstract class StringListEventField(override val name: String) : ListEventField<String>() {
override fun addData(fuData: FeatureUsageData, value: List<String>) {
fuData.addData(name, value)
}
data class ValidatedByAllowedValues(@NonNls override val name: String,
val allowedValues: List<String>) : StringListEventField(name) {
override val validationRule: List<String>
get() = listOf("{enum:${allowedValues.joinToString("|")}}")
}
data class ValidatedByEnum(@NonNls override val name: String, @NonNls val enumRef: String) : StringListEventField(name) {
override val validationRule: List<String>
get() = listOf("{enum#$enumRef}")
}
data class ValidatedByCustomRule(@NonNls override val name: String,
@NonNls val customRuleId: String) : StringListEventField(name) {
override val validationRule: List<String>
get() = listOf("{util#$customRuleId}")
}
data class ValidatedByRegexp(@NonNls override val name: String, @NonNls val regexpRef: String) : StringListEventField(name) {
override val validationRule: List<String>
get() = listOf("{regexp#$regexpRef}")
}
data class ValidatedByInlineRegexp(@NonNls override val name: String, @NonNls val regexp: String) : StringListEventField(name) {
override val validationRule: List<String>
get() = listOf("{regexp:$regexp}")
}
}
data class ClassEventField(override val name: String) : PrimitiveEventField<Class<*>>() {
override fun addData(fuData: FeatureUsageData, value: Class<*>) {
val pluginInfo = getPluginInfo(value)
fuData.addData(name, if (pluginInfo.isSafeToReport()) value.name else "third.party")
}
override val validationRule: List<String>
get() = listOf("{util#class_name}")
}
class ObjectEventField(override val name: String, vararg val fields: EventField<*>) : EventField<ObjectEventData>() {
constructor(name: String, description: ObjectDescription) : this(name, *description.getFields())
override fun addData(fuData: FeatureUsageData, value: ObjectEventData) {
fuData.addObjectData(name, value.buildObjectData(fields))
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ObjectEventField
if (name != other.name) return false
if (!fields.contentEquals(other.fields)) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + fields.contentHashCode()
return result
}
}
abstract class ObjectDescription {
private val eventDelegates = ArrayList<EventFieldDelegate<*>>()
fun <T> field(eventField: EventField<T>): EventFieldDelegate<T> {
val delegate = EventFieldDelegate(eventField)
eventDelegates.add(delegate)
return delegate
}
fun getPairs(): Array<EventPair<*>> {
return eventDelegates.mapNotNull { it.getPair() }.toTypedArray()
}
fun getFields(): Array<EventField<*>> {
return eventDelegates.map { it.eventField }.toTypedArray()
}
companion object {
inline fun <O : ObjectDescription> build(creator: () -> O, filler: O.() -> Unit): ObjectEventData {
val obj = creator()
filler(obj)
return ObjectEventData(*obj.getPairs())
}
}
}
class ObjectEventData(private val values: List<EventPair<*>>) {
constructor(vararg values: EventPair<*>) : this(listOf(*values))
fun buildObjectData(allowedFields: Array<out EventField<*>>): Map<String, Any> {
val data = FeatureUsageData()
for (eventPair in values) {
val eventField = eventPair.field
if (eventField !in allowedFields) throw IllegalArgumentException("Field ${eventField.name} is not in allowed object fields")
eventPair.addData(data)
}
return data.build()
}
}
class EventFieldDelegate<T>(val eventField: EventField<T>) {
private var fieldValue: T? = null
operator fun getValue(thisRef: ObjectDescription, property: KProperty<*>): T? = fieldValue
operator fun setValue(thisRef: ObjectDescription, property: KProperty<*>, value: T?) {
fieldValue = value
}
fun getPair(): EventPair<T>? {
val v = fieldValue
if (v != null) {
return EventPair(eventField, v)
}
else {
return null
}
}
}
class ObjectListEventField(override val name: String, vararg val fields: EventField<*>) : EventField<List<ObjectEventData>>() {
constructor(name: String, description: ObjectDescription) : this(name, *description.getFields())
override fun addData(fuData: FeatureUsageData, value: List<ObjectEventData>) {
fuData.addListObjectData(name, value.map { it.buildObjectData(fields) })
}
}
|
apache-2.0
|
8b057d2e792dbb091148ea640bda3215
| 33.627063 | 130 | 0.704251 | 4.47802 | false | false | false | false |
jotomo/AndroidAPS
|
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_User_Option.kt
|
1
|
2577
|
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import javax.inject.Inject
class DanaRS_Packet_Option_Set_User_Option(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
@Inject lateinit var danaPump: DanaPump
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION
aapsLogger.debug(LTag.PUMPCOMM, "Setting user settings")
}
override fun getRequestParams(): ByteArray {
aapsLogger.debug(LTag.PUMPCOMM,
"UserOptions:" + (System.currentTimeMillis() - danaPump.lastConnection) / 1000 + " s ago"
+ "\ntimeDisplayType24:" + danaPump.timeDisplayType24
+ "\nbuttonScroll:" + danaPump.buttonScrollOnOff
+ "\nbeepAndAlarm:" + danaPump.beepAndAlarm
+ "\nlcdOnTimeSec:" + danaPump.lcdOnTimeSec
+ "\nbacklight:" + danaPump.backlightOnTimeSec
+ "\ndanaRPumpUnits:" + danaPump.units
+ "\nlowReservoir:" + danaPump.lowReservoirRate)
val request = ByteArray(13)
request[0] = if (danaPump.timeDisplayType24) 0.toByte() else 1.toByte()
request[1] = if (danaPump.buttonScrollOnOff) 1.toByte() else 0.toByte()
request[2] = (danaPump.beepAndAlarm and 0xff).toByte()
request[3] = (danaPump.lcdOnTimeSec and 0xff).toByte()
request[4] = (danaPump.backlightOnTimeSec and 0xff).toByte()
request[5] = (danaPump.selectedLanguage and 0xff).toByte()
request[6] = (danaPump.units and 0xff).toByte()
request[7] = (danaPump.shutdownHour and 0xff).toByte()
request[8] = (danaPump.lowReservoirRate and 0xff).toByte()
request[9] = (danaPump.cannulaVolume and 0xff).toByte()
request[10] = (danaPump.cannulaVolume ushr 8 and 0xff).toByte()
request[11] = (danaPump.refillAmount and 0xff).toByte()
request[12] = (danaPump.refillAmount ushr 8 and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "OPTION__SET_USER_OPTION"
}
}
|
agpl-3.0
|
01d60c9b425ba2a59d530a31148ae0ad
| 41.262295 | 101 | 0.648816 | 4.360406 | false | false | false | false |
charlesng/SampleAppArch
|
app/src/main/java/com/cn29/aac/di/ui/UiBuilder.kt
|
1
|
3749
|
package com.cn29.aac.di.ui
import com.cn29.aac.ui.feedentry.FeedActivity
import com.cn29.aac.ui.feedentry.FeedActivityModule
import com.cn29.aac.ui.feedentry.FeedEntryFragment
import com.cn29.aac.ui.feedentry.FeedEntryFragmentModule
import com.cn29.aac.ui.feedentrydetail.FeedEntryDetailActivity
import com.cn29.aac.ui.feedentrydetail.FeedEntryDetailActivityModule
import com.cn29.aac.ui.location.LocationActivity
import com.cn29.aac.ui.location.LocationActivityModule
import com.cn29.aac.ui.location.LocationFragment
import com.cn29.aac.ui.location.LocationFragmentModule
import com.cn29.aac.ui.login.LoginActivity
import com.cn29.aac.ui.login.LoginActivityModule
import com.cn29.aac.ui.main.AppArchNavigationDrawer
import com.cn29.aac.ui.main.AppArchNavigationDrawerModule
import com.cn29.aac.ui.masterdetail.*
import com.cn29.aac.ui.shopping.*
import com.cn29.aac.ui.shoppingkart.ShoppingKartActivity
import com.cn29.aac.ui.shoppingkart.ShoppingKartActivityModule
import com.cn29.aac.ui.viewpager.*
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* Created by Charles Ng on 27/9/2017.
*/
@Module
abstract class UiBuilder {
//Login
@ContributesAndroidInjector(modules = [LoginActivityModule::class])
abstract fun bindLoginActivity(): LoginActivity?
//Main Activity
@ContributesAndroidInjector(modules = [AppArchNavigationDrawerModule::class])
abstract fun bindDrawer(): AppArchNavigationDrawer?
//feed entry
@ContributesAndroidInjector(modules = [FeedActivityModule::class])
abstract fun bindFeedActivity(): FeedActivity?
@ContributesAndroidInjector(modules = [FeedEntryDetailActivityModule::class])
abstract fun bindFeedEntryDetailActivity(): FeedEntryDetailActivity?
@ContributesAndroidInjector(modules = [FeedEntryFragmentModule::class])
abstract fun bindFeedEntryFragment(): FeedEntryFragment?
//location
@ContributesAndroidInjector(modules = [LocationActivityModule::class])
abstract fun bindLocationActivity(): LocationActivity?
@ContributesAndroidInjector(modules = [LocationFragmentModule::class])
abstract fun bindLocationFragment(): LocationFragment?
//view pager
@ContributesAndroidInjector(modules = [PagerActivityModule::class])
abstract fun bindPagerActivity(): PagerActivity?
@ContributesAndroidInjector(modules = [BlankFragmentAModule::class])
abstract fun bindBlankFragmentA(): BlankFragmentA?
@ContributesAndroidInjector(modules = [BlankFragmentBModule::class])
abstract fun bindBlankFragmentB(): BlankFragmentB?
//master detail
@ContributesAndroidInjector(modules = [SimpleListActivityModule::class])
abstract fun bindSimpleListActivity(): SimpleListActivity?
@ContributesAndroidInjector(modules = [SimpleDetailActivityModule::class])
abstract fun bindSimpleDetailActivity(): SimpleDetailActivity?
@ContributesAndroidInjector(modules = [SimpleDetailFragmentModule::class])
abstract fun bindSimpleDetailFragment(): SimpleDetailFragment?
// Shopping
@ContributesAndroidInjector(modules = [ShoppingActivityModule::class])
abstract fun bindShoppingActivity(): ShoppingActivity?
@ContributesAndroidInjector(modules = [ArtistDetailActivityModule::class])
abstract fun bindArtistDetailActivity(): ArtistDetailActivity?
@ContributesAndroidInjector(modules = [AlbumFragmentModule::class])
abstract fun bindAlbumFragment(): AlbumFragment?
@ContributesAndroidInjector(modules = [ArtistFragmentModule::class])
abstract fun bindArtistFragment(): ArtistFragment?
// Shopping Kart
@ContributesAndroidInjector(modules = [ShoppingKartActivityModule::class])
abstract fun bindShoppingKartActivity(): ShoppingKartActivity?
}
|
apache-2.0
|
aeecd07aad396b0eea0d450e4d8071bd
| 40.208791 | 81 | 0.80128 | 4.932895 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/AbstractUselessCallInspection.kt
|
1
|
2472
|
// 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.collections
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
abstract open class AbstractUselessCallInspection : AbstractKotlinInspection() {
protected abstract val uselessFqNames: Map<String, Conversion>
protected abstract val uselessNames: Set<String>
protected abstract fun QualifiedExpressionVisitor.suggestConversionIfNeeded(
expression: KtQualifiedExpression,
calleeExpression: KtExpression,
context: BindingContext,
conversion: Conversion
)
inner class QualifiedExpressionVisitor internal constructor(val holder: ProblemsHolder, val isOnTheFly: Boolean) : KtVisitorVoid() {
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
super.visitQualifiedExpression(expression)
val selector = expression.selectorExpression as? KtCallExpression ?: return
val calleeExpression = selector.calleeExpression ?: return
if (calleeExpression.text !in uselessNames) return
val context = expression.analyze()
val resolvedCall = expression.getResolvedCall(context) ?: return
val conversion = uselessFqNames[resolvedCall.resultingDescriptor.fqNameOrNull()?.asString()] ?: return
suggestConversionIfNeeded(expression, calleeExpression, context, conversion)
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = QualifiedExpressionVisitor(holder, isOnTheFly)
protected data class Conversion(val replacementName: String? = null)
protected companion object {
val deleteConversion = Conversion()
fun Set<String>.toShortNames() = mapTo(mutableSetOf()) { fqName -> fqName.takeLastWhile { it != '.' } }
}
}
|
apache-2.0
|
029e09864dcb7bbafd8ecb500f461f71
| 44.796296 | 158 | 0.766181 | 5.456954 | false | false | false | false |
siosio/intellij-community
|
plugins/devkit/devkit-core/src/inspections/NonDefaultConstructorInspection.kt
|
1
|
12923
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiParameterList
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.xml.XmlTag
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.xml.DomManager
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.dom.Extension
import org.jetbrains.idea.devkit.dom.ExtensionPoint
import org.jetbrains.idea.devkit.dom.ExtensionPoint.Area
import org.jetbrains.idea.devkit.util.locateExtensionsByPsiClass
import org.jetbrains.idea.devkit.util.processExtensionDeclarations
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.convertOpt
import java.util.*
import kotlin.collections.HashSet
private const val serviceBeanFqn = "com.intellij.openapi.components.ServiceDescriptor"
class NonDefaultConstructorInspection : DevKitUastInspectionBase(UClass::class.java) {
override fun checkClass(aClass: UClass, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
val javaPsi = aClass.javaPsi
// Groovy from test data - ignore it
if (javaPsi.language.id == "Groovy" || javaPsi.classKind != JvmClassKind.CLASS ||
PsiUtil.isInnerClass(javaPsi) || PsiUtil.isLocalOrAnonymousClass(javaPsi) || PsiUtil.isAbstractClass(javaPsi) ||
javaPsi.hasModifierProperty(PsiModifier.PRIVATE) /* ignore private classes */) {
return null
}
val constructors = javaPsi.constructors
// very fast path - do nothing if no constructors
if (constructors.isEmpty()) {
return null
}
val area: Area?
val isService: Boolean
var serviceClientKind: ServiceDescriptor.ClientKind? = null
// hack, allow Project-level @Service
var isServiceAnnotation = false
var extensionPoint: ExtensionPoint? = null
if (javaPsi.hasAnnotation("com.intellij.openapi.components.Service")) {
area = null
isService = true
isServiceAnnotation = true
}
else {
// fast path - check by qualified name
if (!isExtensionBean(aClass)) {
// slow path - check using index
extensionPoint = findExtensionPoint(aClass, manager.project) ?: return null
}
else if (javaPsi.name == "VcsConfigurableEP") {
// VcsConfigurableEP extends ConfigurableEP but used directly, for now just ignore it as hardcoded exclusion
return null
}
area = getArea(extensionPoint)
isService = extensionPoint?.beanClass?.stringValue == serviceBeanFqn
if (isService) {
val extension = ContainerUtil.getOnlyItem(locateExtensionsByPsiClass(javaPsi))?.pointer?.element
val extensionTag = DomManager.getDomManager(manager.project).getDomElement(extension) as? Extension
serviceClientKind = when (extensionTag?.xmlTag?.getAttribute("client")?.value?.toLowerCase(Locale.US)) {
"all" -> ServiceDescriptor.ClientKind.ALL
"guest" -> ServiceDescriptor.ClientKind.GUEST
"local" -> ServiceDescriptor.ClientKind.LOCAL
else -> null
}
}
}
val isAppLevelExtensionPoint = area == null || area == Area.IDEA_APPLICATION
var errors: MutableList<ProblemDescriptor>? = null
loop@ for (method in constructors) {
if (isAllowedParameters(method.parameterList, extensionPoint, isAppLevelExtensionPoint, serviceClientKind, isServiceAnnotation)) {
// allow to have empty constructor and extra (e.g. DartQuickAssistIntention)
return null
}
if (errors == null) {
errors = SmartList()
}
// kotlin is not physical, but here only physical is expected, so, convert to uast element and use sourcePsi
val anchorElement = when {
method.isPhysical -> method.identifyingElement!!
else -> aClass.sourcePsi?.let { UastFacade.findPlugin(it)?.convertOpt<UMethod>(method, aClass)?.sourcePsi } ?: continue@loop
}
@NlsSafe val kind = if (isService) DevKitBundle.message("inspections.non.default.warning.type.service") else DevKitBundle.message("inspections.non.default.warning.type.extension")
@Nls val suffix =
if (area == null) DevKitBundle.message("inspections.non.default.warning.suffix.project.or.module")
else {
when {
isAppLevelExtensionPoint -> ""
area == Area.IDEA_PROJECT -> DevKitBundle.message("inspections.non.default.warning.suffix.project")
else -> DevKitBundle.message("inspections.non.default.warning.suffix.module")
}
}
errors.add(manager.createProblemDescriptor(anchorElement,
DevKitBundle.message("inspections.non.default.warning.and.suffix.message", kind, suffix),
true,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly))
}
return errors?.toTypedArray()
}
@Suppress("HardCodedStringLiteral")
private fun getArea(extensionPoint: ExtensionPoint?): Area {
val areaName = (extensionPoint ?: return Area.IDEA_APPLICATION).area.stringValue
when (areaName) {
"IDEA_PROJECT" -> return Area.IDEA_PROJECT
"IDEA_MODULE" -> return Area.IDEA_MODULE
else -> {
when (extensionPoint.name.value) {
"projectService" -> return Area.IDEA_PROJECT
"moduleService" -> return Area.IDEA_MODULE
}
}
}
return Area.IDEA_APPLICATION
}
}
private fun findExtensionPoint(clazz: UClass, project: Project): ExtensionPoint? {
val parentClass = clazz.uastParent as? UClass
if (parentClass == null) {
val qualifiedName = clazz.qualifiedName ?: return null
return findExtensionPointByImplementationClass(qualifiedName, qualifiedName, project)
}
else {
val parentQualifiedName = parentClass.qualifiedName ?: return null
// parent$inner string cannot be found, so, search by parent FQN
return findExtensionPointByImplementationClass(parentQualifiedName, "$parentQualifiedName$${clazz.javaPsi.name}", project)
}
}
private fun findExtensionPointByImplementationClass(searchString: String, qualifiedName: String, project: Project): ExtensionPoint? {
var result: ExtensionPoint? = null
val strictMatch = searchString === qualifiedName
processExtensionDeclarations(searchString, project, strictMatch = strictMatch) { extension, tag ->
val point = extension.extensionPoint ?: return@processExtensionDeclarations true
if (point.name.value == "psi.symbolReferenceProvider") {
return@processExtensionDeclarations true
}
when (point.beanClass.stringValue) {
null -> {
if (tag.attributes.any { it.name == Extension.IMPLEMENTATION_ATTRIBUTE && it.value == qualifiedName }) {
result = point
return@processExtensionDeclarations false
}
}
serviceBeanFqn -> {
if (tag.attributes.any { it.name == "serviceImplementation" && it.value == qualifiedName }) {
result = point
return@processExtensionDeclarations false
}
}
else -> {
// bean EP
if (tag.name == "className" || tag.subTags.any {
it.name == "className" && (strictMatch || it.textMatches(qualifiedName))
} || checkAttributes(tag, qualifiedName)) {
result = point
return@processExtensionDeclarations false
}
}
}
true
}
return result
}
// todo can we use attribute `with`?
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val ignoredTagNames = java.util.Set.of("semContributor", "modelFacade", "scriptGenerator",
"editorActionHandler", "editorTypedHandler",
"dataImporter", "java.error.fix", "explainPlanProvider", "typeIcon")
// problem - tag
//<lang.elementManipulator forClass="com.intellij.psi.css.impl.CssTokenImpl"
// implementationClass="com.intellij.psi.css.impl.CssTokenImpl$Manipulator"/>
// will be found for `com.intellij.psi.css.impl.CssTokenImpl`, but we need to ignore `forClass` and check that we have exact match for implementation attribute
private fun checkAttributes(tag: XmlTag, qualifiedName: String): Boolean {
if (ignoredTagNames.contains(tag.name)) {
// DbmsExtension passes Dbms instance directly, doesn't need to check
return false
}
return tag.attributes.any {
val name = it.name
(name.startsWith(Extension.IMPLEMENTATION_ATTRIBUTE) || name == "instance") && it.value == qualifiedName
}
}
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val allowedClientSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientSession",
"com.jetbrains.rdserver.core.GuestSession",
)
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val allowedClientAppSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientAppSession",
"com.jetbrains.rdserver.core.GuestAppSession",
) + allowedClientSessionsQualifiedNames
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val allowedClientProjectSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientProjectSession",
"com.jetbrains.rdserver.core.GuestProjectSession",
) + allowedClientSessionsQualifiedNames
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val allowedServiceQualifiedNames = setOf(
"com.intellij.openapi.project.Project",
"com.intellij.openapi.module.Module",
"com.intellij.util.messages.MessageBus",
"com.intellij.openapi.options.SchemeManagerFactory",
"com.intellij.openapi.editor.actionSystem.TypedActionHandler",
"com.intellij.database.Dbms"
) + allowedClientAppSessionsQualifiedNames + allowedClientProjectSessionsQualifiedNames
private val allowedServiceNames = allowedServiceQualifiedNames.mapTo(HashSet(allowedServiceQualifiedNames.size)) { it.substringAfterLast('.') }
@Suppress("HardCodedStringLiteral")
private fun isAllowedParameters(list: PsiParameterList,
extensionPoint: ExtensionPoint?,
isAppLevelExtensionPoint: Boolean,
clientKind: ServiceDescriptor.ClientKind?,
isServiceAnnotation: Boolean): Boolean {
if (list.isEmpty) {
return true
}
// hardcoded for now, later will be generalized
if (!isServiceAnnotation && extensionPoint?.effectiveQualifiedName == "com.intellij.semContributor") {
// disallow any parameters
return false
}
for (parameter in list.parameters) {
if (parameter.isVarArgs) {
return false
}
val type = parameter.type as? PsiClassType ?: return false
// before resolve, check unqualified name
val name = type.className
if (!allowedServiceNames.contains(name)) {
return false
}
val qualifiedName = (type.resolve() ?: return false).qualifiedName
if (!allowedServiceQualifiedNames.contains(qualifiedName)) {
return false
}
if (clientKind != ServiceDescriptor.ClientKind.GUEST &&
qualifiedName?.startsWith("com.jetbrains.rdserver.core") == true) {
return false
}
if (clientKind == null && allowedClientProjectSessionsQualifiedNames.contains(qualifiedName)) {
return false
}
if (isAppLevelExtensionPoint && !isServiceAnnotation && name == "Project") {
return false
}
}
return true
}
private val interfacesToCheck = HashSet(listOf(
"com.intellij.codeInsight.daemon.LineMarkerProvider",
"com.intellij.openapi.fileTypes.SyntaxHighlighterFactory"
))
private val classesToCheck = HashSet(listOf(
"com.intellij.codeInsight.completion.CompletionContributor",
"com.intellij.codeInsight.completion.CompletionConfidence",
"com.intellij.psi.PsiReferenceContributor"
))
private fun isExtensionBean(aClass: UClass): Boolean {
var found = false
InheritanceUtil.processSupers(aClass.javaPsi, true) {
val qualifiedName = it.qualifiedName
found = (if (it.isInterface) interfacesToCheck else classesToCheck).contains(qualifiedName)
!found
}
return found
}
|
apache-2.0
|
4730369faef0f7bf940945da74858329
| 39.261682 | 185 | 0.713379 | 4.983803 | false | false | false | false |
ClearVolume/scenery
|
src/main/kotlin/graphics/scenery/controls/MouseAndKeyHandlerBase.kt
|
1
|
15437
|
package graphics.scenery.controls
import gnu.trove.map.hash.TIntLongHashMap
import gnu.trove.set.hash.TIntHashSet
import graphics.scenery.Hub
import graphics.scenery.backends.SceneryWindow
import graphics.scenery.controls.behaviours.GamepadBehaviour
import graphics.scenery.controls.behaviours.GamepadClickBehaviour
import graphics.scenery.utils.ExtractsNatives
import graphics.scenery.utils.ExtractsNatives.Platform.*
import graphics.scenery.utils.LazyLogger
import net.java.games.input.*
import org.scijava.ui.behaviour.*
import java.awt.Toolkit
import java.awt.event.KeyEvent
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import java.util.logging.Level
import kotlin.concurrent.thread
import kotlin.math.abs
/**
* Base class for MouseAndKeyHandlers
*
* @author Ulrik Günther <[email protected]>
*/
open class MouseAndKeyHandlerBase : ControllerListener, ExtractsNatives {
protected val logger by LazyLogger()
/** ui-behaviour input trigger map */
protected lateinit var inputTriggerMap: InputTriggerMap
/** ui-behaviour behaviour map */
protected lateinit var behaviours: BehaviourMap
/** expected modifier count */
protected var inputMapExpectedModCount: Int = 0
/** behaviour expected modifier count */
protected var behaviourMapExpectedModCount: Int = 0
/** handle to the active controller */
protected var controller: Controller? = null
private var controllerThread: Thread? = null
private var controllerAxisDown: ConcurrentHashMap<Component.Identifier, Float> = ConcurrentHashMap()
private val gamepads = CopyOnWriteArrayList<BehaviourEntry<Behaviour>>()
private val CONTROLLER_HEARTBEAT = 5L
private val CONTROLLER_DOWN_THRESHOLD = 0.5f
protected var shouldClose = false
/**
* Managing internal behaviour lists.
*
* The internal lists only contain entries for Behaviours that can be
* actually triggered with the current InputMap, grouped by Behaviour type,
* such that hopefully lookup from the event handlers is fast,
*
* @property[buttons] Buttons triggering the input
* @property[behaviour] Behaviour triggered by these buttons
*/
class BehaviourEntry<out T : Behaviour>(
val buttons: InputTrigger,
val behaviour: T)
protected val buttonDrags = ArrayList<BehaviourEntry<DragBehaviour>>()
protected val keyDrags = ArrayList<BehaviourEntry<DragBehaviour>>()
protected val buttonClicks = ArrayList<BehaviourEntry<ClickBehaviour>>()
protected val keyClicks = ArrayList<BehaviourEntry<ClickBehaviour>>()
protected val scrolls = ArrayList<BehaviourEntry<ScrollBehaviour>>()
/**
* Which keys are currently pressed. This does not include modifier keys
* Control, Shift, Alt, AltGr, Meta.
*/
protected val pressedKeys = TIntHashSet(5, 0.5f, -1)
/**
* When keys where pressed
*/
protected val keyPressTimes = TIntLongHashMap(100, 0.5f, -1, -1)
/**
* Whether the SHIFT key is currently pressed. We need this, because for
* mouse-wheel AWT uses the SHIFT_DOWN_MASK to indicate horizontal
* scrolling. We keep track of whether the SHIFT key was actually pressed
* for disambiguation.
*/
protected var shiftPressed = false
/**
* Whether the META key is currently pressed. We need this, because on OS X
* AWT sets the META_DOWN_MASK to for right clicks. We keep track of whether
* the META key was actually pressed for disambiguation.
*/
protected var metaPressed = false
/**
* Whether the WINDOWS key is currently pressed.
*/
protected var winPressed = false
/**
* The current mouse coordinates, updated through [.mouseMoved].
*/
protected var mouseX: Int = 0
/**
* The current mouse coordinates, updated through [.mouseMoved].
*/
protected var mouseY: Int = 0
/**
* Active [DragBehaviour]s initiated by mouse button press.
*/
protected val activeButtonDrags = ArrayList<BehaviourEntry<DragBehaviour>>()
/**
* Active [DragBehaviour]s initiated by key press.
*/
protected val activeKeyDrags = ArrayList<BehaviourEntry<DragBehaviour>>()
/** the windowing system's set double click interval */
protected open val DOUBLE_CLICK_INTERVAL = getDoubleClickInterval()
init {
java.util.logging.Logger.getLogger(ControllerEnvironment::class.java.name).parent.level = Level.SEVERE
/** Returns the name of the DLL/so/dylib required by JInput on the given platform. */
fun ExtractsNatives.Platform.getPlatformJinputLibraryName(): String {
return when(this) {
WINDOWS -> "jinput-raw_64.dll"
LINUX -> "libjinput-linux64.so"
MACOS -> "libjinput-osx.jnilib"
UNKNOWN -> "none"
}
}
try {
val platformJars = getNativeJars("jinput-platform", hint = ExtractsNatives.getPlatform().getPlatformJinputLibraryName())
logger.debug("Native JARs for JInput: ${platformJars.joinToString(", ")}")
val path = extractLibrariesFromJar(platformJars, load = false)
System.setProperty("net.java.games.input.librarypath", path)
ControllerEnvironment.getDefaultEnvironment().controllers.forEach {
if (it.type == Controller.Type.STICK || it.type == Controller.Type.GAMEPAD) {
this.controller = it
logger.info("Added gamepad controller: $it")
}
}
} catch (e: Exception) {
logger.warn("Could not initialize JInput: ${e.message}")
logger.debug("Traceback: ${e.stackTrace}")
}
controllerThread = thread {
var queue: EventQueue
val event = Event()
while (!shouldClose) {
controller?.let { c ->
c.poll()
queue = c.eventQueue
while (queue.getNextEvent(event)) {
controllerEvent(event)
}
}
gamepads.forEach { gamepad ->
for (it in controllerAxisDown) {
val b = gamepad.behaviour
if (b is GamepadBehaviour) {
if (abs(it.value) > 0.02f && b.axis.contains(it.key)) {
logger.trace("Triggering ${it.key} because axis is down (${it.value})")
b.axisEvent(it.key, it.value)
}
}
}
}
Thread.sleep(this.CONTROLLER_HEARTBEAT)
}
}
}
/**
* Queries the windowing system for the current double click interval
*
* @return The double click interval in ms
*/
internal open fun getDoubleClickInterval(): Int {
val prop = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval")
return if (prop == null) {
200
} else {
prop as? Int ?: 200
}
}
/**
* Sets the input trigger map to the given map
*
* @param[inputMap] The input map to set
*/
fun setInputMap(inputMap: InputTriggerMap) {
this.inputTriggerMap = inputMap
inputMapExpectedModCount = inputMap.modCount() - 1
}
/**
* Sets the behaviour trigger map to the given map
*
* @param[behaviourMap] The behaviour map to set
*/
fun setBehaviourMap(behaviourMap: BehaviourMap) {
this.behaviours = behaviourMap
behaviourMapExpectedModCount = behaviourMap.modCount() - 1
}
/**
* Make sure that the internal behaviour lists are up to date. For this, we
* keep track the modification count of [.inputMap] and
* [.behaviourMap]. If expected mod counts are not matched, call
* [.updateInternalMaps] to rebuild the internal behaviour lists.
*/
@Synchronized protected fun update() {
val imc = inputTriggerMap.modCount()
val bmc = behaviours.modCount()
if (imc != inputMapExpectedModCount || bmc != behaviourMapExpectedModCount) {
inputMapExpectedModCount = imc
behaviourMapExpectedModCount = bmc
updateInternalMaps()
}
}
/**
* Build internal lists buttonDrag, keyDrags, etc from BehaviourMap(?) and
* InputMap(?). The internal lists only contain entries for Behaviours that
* can be actually triggered with the current InputMap, grouped by Behaviour
* type, such that hopefully lookup from the event handlers is fast.
*/
private fun updateInternalMaps() {
buttonDrags.clear()
keyDrags.clear()
buttonClicks.clear()
keyClicks.clear()
for ((buttons, value) in inputTriggerMap.allBindings) {
val behaviourKeys = value ?: continue
for (behaviourKey in behaviourKeys) {
val behaviour = behaviours.get(behaviourKey) ?: continue
if (behaviour is DragBehaviour) {
val dragEntry = BehaviourEntry(buttons, behaviour)
if (buttons.isKeyTriggered)
keyDrags.add(dragEntry)
else
buttonDrags.add(dragEntry)
}
if (behaviour is ClickBehaviour) {
val clickEntry = BehaviourEntry(buttons, behaviour)
if (buttons.isKeyTriggered)
keyClicks.add(clickEntry)
else
buttonClicks.add(clickEntry)
}
if (behaviour is ScrollBehaviour) {
val scrollEntry = BehaviourEntry(buttons, behaviour)
scrolls.add(scrollEntry)
}
if (behaviour is GamepadBehaviour || behaviour is GamepadClickBehaviour) {
val gamepadEntry = BehaviourEntry(buttons, behaviour)
gamepads.add(gamepadEntry)
}
}
}
}
/**
* Called when a new controller is added
*
* @param[event] The incoming controller event
*/
override fun controllerAdded(event: ControllerEvent?) {
if (controller == null && event != null && event.controller.type == Controller.Type.GAMEPAD) {
logger.info("Adding controller ${event.controller}")
this.controller = event.controller
}
}
/**
* Called when a controller is removed
*
* @param[event] The incoming controller event
*/
override fun controllerRemoved(event: ControllerEvent?) {
if (event != null && controller != null) {
logger.info("Controller removed: ${event.controller}")
controller = null
}
}
private fun controllerButtonToKeyCode(id: Component.Identifier, value: Float): Int? {
return when(id.name) {
GamepadButton.Button0.ordinal.toString() -> KeyEvent.VK_0
GamepadButton.Button1.ordinal.toString()-> KeyEvent.VK_1
GamepadButton.Button2.ordinal.toString() -> KeyEvent.VK_2
GamepadButton.Button3.ordinal.toString() -> KeyEvent.VK_3
GamepadButton.Button4.ordinal.toString() -> KeyEvent.VK_4
GamepadButton.Button5.ordinal.toString() -> KeyEvent.VK_5
GamepadButton.Button6.ordinal.toString() -> KeyEvent.VK_6
GamepadButton.Button7.ordinal.toString() -> KeyEvent.VK_7
GamepadButton.Button8.ordinal.toString() -> KeyEvent.VK_8
"pov" -> {
when (value) {
0.25f -> KeyEvent.VK_NUMPAD8
0.5f -> KeyEvent.VK_NUMPAD6
0.75f -> KeyEvent.VK_NUMPAD2
1.0f -> KeyEvent.VK_NUMPAD4
else -> null
}
}
else -> null
}
}
private val pressedGamepadKeys = TIntHashSet()
/**
* Called when a controller event is fired. This will update the currently down
* buttons/axis on the controller.
*
* @param[event] The incoming controller event
*/
fun controllerEvent(event: Event) {
logger.trace("Event: $event/identifier=${event.component.identifier}")
for (gamepad in gamepads) {
if (event.component.isAnalog) {
if (abs(event.component.pollData) < CONTROLLER_DOWN_THRESHOLD) {
logger.trace("${event.component.identifier} over threshold, removing")
controllerAxisDown[event.component.identifier] = 0.0f
} else {
controllerAxisDown[event.component.identifier] = event.component.pollData
}
} else {
val button = controllerButtonToKeyCode(event.component.identifier, event.value)
if (event.component.identifier != Component.Identifier.Axis.POV && button != null) {
if (event.value < 0.1f) {
pressedGamepadKeys.remove(button)
}
if (event.value > 0.9f) {
pressedGamepadKeys.add(button)
}
} else {
if(button == null) {
listOf(0.25f, 0.5f, 0.75f, 1.0f).forEach { value ->
controllerButtonToKeyCode(Component.Identifier.Axis.POV, value)?.let {
pressedGamepadKeys.remove(it)
}
}
} else {
if (event.value > 0.05f) {
pressedGamepadKeys.add(button)
} else {
pressedGamepadKeys.remove(button)
}
}
}
}
when(val b = gamepad.behaviour) {
is GamepadBehaviour -> {
if (b.axis.contains(event.component.identifier)) {
b.axisEvent(event.component.identifier, event.component.pollData)
}
}
is GamepadClickBehaviour -> {
if(gamepad.buttons.matches(0, pressedGamepadKeys)) {
b.click(0, 0)
}
}
}
}
}
/**
* Attaches this handler to a given [window], with input bindings and behaviours given in [inputMap] and
* [behaviourMap]. MouseAndKeyHandlerBase itself cannot be attached to any windows.
*/
open fun attach(hub: Hub?, window: SceneryWindow, inputMap: InputTriggerMap, behaviourMap: BehaviourMap): MouseAndKeyHandlerBase {
throw UnsupportedOperationException("MouseAndKeyHandlerBase cannot be attached to a window.")
}
/**
* Closes this instance of MouseAndKeyHandlerBase.
* This function needs to be called as super.close() by derived classes in order to clean up gamepad handling logic.
*/
open fun close() {
shouldClose = true
controllerThread?.join()
controllerThread = null
logger.debug("MouseAndKeyHandlerBase closed.")
}
}
|
lgpl-3.0
|
eed9f6c2e9c656500281686389e2d30a
| 35.578199 | 134 | 0.593353 | 5.084321 | false | false | false | false |
JetBrains/kotlin-native
|
shared/src/library/kotlin/org/jetbrains/kotlin/konan/library/SearchPathResolver.kt
|
1
|
3283
|
package org.jetbrains.kotlin.konan.library
import org.jetbrains.kotlin.konan.CompilerVersion
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.library.impl.KonanLibraryImpl
import org.jetbrains.kotlin.konan.library.impl.createKonanLibraryComponents
import org.jetbrains.kotlin.konan.target.Distribution
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.library.impl.createKotlinLibrary
import org.jetbrains.kotlin.util.DummyLogger
import org.jetbrains.kotlin.util.Logger
interface SearchPathResolverWithTarget<L: KotlinLibrary>: SearchPathResolver<L> {
val target: KonanTarget
}
fun defaultResolver(
repositories: List<String>,
target: KonanTarget,
distribution: Distribution
): SearchPathResolverWithTarget<KonanLibrary> = defaultResolver(repositories, emptyList(), target, distribution)
fun defaultResolver(
repositories: List<String>,
directLibs: List<String>,
target: KonanTarget,
distribution: Distribution,
logger: Logger = DummyLogger,
skipCurrentDir: Boolean = false
): SearchPathResolverWithTarget<KonanLibrary> = KonanLibraryProperResolver(
repositories,
directLibs,
target,
distribution.klib,
distribution.localKonanDir.absolutePath,
skipCurrentDir,
logger
)
fun resolverByName(
repositories: List<String>,
directLibs: List<String> = emptyList(),
distributionKlib: String? = null,
localKotlinDir: String? = null,
skipCurrentDir: Boolean = false,
logger: Logger
): SearchPathResolver<KotlinLibrary> =
object : KotlinLibrarySearchPathResolver<KotlinLibrary>(
repositories,
directLibs,
distributionKlib,
localKotlinDir,
skipCurrentDir,
logger
) {
override fun libraryComponentBuilder(file: File, isDefault: Boolean) = createKonanLibraryComponents(file, null, isDefault)
}
internal class KonanLibraryProperResolver(
repositories: List<String>,
directLibs: List<String>,
override val target: KonanTarget,
distributionKlib: String?,
localKonanDir: String?,
skipCurrentDir: Boolean,
override val logger: Logger
) : KotlinLibraryProperResolverWithAttributes<KonanLibrary>(
repositories, directLibs,
distributionKlib,
localKonanDir,
skipCurrentDir,
logger,
listOf(KLIB_INTEROP_IR_PROVIDER_IDENTIFIER)
), SearchPathResolverWithTarget<KonanLibrary>
{
override fun libraryComponentBuilder(file: File, isDefault: Boolean) = createKonanLibraryComponents(file, target, isDefault)
override val distPlatformHead: File?
get() = distributionKlib?.File()?.child("platform")?.child(target.visibleName)
override fun libraryMatch(candidate: KonanLibrary, unresolved: UnresolvedLibrary): Boolean {
val resolverTarget = this.target
val candidatePath = candidate.libraryFile.absolutePath
if (!candidate.targetList.contains(resolverTarget.visibleName)) {
logger.warning("skipping $candidatePath. The target doesn't match. Expected '$resolverTarget', found ${candidate.targetList}")
return false
}
return super.libraryMatch(candidate, unresolved)
}
}
|
apache-2.0
|
80bef37a3efce8d88bbd217eef89a577
| 33.925532 | 138 | 0.742004 | 5.074189 | false | false | false | false |
vovagrechka/fucking-everything
|
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/clean/removeUnusedImports.kt
|
3
|
1458
|
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.inline.clean
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.metadata.imported
fun removeUnusedImports(root: JsNode) {
val collector = UsedImportsCollector()
root.accept(collector)
NodeRemover(JsVars::class.java) { statement ->
if (statement.vars.size == 1) {
val name = statement.vars[0].name
name.imported && name !in collector.usedImports
}
else {
false
}
}.accept(root)
}
private class UsedImportsCollector : RecursiveJsVisitor() {
val usedImports = mutableSetOf<JsName>()
override fun visitNameRef(nameRef: JsNameRef) {
val name = nameRef.name
if (name != null && name.imported) {
usedImports += name
}
super.visitNameRef(nameRef)
}
}
|
apache-2.0
|
ec0c6229c1b1a7b54673d02d76f81051
| 30.695652 | 75 | 0.679698 | 4.107042 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt
|
1
|
1848
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.psi.KtCodeFragment
abstract class KotlinIntentionActionsFactory : QuickFixFactory {
protected open fun isApplicableForCodeFragment(): Boolean = false
protected abstract fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction>
protected open fun doCreateActionsForAllProblems(
sameTypeDiagnostics: Collection<Diagnostic>
): List<IntentionAction> = emptyList()
fun createActions(diagnostic: Diagnostic): List<IntentionAction> = createActions(listOfNotNull(diagnostic), false)
fun createActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<IntentionAction> =
createActions(sameTypeDiagnostics, true)
private fun createActions(sameTypeDiagnostics: Collection<Diagnostic>, createForAll: Boolean): List<IntentionAction> {
if (sameTypeDiagnostics.isEmpty()) return emptyList()
val first = sameTypeDiagnostics.first()
if (first.psiElement.containingFile is KtCodeFragment && !isApplicableForCodeFragment()) {
return emptyList()
}
if (sameTypeDiagnostics.size > 1 && createForAll) {
assert(sameTypeDiagnostics.all { it.psiElement == first.psiElement && it.factory == first.factory }) {
"It's expected to be the list of diagnostics of same type and for same element"
}
return doCreateActionsForAllProblems(sameTypeDiagnostics)
}
return sameTypeDiagnostics.flatMapTo(arrayListOf()) { doCreateActions(it) }
}
}
|
apache-2.0
|
3780fa436a4d5fd22a48884835ba5cd9
| 44.073171 | 158 | 0.742424 | 5.5 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/tests-common/test/org/jetbrains/kotlin/idea/TestHelperGenerator.kt
|
4
|
6570
|
// 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
import org.jetbrains.kotlin.test.TargetBackend
// Add the directive `// WITH_COROUTINES` to use these helpers in codegen tests (see TestFiles.java).
fun createTextForCoroutineHelpers(checkStateMachine: Boolean, checkTailCallOptimization: Boolean): String {
fun continuationBody(t: String, useResult: (String) -> String) =
"""
|override fun resumeWith(result: Result<$t>) {
| ${useResult("result.getOrThrow()")}
|}
""".trimMargin()
val handleExceptionContinuationBody =
"""
|override fun resumeWith(result: Result<Any?>) {
| result.exceptionOrNull()?.let(x)
|}
""".trimMargin()
val continuationAdapterBody =
"""
|override fun resumeWith(result: Result<T>) {
| if (result.isSuccess) {
| resume(result.getOrThrow())
| } else {
| resumeWithException(result.exceptionOrNull()!!)
| }
|}
|
|abstract fun resumeWithException(exception: Throwable)
|abstract fun resume(value: T)
""".trimMargin()
val checkStateMachineString = """
class StateMachineCheckerClass {
private var counter = 0
var finished = false
var proceed: () -> Unit = {}
fun reset() {
counter = 0
finished = false
proceed = {}
}
suspend fun suspendHere() = suspendCoroutine<Unit> { c ->
counter++
proceed = { c.resume(Unit) }
}
fun check(numberOfSuspensions: Int, checkFinished: Boolean = true) {
for (i in 1..numberOfSuspensions) {
if (counter != i) error("Wrong state-machine generated: suspendHere should be called exactly once in one state. Expected " + i + ", got " + counter)
proceed()
}
if (counter != numberOfSuspensions)
error("Wrong state-machine generated: wrong number of overall suspensions. Expected " + numberOfSuspensions + ", got " + counter)
if (finished) error("Wrong state-machine generated: it is finished early")
proceed()
if (checkFinished && !finished) error("Wrong state-machine generated: it is not finished yet")
}
}
val StateMachineChecker = StateMachineCheckerClass()
object CheckStateMachineContinuation: ContinuationAdapter<Unit>() {
override val context: CoroutineContext
get() = EmptyCoroutineContext
override fun resume(value: Unit) {
StateMachineChecker.proceed = {
StateMachineChecker.finished = true
}
}
override fun resumeWithException(exception: Throwable) {
throw exception
}
}
""".trimIndent()
// TODO: Find a way to check for tail-call optimization on JS and Native
val checkTailCallOptimizationString =
"""
class TailCallOptimizationCheckerClass {
private val stackTrace = arrayListOf<StackTraceElement?>()
suspend fun saveStackTrace() = suspendCoroutineUninterceptedOrReturn<Unit> {
saveStackTrace(it)
}
fun saveStackTrace(c: Continuation<*>) {
if (c !is CoroutineStackFrame) error("Continuation " + c + " is not subtype of CoroutineStackFrame")
stackTrace.clear()
var csf: CoroutineStackFrame? = c
while (csf != null) {
stackTrace.add(csf.getStackTraceElement())
csf = csf.callerFrame
}
}
fun checkNoStateMachineIn(method: String) {
stackTrace.find { it?.methodName?.startsWith(method) == true }?.let { error("tail-call optimization miss: method at " + it + " has state-machine " +
stackTrace.joinToString(separator = "\n")) }
}
fun checkStateMachineIn(method: String) {
stackTrace.find { it?.methodName?.startsWith(method) == true } ?: error("tail-call optimization hit: method " + method + " has no state-machine " +
stackTrace.joinToString(separator = "\n"))
}
}
val TailCallOptimizationChecker = TailCallOptimizationCheckerClass()
""".trimIndent()
return """
|package helpers
|import kotlin.coroutines.*
|import kotlin.coroutines.intrinsics.*
|${if (checkTailCallOptimization) "import kotlin.coroutines.jvm.internal.*" else ""}
|
|fun <T> handleResultContinuation(x: (T) -> Unit): Continuation<T> = object: Continuation<T> {
| override val context = EmptyCoroutineContext
| ${continuationBody("T") { "x($it)" }}
|}
|
|fun handleExceptionContinuation(x: (Throwable) -> Unit): Continuation<Any?> = object: Continuation<Any?> {
| override val context = EmptyCoroutineContext
| $handleExceptionContinuationBody
|}
|
|open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
| companion object : EmptyContinuation()
| ${continuationBody("Any?") { it }}
|}
|
|class ResultContinuation : Continuation<Any?> {
| override val context = EmptyCoroutineContext
| ${continuationBody("Any?") { "this.result = $it" }}
|
| var result: Any? = null
|}
|
|abstract class ContinuationAdapter<in T> : Continuation<T> {
| override val context: CoroutineContext = EmptyCoroutineContext
| $continuationAdapterBody
|}
|
|${if (checkStateMachine) checkStateMachineString else ""}
|${if (checkTailCallOptimization) checkTailCallOptimizationString else ""}
""".trimMargin()
}
// Add the directive `// WITH_HELPERS` to use these helpers in codegen tests (see CodegenTestCase.java).
fun createTextForCodegenTestHelpers(backend: TargetBackend) =
"""
|package helpers
|
|fun isIR() = ${backend.isIR}
""".trimMargin()
|
apache-2.0
|
db958cb546d21891af50a082b4dc6ce5
| 39.555556 | 164 | 0.573973 | 5.23506 | false | false | false | false |
jwren/intellij-community
|
platform/platform-api/src/com/intellij/ui/tabs/impl/themes/TabTheme.kt
|
5
|
6314
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.tabs.impl.themes
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.ui.ExperimentalUI
import com.intellij.util.ui.JBUI
import java.awt.Color
interface TabTheme {
val topBorderThickness: Int
get() = JBUI.scale(1)
val background: Color?
val borderColor: Color
val underlineColor: Color
val inactiveUnderlineColor: Color
val hoverBackground: Color
val hoverSelectedBackground: Color
get() = hoverBackground
val hoverSelectedInactiveBackground: Color
get() = hoverBackground
val hoverInactiveBackground: Color?
val underlinedTabBackground: Color?
val underlinedTabForeground: Color
val underlineHeight: Int
val underlineArc: Int
get() = 0
val underlinedTabInactiveBackground: Color?
val underlinedTabInactiveForeground: Color?
val inactiveColoredTabBackground: Color?
}
open class DefaultTabTheme : TabTheme {
override val background: Color? get() = JBUI.CurrentTheme.DefaultTabs.background()
override val borderColor: Color get() = JBUI.CurrentTheme.DefaultTabs.borderColor()
override val underlineColor: Color get() = JBUI.CurrentTheme.DefaultTabs.underlineColor()
override val inactiveUnderlineColor: Color get() = JBUI.CurrentTheme.DefaultTabs.inactiveUnderlineColor()
override val hoverBackground: Color get() = JBUI.CurrentTheme.DefaultTabs.hoverBackground()
override val underlinedTabBackground: Color? get() = JBUI.CurrentTheme.DefaultTabs.underlinedTabBackground()
override val underlinedTabForeground: Color get() = JBUI.CurrentTheme.DefaultTabs.underlinedTabForeground()
override val underlineHeight: Int get()= JBUI.CurrentTheme.DefaultTabs.underlineHeight()
override val hoverInactiveBackground: Color?
get() = hoverBackground
override val underlinedTabInactiveBackground: Color?
get() = underlinedTabBackground
override val underlinedTabInactiveForeground: Color
get() = underlinedTabForeground
override val inactiveColoredTabBackground: Color
get() = JBUI.CurrentTheme.DefaultTabs.inactiveColoredTabBackground()
}
class EditorTabTheme : TabTheme {
override val topBorderThickness: Int
get() = newUIAware(1, super.topBorderThickness)
val globalScheme: EditorColorsScheme
get() = EditorColorsManager.getInstance().globalScheme
override val background: Color
get() = newUIAware(EditorColorsManager.getInstance().globalScheme.defaultBackground, JBUI.CurrentTheme.EditorTabs.background())
override val borderColor: Color
get() = JBUI.CurrentTheme.EditorTabs.borderColor()
override val underlineColor: Color
get() = globalScheme.getColor(EditorColors.TAB_UNDERLINE) ?: JBUI.CurrentTheme.EditorTabs.underlineColor()
override val inactiveUnderlineColor: Color
get() = globalScheme.getColor(EditorColors.TAB_UNDERLINE_INACTIVE) ?: JBUI.CurrentTheme.EditorTabs.inactiveUnderlineColor()
override val underlinedTabBackground: Color?
get() = newUIAware(globalScheme.defaultBackground as Color?, globalScheme.getAttributes(EditorColors.TAB_SELECTED).backgroundColor?: JBUI.CurrentTheme.EditorTabs.underlinedTabBackground())
override val underlinedTabForeground: Color
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED).foregroundColor?: JBUI.CurrentTheme.EditorTabs.underlinedTabForeground()
override val underlineHeight: Int
get() = JBUI.CurrentTheme.EditorTabs.underlineHeight()
override val underlineArc: Int
get() = JBUI.CurrentTheme.EditorTabs.underlineArc()
override val hoverBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.hoverBackground()
override val hoverInactiveBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.hoverBackground(false, false)
override val hoverSelectedBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.hoverBackground(true, true)
override val hoverSelectedInactiveBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.hoverBackground(true, false)
override val underlinedTabInactiveBackground: Color?
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED_INACTIVE).backgroundColor?: underlinedTabBackground
override val underlinedTabInactiveForeground: Color
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED_INACTIVE).foregroundColor?: underlinedTabForeground
override val inactiveColoredTabBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.inactiveColoredFileBackground()
fun <T> newUIAware(newUI: T, oldUI:T):T = if (ExperimentalUI.isNewUI()) newUI else oldUI
}
internal class ToolWindowTabTheme : DefaultTabTheme() {
override val background: Color?
get() = null
override val borderColor: Color
get() = JBUI.CurrentTheme.ToolWindow.borderColor()
override val underlineColor: Color
get() = JBUI.CurrentTheme.ToolWindow.underlineColor()
override val inactiveUnderlineColor: Color
get() = JBUI.CurrentTheme.ToolWindow.inactiveUnderlineColor()
override val hoverBackground: Color
get() = JBUI.CurrentTheme.ToolWindow.hoverBackground()
override val underlinedTabBackground: Color?
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabBackground()
override val underlinedTabForeground: Color
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabForeground()
override val underlineHeight: Int
get() = JBUI.CurrentTheme.ToolWindow.underlineHeight()
override val underlineArc: Int
get() = JBUI.CurrentTheme.ToolWindow.headerTabUnderlineArc()
override val hoverInactiveBackground: Color?
get() = JBUI.CurrentTheme.ToolWindow.hoverInactiveBackground()
override val underlinedTabInactiveBackground: Color?
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabInactiveBackground()
override val underlinedTabInactiveForeground: Color
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabInactiveForeground()
}
internal class DebuggerTabTheme : DefaultTabTheme() {
override val underlineHeight: Int
get() = JBUI.CurrentTheme.DebuggerTabs.underlineHeight()
override val underlinedTabBackground: Color?
get() = JBUI.CurrentTheme.DebuggerTabs.underlinedTabBackground()
}
|
apache-2.0
|
a3ba0305e45e108e6397aa1a7e3c0d5d
| 42.854167 | 192 | 0.795692 | 5.457217 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/run-configurations/jvm/src/org/jetbrains/kotlin/idea/runConfigurations/jvm/KotlinMainMethodProvider.kt
|
1
|
2699
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.runConfigurations.jvm
import com.intellij.codeInsight.runner.JavaMainMethodProvider
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.classes.KtLightClassBase
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacadeBase
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinMainFunctionDetector
import org.jetbrains.kotlin.idea.base.codeInsight.findMain
import org.jetbrains.kotlin.idea.base.codeInsight.hasMain
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedFunction
class KotlinMainMethodProvider: JavaMainMethodProvider {
override fun isApplicable(clazz: PsiClass): Boolean {
return clazz is KtLightClassBase
}
override fun hasMainMethod(clazz: PsiClass): Boolean {
val lightClassBase = clazz as? KtLightClassBase
val mainFunctionDetector = KotlinMainFunctionDetector.getInstance()
if (lightClassBase is KtLightClassForFacadeBase) {
return runReadAction { lightClassBase.files.any { mainFunctionDetector.hasMain(it) } }
}
val classOrObject = lightClassBase?.kotlinOrigin ?: return false
return runReadAction { mainFunctionDetector.hasMain(classOrObject) }
}
override fun findMainInClass(clazz: PsiClass): PsiMethod? =
runReadAction {
val lightClassBase = clazz as? KtLightClassBase
val mainFunctionDetector = KotlinMainFunctionDetector.getInstance()
if (lightClassBase is KtLightClassForFacadeBase) {
return@runReadAction lightClassBase.files
.asSequence()
.flatMap { it.declarations }
.mapNotNull { declaration ->
ProgressManager.checkCanceled()
when (declaration) {
is KtNamedFunction -> declaration.takeIf(mainFunctionDetector::isMain)
is KtClassOrObject -> mainFunctionDetector.findMain(declaration)
else -> null
}
}.flatMap { it.toLightMethods() }
.firstOrNull()
}
val classOrObject = lightClassBase?.kotlinOrigin ?: return@runReadAction null
mainFunctionDetector.findMain(classOrObject)?.toLightMethods()?.firstOrNull()
}
}
|
apache-2.0
|
7400e61a26e7c08527d56132fbc1a199
| 48.090909 | 120 | 0.696925 | 5.767094 | false | false | false | false |
androidx/androidx
|
external/paparazzi/paparazzi/src/main/java/app/cash/paparazzi/internal/PaparazziLogger.kt
|
3
|
3722
|
/*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.paparazzi.internal
import app.cash.paparazzi.Paparazzi
import com.android.ide.common.rendering.api.ILayoutLog
import com.android.utils.ILogger
import java.io.PrintStream
import java.io.PrintWriter
import java.util.logging.Level
import java.util.logging.Logger
import java.util.logging.Logger.getLogger
/**
* This logger delegates to java.util.Logging.
*/
internal class PaparazziLogger : ILayoutLog, ILogger {
private val logger: Logger = getLogger(Paparazzi::class.java.name)
private val errors = mutableListOf<Throwable>()
override fun error(
throwable: Throwable?,
format: String?,
vararg args: Any
) {
logger.log(Level.SEVERE, format?.format(args), throwable)
if (throwable != null) {
errors += throwable
}
}
override fun warning(
format: String,
vararg args: Any
) {
logger.log(Level.WARNING, format, args)
}
override fun info(
format: String,
vararg args: Any
) {
logger.log(Level.INFO, format, args)
}
override fun verbose(
format: String,
vararg args: Any
) {
logger.log(Level.FINE, format, args)
}
override fun fidelityWarning(
tag: String?,
message: String?,
throwable: Throwable?,
cookie: Any?,
data: Any?
) {
logger.log(Level.WARNING, "$tag: $message", throwable)
}
override fun error(
tag: String?,
message: String?,
viewCookie: Any?,
data: Any?
) {
logger.log(Level.SEVERE, "$tag: $message")
}
override fun error(
tag: String?,
message: String?,
throwable: Throwable?,
viewCookie: Any?,
data: Any?
) {
logger.log(Level.SEVERE, "$tag: $message", throwable)
if (throwable != null) {
errors += throwable
}
}
override fun warning(
tag: String?,
message: String?,
viewCookie: Any?,
data: Any?
) {
logger.log(Level.WARNING, "$tag: $message")
}
override fun logAndroidFramework(priority: Int, tag: String?, message: String?) {
logger.log(Level.INFO, "$tag [$priority]: $message")
}
fun assertNoErrors() {
when (errors.size) {
0 -> return
1 -> throw errors[0]
else -> throw MultipleFailuresException(errors)
}
}
internal class MultipleFailuresException(private val causes: List<Throwable>) : Exception() {
init {
require(causes.isNotEmpty()) { "List of Throwables must not be empty" }
}
override val message: String
get() = buildString {
appendLine(String.format("There were %d errors:", causes.size))
causes.forEach { e ->
appendLine(String.format("%n %s: %s", e.javaClass.name, e.message))
e.stackTrace.forEach { traceElement ->
appendLine("\tat $traceElement")
}
}
}
override fun printStackTrace() {
causes.forEach { e ->
e.printStackTrace()
}
}
override fun printStackTrace(s: PrintStream) {
causes.forEach { e ->
e.printStackTrace(s)
}
}
override fun printStackTrace(s: PrintWriter) {
causes.forEach { e ->
e.printStackTrace(s)
}
}
}
}
|
apache-2.0
|
e248c066eeeffbbb46c2b94b0a544f80
| 23.326797 | 95 | 0.643471 | 3.938624 | false | false | false | false |
GunoH/intellij-community
|
plugins/git4idea/src/git4idea/index/GitStageManager.kt
|
5
|
2234
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.impl.LineStatusTrackerSettingListener
import com.intellij.vcs.commit.CommitMode
import com.intellij.vcs.commit.CommitModeManager
import git4idea.GitVcs
import git4idea.config.GitVcsApplicationSettings
internal class CommitModeListener(val project: Project) : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
ApplicationManager.getApplication().assertIsDispatchThread()
if (isStagingAreaAvailable(project)) {
GitStageTracker.getInstance(project).updateTrackerState()
}
invokeLater {
// Notify LSTM after CLM to let it save current partial changelists state
ApplicationManager.getApplication().messageBus.syncPublisher(LineStatusTrackerSettingListener.TOPIC).settingsUpdated()
}
}
}
internal class GitStageStartupActivity : ProjectPostStartupActivity {
override suspend fun execute(project: Project) {
if (isStagingAreaAvailable(project)) {
GitStageTracker.getInstance(project) // initialize tracker
}
}
}
internal fun stageLineStatusTrackerRegistryOption() = Registry.get("git.enable.stage.line.status.tracker")
fun enableStagingArea(enabled: Boolean) {
val applicationSettings = GitVcsApplicationSettings.getInstance()
if (enabled == applicationSettings.isStagingAreaEnabled) return
applicationSettings.isStagingAreaEnabled = enabled
ApplicationManager.getApplication().messageBus.syncPublisher(CommitModeManager.SETTINGS).settingsChanged()
}
internal fun canEnableStagingArea() = CommitModeManager.isNonModalInSettings()
internal fun isStagingAreaAvailable(project: Project): Boolean {
val commitMode = CommitModeManager.getInstance(project).getCurrentCommitMode()
return commitMode is CommitMode.ExternalCommitMode &&
commitMode.vcs.keyInstanceMethod == GitVcs.getKey()
}
|
apache-2.0
|
cf802f8b1335ad76dd1dab3f77c2b398
| 40.388889 | 124 | 0.813787 | 5.207459 | false | false | false | false |
GunoH/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/sam/samConversion.kt
|
2
|
8607
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.lang.sam
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil
import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.MethodSignature
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.asSafely
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isTrait
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.lang.resolve.api.*
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.ExpectedType
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.GroovyInferenceSession
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypeConstraint
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypePositionConstraint
import org.jetbrains.plugins.groovy.lang.typing.GroovyClosureType
fun findSingleAbstractMethod(clazz: PsiClass): PsiMethod? = findSingleAbstractSignatureCached(clazz)?.method
fun findSingleAbstractSignature(clazz: PsiClass): MethodSignature? = findSingleAbstractSignatureCached(clazz)
private fun findSingleAbstractMethodAndClass(type: PsiType): Pair<PsiMethod, PsiClassType.ClassResolveResult>? {
val groundType = (type as? PsiClassType)?.let { FunctionalInterfaceParameterizationUtil.getNonWildcardParameterization(it) }
?: return null
val resolveResult = (groundType as PsiClassType).resolveGenerics()
val samClass = resolveResult.element ?: return null
val sam = findSingleAbstractMethod(samClass) ?: return null
return sam to resolveResult
}
private fun findSingleAbstractSignatureCached(clazz: PsiClass): HierarchicalMethodSignature? {
return CachedValuesManager.getCachedValue(clazz) {
CachedValueProvider.Result.create(doFindSingleAbstractSignature(clazz), clazz)
}
}
private fun doFindSingleAbstractSignature(clazz: PsiClass): HierarchicalMethodSignature? {
var result: HierarchicalMethodSignature? = null
for (signature in clazz.visibleSignatures) {
if (!isEffectivelyAbstractMethod(signature)) continue
if (result != null) return null // found another abstract method
result = signature
}
return result
}
private fun isEffectivelyAbstractMethod(signature: HierarchicalMethodSignature): Boolean {
val method = signature.method
if (!method.hasModifierProperty(PsiModifier.ABSTRACT)) return false
if (isObjectMethod(signature)) return false
if (isImplementedTraitMethod(method)) return false
return true
}
private fun isObjectMethod(signature: HierarchicalMethodSignature): Boolean {
return signature.superSignatures.any {
it.method.containingClass?.qualifiedName == JAVA_LANG_OBJECT
}
}
private fun isImplementedTraitMethod(method: PsiMethod): Boolean {
val clazz = method.containingClass ?: return false
if (!isTrait(clazz)) return false
val traitMethod = method as? GrMethod ?: return false
return traitMethod.block != null
}
fun isSamConversionAllowed(context: PsiElement): Boolean {
return GroovyConfigUtils.getInstance().isVersionAtLeast(context, GroovyConfigUtils.GROOVY2_2)
}
internal fun processSAMConversion(targetType: PsiType,
closureType: GroovyClosureType,
context: PsiElement): List<ConstraintFormula> {
val constraints = mutableListOf<ConstraintFormula>()
val pair = findSingleAbstractMethodAndClass(targetType)
if (pair == null) {
constraints.add(
TypeConstraint(targetType, TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, context), context))
return constraints
}
val (sam, classResolveResult) = pair
val groundClass = classResolveResult.element ?: return constraints
val groundType = groundTypeForClosure(sam, groundClass, closureType, classResolveResult.substitutor, context)
if (groundType != null) {
constraints.add(TypeConstraint(targetType, groundType, context))
}
return constraints
}
private fun returnTypeConstraint(samReturnType: PsiType?,
returnType: PsiType?,
context: PsiElement): ConstraintFormula? {
if (returnType == null || samReturnType == null || samReturnType == PsiType.VOID) {
return null
}
return TypeConstraint(samReturnType, returnType, context)
}
/**
* JLS 18.5.3
* com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil.getFunctionalTypeExplicit
*/
private fun groundTypeForClosure(sam: PsiMethod,
groundClass: PsiClass,
closureType: GroovyClosureType,
resultTypeSubstitutor : PsiSubstitutor,
context: PsiElement): PsiClassType? {
if (!Registry.`is`("groovy.use.explicitly.typed.closure.in.inference", true)) return null
val typeParameters = groundClass.typeParameters ?: return null
if (typeParameters.isEmpty()) return null
val samContainingClass = sam.containingClass ?: return null
val groundClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(samContainingClass, groundClass, PsiSubstitutor.EMPTY)
// erase all ground class parameters to null, otherwise explicit closure signature will be inapplicable
val erasingSubstitutor = PsiSubstitutor.createSubstitutor(typeParameters.associate { it to PsiType.NULL })
val samParameterTypes = sam.parameterList.parameters.map { it.type }
val arguments = samParameterTypes.map {
val withInheritance = groundClassSubstitutor.substitute(it)
ExplicitRuntimeTypeArgument(withInheritance, TypeConversionUtil.erasure(erasingSubstitutor.substitute(withInheritance)))
}
val argumentMapping = closureType.applyTo(arguments).find { it.applicability() == Applicability.applicable } ?: return null
val samSession = GroovyInferenceSession(typeParameters, PsiSubstitutor.EMPTY, context, false)
argumentMapping.expectedTypes.forEach { (expectedType, argument) ->
val adjustedExpectedType = adjustUntypedParameter(argument, argumentMapping.targetParameter(argument), resultTypeSubstitutor) ?: expectedType
val leftType = samSession.substituteWithInferenceVariables(groundClassSubstitutor.substitute(adjustedExpectedType))
samSession.addConstraint(
TypePositionConstraint(ExpectedType(leftType, GrTypeConverter.Position.METHOD_PARAMETER), samSession.substituteWithInferenceVariables(argument.type), context))
}
val returnTypeConstraint = returnTypeConstraint(sam.returnType, closureType.returnType(arguments), context)
if (returnTypeConstraint != null) samSession.addConstraint(returnTypeConstraint)
if (!samSession.repeatInferencePhases()) {
return null
}
val resultSubstitutor = samSession.result()
val elementFactory = JavaPsiFacade.getElementFactory(context.project)
return elementFactory.createType(groundClass, resultSubstitutor)
}
private fun adjustUntypedParameter(argument : Argument, parameter : CallParameter?, resultTypeSubstitutor: PsiSubstitutor) : PsiType? {
val psi = (parameter as? PsiCallParameter)?.psi?.takeIf { it.typeElement == null } ?: return null
return if (psi.typeElement == null) {
resultTypeSubstitutor.substitute(argument.type)
} else {
null
}
}
internal fun samDistance(closure: Argument?, samClass: PsiClass?) : Int? {
if (closure !is ExpressionArgument || closure.type !is GroovyClosureType) {
return null
}
samClass ?: return null
val sam = findSingleAbstractMethod(samClass) ?: return null
val argument = closure.expression.asSafely<GrFunctionalExpression>() ?: return null
if (argument.parameterList.isEmpty) {
return 3
}
if (sam.parameters.isEmpty() == argument.parameters.isEmpty()) {
return 2
} else {
return 3
}
}
|
apache-2.0
|
06f9c0e99b3b661560a5ed05a92df0a1
| 45.27957 | 165 | 0.777971 | 4.980903 | false | false | false | false |
feelfreelinux/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/fragments/entries/EntriesFragmentPresenter.kt
|
1
|
2015
|
package io.github.feelfreelinux.wykopmobilny.ui.fragments.entries
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.github.feelfreelinux.wykopmobilny.utils.intoComposite
import io.reactivex.Single
open class EntriesFragmentPresenter(
val schedulers: Schedulers,
val entriesApi: EntriesApi,
val entriesInteractor: EntriesInteractor
) : BasePresenter<EntriesFragmentView>(), EntryActionListener {
override fun voteEntry(entry: Entry) = entriesInteractor.voteEntry(entry).processEntrySingle(entry)
override fun unvoteEntry(entry: Entry) = entriesInteractor.unvoteEntry(entry).processEntrySingle(entry)
override fun markFavorite(entry: Entry) = entriesInteractor.markFavorite(entry).processEntrySingle(entry)
override fun deleteEntry(entry: Entry) = entriesInteractor.deleteEntry(entry).processEntrySingle(entry)
override fun voteSurvey(entry: Entry, index: Int) = entriesInteractor.voteSurvey(entry, index).processEntrySingle(entry)
override fun getVoters(entry: Entry) {
view?.openVotersMenu()
entriesApi.getEntryVoters(entry.id)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({
view?.showVoters(it)
}, {
view?.showErrorDialog(it)
})
.intoComposite(compositeObservable)
}
private fun Single<Entry>.processEntrySingle(entry: Entry) {
this
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.updateEntry(it) },
{
view?.showErrorDialog(it)
view?.updateEntry(entry)
})
.intoComposite(compositeObservable)
}
}
|
mit
|
1ea34615558de401eac3430e50ba963f
| 39.32 | 124 | 0.705707 | 5.0375 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/tests/testData/structuralsearch/binaryExpression/binaryRangeTo.kt
|
4
|
132
|
val a = <warning descr="SSR">1..2</warning>
val b = <warning descr="SSR">1.rangeTo(2)</warning>
val c = 1..3
val d = 1.rangeTo(3)
|
apache-2.0
|
d88c1e3edb4b49b1ed412a8c8212564b
| 18 | 51 | 0.621212 | 2.490566 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KotlinCacheServiceImpl.kt
|
1
|
31823
|
// 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.caches.resolve
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.openapi.util.ModificationTracker
import com.intellij.psi.PsiCodeFragment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.SLRUCache
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForLibrariesName
import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForModulesName
import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForScriptDependenciesName
import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForSdkName
import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForSpecialInfoName
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.caches.resolve.PlatformAnalysisSettings
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.context.GlobalContext
import org.jetbrains.kotlin.context.GlobalContextImpl
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.util.GlobalFacadeModuleFilters
import org.jetbrains.kotlin.idea.caches.resolve.util.contextWithCompositeExceptionTracker
import org.jetbrains.kotlin.idea.caches.trackers.outOfBlockModificationCount
import org.jetbrains.kotlin.idea.compiler.IDELanguageSettingsProvider
import org.jetbrains.kotlin.idea.core.script.ScriptDependenciesModificationTracker
import org.jetbrains.kotlin.idea.core.script.dependencies.ScriptAdditionalIdeaDependenciesProvider
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.useCompositeAnalysis
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.diagnostics.KotlinSuppressCache
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.sumByLong
internal val LOG = Logger.getInstance(KotlinCacheService::class.java)
data class PlatformAnalysisSettingsImpl(
val platform: TargetPlatform,
val sdk: Sdk?,
val isAdditionalBuiltInFeaturesSupported: Boolean,
) : PlatformAnalysisSettings
object CompositeAnalysisSettings : PlatformAnalysisSettings
fun createPlatformAnalysisSettings(
project: Project,
platform: TargetPlatform,
sdk: Sdk?,
isAdditionalBuiltInFeaturesSupported: Boolean
) = if (project.useCompositeAnalysis)
CompositeAnalysisSettings
else
PlatformAnalysisSettingsImpl(platform, sdk, isAdditionalBuiltInFeaturesSupported)
class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
override fun getResolutionFacade(element: KtElement): ResolutionFacade {
val file = element.fileForElement()
if (file.isScript()) {
// Scripts support seem to modify some of the important aspects via file user data without triggering PsiModificationTracker.
// If in doubt, run ScriptDefinitionsOrderTestGenerated
val settings = file.getModuleInfo().platformSettings(TargetPlatformDetector.getPlatform(file))
return getFacadeToAnalyzeFile(file, settings)
} else {
return CachedValuesManager.getCachedValue(file) {
val settings = file.getModuleInfo().platformSettings(TargetPlatformDetector.getPlatform(file))
CachedValueProvider.Result(
getFacadeToAnalyzeFile(file, settings),
PsiModificationTracker.MODIFICATION_COUNT
)
}
}
}
override fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade {
val files = getFilesForElements(elements)
if (files.size == 1) return getResolutionFacade(files.single())
val platform = TargetPlatformDetector.getPlatform(files.first())
// it is quite suspicious that we take first().moduleInfo, while there might be multiple files of different kinds (e.g.
// some might be "special", see case chasing in [getFacadeToAnalyzeFiles] later
val settings = files.first().getModuleInfo().platformSettings(platform)
return getFacadeToAnalyzeFiles(files, settings)
}
// Implementation note: currently, it provides platform-specific view on common sources via plain creation of
// separate GlobalFacade even when CompositeAnalysis is enabled.
//
// Because GlobalFacade retains a lot of memory and is cached per-platform, calling this function with non-simple TargetPlatforms
// (e.g. with {JVM, Android}, {JVM_1.6, JVM_1.8}, etc.) might lead to explosive growth of memory consumption, so such calls are
// logged as errors currently and require immediate attention.
override fun getResolutionFacadeWithForcedPlatform(elements: List<KtElement>, platform: TargetPlatform): ResolutionFacade {
val files = getFilesForElements(elements)
val moduleInfo = files.first().getModuleInfo()
val settings = PlatformAnalysisSettingsImpl(platform, moduleInfo.sdk, moduleInfo.supportsAdditionalBuiltInsMembers(project))
if (!canGetFacadeWithForcedPlatform(elements, files, moduleInfo, platform)) {
// Fallback to facade without forced platform
return getResolutionFacade(elements)
}
// Note that there's no need to switch on project.useCompositeAnalysis
// - For SEPARATE analysis, using 'PlatformAnalysisSettingsImpl' is totally OK, and actually that's what we'd create normally
//
// - For COMPOSITE analysis, we intentionally want to use 'PlatformAnalysisSettingsImpl' to re-analyze code in separate
// platform-specific facade, even though normally we'd create CompositeAnalysisSettings.
// Some branches in [getFacadeToAnalyzeFile] in such case will be effectively dead due to [canGetFacadeWithForcedPlatform]
// (e.g. everything script-related), but, for example, special-files are still needed, so one can't just skip straight to
// [getResolutionFacadeByModuleInfoAndSettings] instead
return getFacadeToAnalyzeFiles(files, settings)
}
private fun canGetFacadeWithForcedPlatform(
elements: List<KtElement>,
files: List<KtFile>,
moduleInfo: IdeaModuleInfo,
platform: TargetPlatform
): Boolean {
val specialFiles = files.filterNotInProjectSource(moduleInfo)
val scripts = specialFiles.filterScripts()
return when {
platform.size > 1 -> {
LOG.error(
"Getting resolution facade with non-trivial platform $platform is strongly discouraged,\n" +
"as it can lead to heavy memory consumption. Facade with non-forced platform will be used instead."
)
false
}
moduleInfo is ScriptDependenciesInfo || moduleInfo is ScriptDependenciesSourceInfo -> {
LOG.error(
"Getting resolution facade for ScriptDependencies is not supported\n" +
"Requested elements: $elements\n" +
"Files for requested elements: $files\n" +
"Module info for the first file: $moduleInfo"
)
false
}
scripts.isNotEmpty() -> {
LOG.error(
"Getting resolution facade with forced platform is not supported for scripts\n" +
"Requested elements: $elements\n" +
"Files for requested elements: $files\n" +
"Among them, following are scripts: $scripts"
)
false
}
else -> true
}
}
private fun getFilesForElements(elements: List<KtElement>): List<KtFile> {
return elements.map {
it.fileForElement()
}.distinct()
}
private fun KtElement.fileForElement() = try {
// in theory `containingKtFile` is `@NotNull` but in practice EA-114080
@Suppress("USELESS_ELVIS")
containingKtFile ?: throw IllegalStateException("containingKtFile was null for $this of ${this.javaClass}")
} catch (e: Exception) {
if (e is ControlFlowException) throw e
throw KotlinExceptionWithAttachments("Couldn't get containingKtFile for ktElement", e)
.withPsiAttachment("element", this)
.withPsiAttachment("file", this.containingFile)
.withAttachment("original", e.message)
}
override fun getSuppressionCache(): KotlinSuppressCache = kotlinSuppressCache.value
private val globalFacadesPerPlatformAndSdk: SLRUCache<PlatformAnalysisSettings, GlobalFacade> =
object : SLRUCache<PlatformAnalysisSettings, GlobalFacade>(2 * 3 * 2, 2 * 3 * 2) {
override fun createValue(settings: PlatformAnalysisSettings): GlobalFacade {
return GlobalFacade(settings)
}
}
private val facadeForScriptDependenciesForProject = createFacadeForScriptDependencies(ScriptDependenciesInfo.ForProject(project))
private fun createFacadeForScriptDependencies(
dependenciesModuleInfo: ScriptDependenciesInfo
): ProjectResolutionFacade {
val sdk = dependenciesModuleInfo.sdk
val platform = JvmPlatforms.defaultJvmPlatform // TODO: Js scripts?
val settings = createPlatformAnalysisSettings(project, platform, sdk, true)
val dependenciesForScriptDependencies = listOf(
LibraryModificationTracker.getInstance(project),
ProjectRootModificationTracker.getInstance(project),
ScriptDependenciesModificationTracker.getInstance(project)
)
val scriptFile = (dependenciesModuleInfo as? ScriptDependenciesInfo.ForFile)?.scriptFile
val relatedModules = scriptFile?.let { ScriptAdditionalIdeaDependenciesProvider.getRelatedModules(it, project) }
val globalFacade =
if (relatedModules?.isNotEmpty() == true) {
facadeForModules(settings)
} else {
getOrBuildGlobalFacade(settings).facadeForSdk
}
val globalContext = globalFacade.globalContext.contextWithCompositeExceptionTracker(project, "facadeForScriptDependencies")
return ProjectResolutionFacade(
"facadeForScriptDependencies",
resolverForScriptDependenciesName,
project, globalContext, settings,
reuseDataFrom = globalFacade,
allModules = dependenciesModuleInfo.dependencies(),
//TODO: provide correct trackers
dependencies = dependenciesForScriptDependencies,
moduleFilter = { it == dependenciesModuleInfo },
invalidateOnOOCB = true
)
}
private inner class GlobalFacade(settings: PlatformAnalysisSettings) {
private val sdkContext = GlobalContext(resolverForSdkName)
private val moduleFilters = GlobalFacadeModuleFilters(project)
val facadeForSdk = ProjectResolutionFacade(
"facadeForSdk", "$resolverForSdkName with settings=$settings",
project, sdkContext, settings,
moduleFilter = moduleFilters::sdkFacadeFilter,
dependencies = listOf(
LibraryModificationTracker.getInstance(project),
ProjectRootModificationTracker.getInstance(project)
),
invalidateOnOOCB = false,
reuseDataFrom = null
)
private val librariesContext = sdkContext.contextWithCompositeExceptionTracker(project, resolverForLibrariesName)
val facadeForLibraries = ProjectResolutionFacade(
"facadeForLibraries", "$resolverForLibrariesName with settings=$settings",
project, librariesContext, settings,
reuseDataFrom = facadeForSdk,
moduleFilter = moduleFilters::libraryFacadeFilter,
invalidateOnOOCB = false,
dependencies = listOf(
LibraryModificationTracker.getInstance(project),
ProjectRootModificationTracker.getInstance(project)
)
)
private val modulesContext = librariesContext.contextWithCompositeExceptionTracker(project, resolverForModulesName)
val facadeForModules = ProjectResolutionFacade(
"facadeForModules", "$resolverForModulesName with settings=$settings",
project, modulesContext, settings,
reuseDataFrom = facadeForLibraries,
moduleFilter = moduleFilters::moduleFacadeFilter,
dependencies = listOf(
LibraryModificationTracker.getInstance(project),
ProjectRootModificationTracker.getInstance(project)
),
invalidateOnOOCB = true
)
}
private fun IdeaModuleInfo.platformSettings(targetPlatform: TargetPlatform) = createPlatformAnalysisSettings(
[email protected], targetPlatform, sdk,
supportsAdditionalBuiltInsMembers([email protected])
)
private fun facadeForModules(settings: PlatformAnalysisSettings) =
getOrBuildGlobalFacade(settings).facadeForModules
private fun librariesFacade(settings: PlatformAnalysisSettings) =
getOrBuildGlobalFacade(settings).facadeForLibraries
@Synchronized
private fun getOrBuildGlobalFacade(settings: PlatformAnalysisSettings) =
globalFacadesPerPlatformAndSdk[settings]
// explicitSettings allows to override the "innate" settings of the files' moduleInfo
// This can be useful, if the module is common, but we want to create a facade to
// analyze that module from the platform (e.g. JVM) point of view
private fun createFacadeForFilesWithSpecialModuleInfo(
files: Set<KtFile>,
explicitSettings: PlatformAnalysisSettings? = null
): ProjectResolutionFacade {
// we assume that all files come from the same module
val targetPlatform = files.map { TargetPlatformDetector.getPlatform(it) }.toSet().single()
val specialModuleInfo = files.map(KtFile::getModuleInfo).toSet().single()
val settings = explicitSettings ?: specialModuleInfo.platformSettings(specialModuleInfo.platform)
// Dummy files created e.g. by J2K do not receive events.
val dependencyTrackerForSyntheticFileCache = if (files.all { it.originalFile != it }) {
ModificationTracker { files.sumByLong { it.outOfBlockModificationCount } }
} else ModificationTracker { files.sumByLong { it.modificationStamp } }
val resolverDebugName =
"$resolverForSpecialInfoName $specialModuleInfo for files ${files.joinToString { it.name }} for platform $targetPlatform"
fun makeProjectResolutionFacade(
debugName: String,
globalContext: GlobalContextImpl,
reuseDataFrom: ProjectResolutionFacade? = null,
moduleFilter: (IdeaModuleInfo) -> Boolean = { true },
allModules: Collection<IdeaModuleInfo>? = null
): ProjectResolutionFacade {
return ProjectResolutionFacade(
debugName,
resolverDebugName,
project,
globalContext,
settings,
syntheticFiles = files,
reuseDataFrom = reuseDataFrom,
moduleFilter = moduleFilter,
dependencies = listOf(dependencyTrackerForSyntheticFileCache),
invalidateOnOOCB = true,
allModules = allModules
)
}
return when {
specialModuleInfo is ModuleSourceInfo -> {
val dependentModules = specialModuleInfo.getDependentModules()
val modulesFacade = facadeForModules(settings)
val globalContext =
modulesFacade.globalContext.contextWithCompositeExceptionTracker(
project,
"facadeForSpecialModuleInfo (ModuleSourceInfo)"
)
makeProjectResolutionFacade(
"facadeForSpecialModuleInfo (ModuleSourceInfo)",
globalContext,
reuseDataFrom = modulesFacade,
moduleFilter = { it in dependentModules }
)
}
specialModuleInfo is ScriptModuleInfo -> {
val facadeForScriptDependencies = createFacadeForScriptDependencies(
ScriptDependenciesInfo.ForFile(project, specialModuleInfo.scriptFile, specialModuleInfo.scriptDefinition)
)
val globalContext = facadeForScriptDependencies.globalContext.contextWithCompositeExceptionTracker(
project,
"facadeForSpecialModuleInfo (ScriptModuleInfo)"
)
makeProjectResolutionFacade(
"facadeForSpecialModuleInfo (ScriptModuleInfo)",
globalContext,
reuseDataFrom = facadeForScriptDependencies,
allModules = specialModuleInfo.dependencies(),
moduleFilter = { it == specialModuleInfo }
)
}
specialModuleInfo is ScriptDependenciesInfo -> facadeForScriptDependenciesForProject
specialModuleInfo is ScriptDependenciesSourceInfo -> {
val globalContext =
facadeForScriptDependenciesForProject.globalContext.contextWithCompositeExceptionTracker(
project,
"facadeForSpecialModuleInfo (ScriptDependenciesSourceInfo)"
)
makeProjectResolutionFacade(
"facadeForSpecialModuleInfo (ScriptDependenciesSourceInfo)",
globalContext,
reuseDataFrom = facadeForScriptDependenciesForProject,
allModules = specialModuleInfo.dependencies(),
moduleFilter = { it == specialModuleInfo }
)
}
specialModuleInfo is LibrarySourceInfo || specialModuleInfo === NotUnderContentRootModuleInfo -> {
val librariesFacade = librariesFacade(settings)
val debugName = "facadeForSpecialModuleInfo (LibrarySourceInfo or NotUnderContentRootModuleInfo)"
val globalContext = librariesFacade.globalContext.contextWithCompositeExceptionTracker(project, debugName)
makeProjectResolutionFacade(
debugName,
globalContext,
reuseDataFrom = librariesFacade,
moduleFilter = { it == specialModuleInfo }
)
}
specialModuleInfo.isLibraryClasses() -> {
//NOTE: this code should not be called for sdk or library classes
// currently the only known scenario is when we cannot determine that file is a library source
// (file under both classes and sources root)
LOG.warn("Creating cache with synthetic files ($files) in classes of library $specialModuleInfo")
val globalContext = GlobalContext("facadeForSpecialModuleInfo for file under both classes and root")
makeProjectResolutionFacade(
"facadeForSpecialModuleInfo for file under both classes and root",
globalContext
)
}
else -> throw IllegalStateException("Unknown IdeaModuleInfo ${specialModuleInfo::class.java}")
}
}
private val kotlinSuppressCache: CachedValue<KotlinSuppressCache> = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<KotlinSuppressCache>(
object : KotlinSuppressCache() {
override fun getSuppressionAnnotations(annotated: PsiElement): List<AnnotationDescriptor> {
if (annotated !is KtAnnotated) return emptyList()
if (annotated.annotationEntries.none {
it.calleeExpression?.text?.endsWith(SUPPRESS_ANNOTATION_SHORT_NAME) == true
}
) {
// Avoid running resolve heuristics
// TODO: Check aliases in imports
return emptyList()
}
val context =
when (annotated) {
is KtFile -> {
annotated.fileAnnotationList?.analyze(BodyResolveMode.PARTIAL)
?: return emptyList()
}
is KtModifierListOwner -> {
annotated.modifierList?.analyze(BodyResolveMode.PARTIAL)
?: return emptyList()
}
else ->
annotated.analyze(BodyResolveMode.PARTIAL)
}
val annotatedDescriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated)
if (annotatedDescriptor != null) {
return annotatedDescriptor.annotations.toList()
}
return annotated.annotationEntries.mapNotNull {
context.get(
BindingContext.ANNOTATION,
it
)
}
}
},
LibraryModificationTracker.getInstance(project),
PsiModificationTracker.MODIFICATION_COUNT
)
},
false
)
private val specialFilesCacheProvider = CachedValueProvider {
// NOTE: computations inside createFacadeForFilesWithSpecialModuleInfo depend on project root structure
// so we additionally drop the whole slru cache on change
CachedValueProvider.Result(
object : SLRUCache<Pair<Set<KtFile>, PlatformAnalysisSettings>, ProjectResolutionFacade>(2, 3) {
override fun createValue(filesAndSettings: Pair<Set<KtFile>, PlatformAnalysisSettings>) =
createFacadeForFilesWithSpecialModuleInfo(filesAndSettings.first, filesAndSettings.second)
},
LibraryModificationTracker.getInstance(project),
ProjectRootModificationTracker.getInstance(project)
)
}
private fun getFacadeForSpecialFiles(files: Set<KtFile>, settings: PlatformAnalysisSettings): ProjectResolutionFacade {
val cachedValue: SLRUCache<Pair<Set<KtFile>, PlatformAnalysisSettings>, ProjectResolutionFacade> =
CachedValuesManager.getManager(project).getCachedValue(project, specialFilesCacheProvider)
// In Upsource, we create multiple instances of KotlinCacheService, which all access the same CachedValue instance (UP-8046)
// This is so because class name of provider is used as a key when fetching cached value, see CachedValueManager.getKeyForClass.
// To avoid race conditions, we can't use any local lock to access the cached value contents.
return cachedValue.getOrCreateValue(files to settings)
}
private val scriptsCacheProvider = CachedValueProvider {
CachedValueProvider.Result(
object : SLRUCache<Set<KtFile>, ProjectResolutionFacade>(10, 5) {
override fun createValue(files: Set<KtFile>) = createFacadeForFilesWithSpecialModuleInfo(files)
},
LibraryModificationTracker.getInstance(project),
ProjectRootModificationTracker.getInstance(project),
ScriptDependenciesModificationTracker.getInstance(project)
)
}
private fun getFacadeForScripts(files: Set<KtFile>): ProjectResolutionFacade {
val cachedValue: SLRUCache<Set<KtFile>, ProjectResolutionFacade> =
CachedValuesManager.getManager(project).getCachedValue(project, scriptsCacheProvider)
return cachedValue.getOrCreateValue(files)
}
private fun <K, V> SLRUCache<K, V>.getOrCreateValue(key: K): V =
synchronized(this) {
this.getIfCached(key)
} ?: run {
// do actual value calculation out of any locks
// trade-off: several instances could be created, but only one would be used
val newValue = this.createValue(key)!!
synchronized(this) {
val cached = this.getIfCached(key)
cached ?: run {
this.put(key, newValue)
newValue
}
}
}
private fun getFacadeToAnalyzeFiles(files: Collection<KtFile>, settings: PlatformAnalysisSettings): ResolutionFacade {
val moduleInfo = files.first().getModuleInfo()
val specialFiles = files.filterNotInProjectSource(moduleInfo)
val scripts = specialFiles.filterScripts()
if (scripts.isNotEmpty()) {
val projectFacade = getFacadeForScripts(scripts)
return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(scripts, moduleInfo, settings)
}
if (specialFiles.isNotEmpty()) {
val projectFacade = getFacadeForSpecialFiles(specialFiles, settings)
return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(specialFiles, moduleInfo, settings)
}
return getResolutionFacadeByModuleInfoAndSettings(moduleInfo, settings).createdFor(emptyList(), moduleInfo, settings)
}
private fun getFacadeToAnalyzeFile(file: KtFile, settings: PlatformAnalysisSettings): ResolutionFacade {
val moduleInfo = file.getModuleInfo()
val specialFile = file.filterNotInProjectSource(moduleInfo)
specialFile?.filterScript()?.let { script ->
val scripts = setOf(script)
val projectFacade = getFacadeForScripts(scripts)
return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(scripts, moduleInfo, settings)
}
if (specialFile != null) {
val specialFiles = setOf(specialFile)
val projectFacade = getFacadeForSpecialFiles(specialFiles, settings)
return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(specialFiles, moduleInfo, settings)
}
return getResolutionFacadeByModuleInfoAndSettings(moduleInfo, settings).createdFor(emptyList(), moduleInfo, settings)
}
override fun getResolutionFacadeByFile(file: PsiFile, platform: TargetPlatform): ResolutionFacade? {
if (!ProjectRootsUtil.isInProjectOrLibraryContent(file)) {
return null
}
assert(file !is PsiCodeFragment)
val moduleInfo = file.getModuleInfo()
return getResolutionFacadeByModuleInfo(moduleInfo, platform)
}
private fun getResolutionFacadeByModuleInfo(moduleInfo: IdeaModuleInfo, platform: TargetPlatform): ResolutionFacade {
val settings = moduleInfo.platformSettings(platform)
return getResolutionFacadeByModuleInfoAndSettings(moduleInfo, settings)
}
private fun getResolutionFacadeByModuleInfoAndSettings(
moduleInfo: IdeaModuleInfo,
settings: PlatformAnalysisSettings
): ResolutionFacade {
val projectFacade = when (moduleInfo) {
is ScriptDependenciesInfo.ForProject,
is ScriptDependenciesSourceInfo.ForProject -> facadeForScriptDependenciesForProject
is ScriptDependenciesInfo.ForFile -> createFacadeForScriptDependencies(moduleInfo)
else -> facadeForModules(settings)
}
return ModuleResolutionFacadeImpl(projectFacade, moduleInfo)
}
override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, platform: TargetPlatform): ResolutionFacade? =
(moduleInfo as? IdeaModuleInfo)?.let { getResolutionFacadeByModuleInfo(it, platform) }
override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, settings: PlatformAnalysisSettings): ResolutionFacade? {
val ideaModuleInfo = moduleInfo as? IdeaModuleInfo ?: return null
return getResolutionFacadeByModuleInfoAndSettings(ideaModuleInfo, settings)
}
private fun Collection<KtFile>.filterNotInProjectSource(moduleInfo: IdeaModuleInfo): Set<KtFile> =
mapNotNullTo(mutableSetOf()) { it.filterNotInProjectSource(moduleInfo) }
private fun KtFile.filterNotInProjectSource(moduleInfo: IdeaModuleInfo): KtFile? {
val contextFile = if (this is KtCodeFragment) this.getContextFile() else this
return contextFile?.takeIf {
!ProjectRootsUtil.isInProjectSource(it) || !moduleInfo.contentScope().contains(it)
}
}
private fun Collection<KtFile>.filterScripts(): Set<KtFile> =
mapNotNullTo(mutableSetOf()) { it.filterScript() }
private fun KtFile.filterScript(): KtFile? {
val contextFile = if (this is KtCodeFragment) this.getContextFile() else this
return contextFile?.takeIf { it.isScript() }
}
private fun KtFile.isScript(): Boolean {
val contextFile = if (this is KtCodeFragment) this.getContextFile() else this
return contextFile?.isScript() ?: false
}
private fun KtCodeFragment.getContextFile(): KtFile? {
val contextElement = context ?: return null
val contextFile = (contextElement as? KtElement)?.containingKtFile
?: throw AssertionError("Analyzing kotlin code fragment of type ${this::class.java} with java context of type ${contextElement::class.java}")
return if (contextFile is KtCodeFragment) contextFile.getContextFile() else contextFile
}
private companion object {
private val SUPPRESS_ANNOTATION_SHORT_NAME = StandardNames.FqNames.suppress.shortName().identifier
}
}
fun IdeaModuleInfo.supportsAdditionalBuiltInsMembers(project: Project): Boolean {
return IDELanguageSettingsProvider
.getLanguageVersionSettings(this, project)
.supportsFeature(LanguageFeature.AdditionalBuiltInsMembers)
}
val IdeaModuleInfo.sdk: Sdk? get() = dependencies().firstIsInstanceOrNull<SdkInfo>()?.sdk
|
apache-2.0
|
bc384411770b1c51226b15735b85a532
| 48.723438 | 158 | 0.675989 | 6.519771 | false | false | false | false |
SDS-Studios/ScoreKeeper
|
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Stopwatch.kt
|
1
|
4329
|
package io.github.sdsstudios.ScoreKeeper
import android.content.Context
import android.graphics.Color
import android.os.SystemClock
import android.preference.PreferenceManager
import android.support.v7.widget.AppCompatButton
import android.util.AttributeSet
import io.github.sdsstudios.ScoreKeeper.Activity.SettingsActivity
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by sds2001 on 21/10/17.
*/
class Stopwatch(context: Context,
attrs: AttributeSet? = null)
: AppCompatButton(context, attrs) {
companion object {
private val TIME_FORMAT: SimpleDateFormat
get() {
val dateFormat = SimpleDateFormat("hh:mm:ss:S", Locale.US)
dateFormat.timeZone = TimeZone.getTimeZone("UTC")
return dateFormat
}
private val TIME_DECIMAL_FORMAT = DecimalFormat("00")
private val DELAY_MILLS: Long = 100
private val BLINK_DELAY_MILLS: Long = 500
fun convertTimeToLong(time: String): Long =
TIME_FORMAT.parse(time).time
}
//colors
private val mStartColor: Int = resources.getColor(R.color.start)
private val mPausedColor: Int = resources.getColor(R.color.stop)
private val mTransparent: Int = Color.TRANSPARENT
private val mDisabledColor: Int = textColors.defaultColor
private val mBlinkEnabled: Boolean = PreferenceManager
.getDefaultSharedPreferences(context)
.getBoolean(SettingsActivity.KEY_BLINK_STOPWATCH, true)
private val mTickRunnable = object : Runnable {
override fun run() {
if (!mIsPaused) {
updateText(SystemClock.elapsedRealtime())
postDelayed(this, DELAY_MILLS)
}
}
}
private val mBlinkRunnable = object : Runnable {
var isRed = false
override fun run() {
setTextColor(if (isRed) mTransparent else mPausedColor)
if (mBlinkEnabled) {
isRed = !isRed
postDelayed(this, BLINK_DELAY_MILLS)
}
}
}
private var mIsPaused = true
private var mBase: Long = 0L
private var mTimeWhenStopped: Long = 0L
private lateinit var mOnTickListener: OnTickListener
fun init(startingTime: String, onTickListener: OnTickListener, disable: Boolean) {
mTimeWhenStopped = -convertTimeToLong(startingTime)
text = startingTime
this.mOnTickListener = onTickListener
if (disable) {
disable()
} else {
if (mIsPaused) setTextColor(mPausedColor) else setTextColor(mStartColor)
}
}
fun pause() {
if (!mIsPaused) {
toggle()
}
}
fun start() {
if (mIsPaused) {
toggle()
}
}
fun disable() {
pause()
removeCallbacks(mBlinkRunnable)
setTextColor(mDisabledColor)
}
private fun format(time: Int) = TIME_DECIMAL_FORMAT.format(time)
private fun updateText(now: Long) {
val timeElapsed = now - mBase
val hours = (timeElapsed / (3600 * 1000)).toInt()
var remaining = (timeElapsed % (3600 * 1000)).toInt()
val mins = remaining / (60 * 1000)
remaining %= (60 * 1000)
val secs = remaining / 1000
remaining %= 1000
val milliseconds = timeElapsed.toInt() % 1000 / 100
val text = "${format(hours)}:${format(mins)}:${format(secs)}:$milliseconds"
setText(text)
mOnTickListener.onStopwatchTick(text)
}
fun toggle() {
mIsPaused = !mIsPaused
if (!mIsPaused) {
mBase = mTimeWhenStopped + SystemClock.elapsedRealtime()
removeCallbacks(mBlinkRunnable)
setTextColor(mStartColor)
} else {
mTimeWhenStopped = mBase - SystemClock.elapsedRealtime()
postDelayed(mBlinkRunnable, 0)
}
updateRunning()
}
private fun updateRunning() {
if (!mIsPaused) {
updateText(SystemClock.elapsedRealtime())
postDelayed(mTickRunnable, DELAY_MILLS)
} else {
removeCallbacks(mTickRunnable)
}
}
interface OnTickListener {
fun onStopwatchTick(time: String)
}
}
|
gpl-3.0
|
8ca90bcf31b54a3dbaaa2d4626efa1e0
| 26.75641 | 86 | 0.613768 | 4.788717 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertPropertyGetterToInitializerIntention.kt
|
4
|
2133
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.endOffset
class ConvertPropertyGetterToInitializerIntention : SelfTargetingIntention<KtPropertyAccessor>(
KtPropertyAccessor::class.java, KotlinBundle.lazyMessage("convert.property.getter.to.initializer")
) {
override fun isApplicableTo(element: KtPropertyAccessor, caretOffset: Int): Boolean {
if (!element.isGetter || element.singleExpression() == null) return false
val property = element.parent as? KtProperty ?: return false
if (property.hasInitializer()
|| property.receiverTypeReference != null
|| property.containingClass()?.isInterface() == true
|| (property.descriptor as? PropertyDescriptor)?.isExpect == true
) return false
return true
}
override fun applyTo(element: KtPropertyAccessor, editor: Editor?) {
val property = element.parent as? KtProperty ?: return
val commentSaver = CommentSaver(property)
property.initializer = element.singleExpression()
property.deleteChildRange(property.initializer?.nextSibling, element)
editor?.caretModel?.moveToOffset(property.endOffset)
commentSaver.restore(property)
}
}
private fun KtPropertyAccessor.singleExpression(): KtExpression? = when (val bodyExpression = bodyExpression) {
is KtBlockExpression -> (bodyExpression.statements.singleOrNull() as? KtReturnExpression)?.returnedExpression
else -> bodyExpression
}
|
apache-2.0
|
b110308d85cc2e532809647da1432713
| 46.4 | 158 | 0.761369 | 5.090692 | false | false | false | false |
android/compose-samples
|
Crane/app/src/main/java/androidx/compose/samples/crane/home/HomeFeatures.kt
|
1
|
4694
|
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.home
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.samples.crane.R
import androidx.compose.samples.crane.base.SimpleUserInput
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@Composable
fun FlySearchContent(
widthSize: WindowWidthSizeClass,
datesSelected: String,
searchUpdates: FlySearchContentUpdates
) {
val columns = when (widthSize) {
WindowWidthSizeClass.Compact -> 1
WindowWidthSizeClass.Medium -> 2
WindowWidthSizeClass.Expanded -> 4
else -> 1
}
CraneSearch(
columns,
content = {
item {
PeopleUserInput(
titleSuffix = ", Economy",
onPeopleChanged = searchUpdates.onPeopleChanged
)
}
item {
FromDestination()
}
item {
ToDestinationUserInput(
onToDestinationChanged = searchUpdates.onToDestinationChanged
)
}
item {
DatesUserInput(
datesSelected,
onDateSelectionClicked = searchUpdates.onDateSelectionClicked
)
}
}
)
}
@Composable
fun SleepSearchContent(
widthSize: WindowWidthSizeClass,
datesSelected: String,
sleepUpdates: SleepSearchContentUpdates
) {
val columns = when (widthSize) {
WindowWidthSizeClass.Compact -> 1
WindowWidthSizeClass.Medium -> 3
WindowWidthSizeClass.Expanded -> 3
else -> 1
}
CraneSearch(
columns,
content = {
item {
PeopleUserInput(onPeopleChanged = { sleepUpdates.onPeopleChanged })
}
item {
DatesUserInput(
datesSelected,
onDateSelectionClicked = sleepUpdates.onDateSelectionClicked
)
}
item {
SimpleUserInput(
caption = stringResource(R.string.input_select_location),
vectorImageId = R.drawable.ic_hotel
)
}
}
)
}
@Composable
fun EatSearchContent(
widthSize: WindowWidthSizeClass,
datesSelected: String,
eatUpdates: EatSearchContentUpdates
) {
val columns = when (widthSize) {
WindowWidthSizeClass.Compact -> 1
WindowWidthSizeClass.Medium -> 2
WindowWidthSizeClass.Expanded -> 4
else -> 1
}
CraneSearch(columns) {
item {
PeopleUserInput(onPeopleChanged = eatUpdates.onPeopleChanged)
}
item {
DatesUserInput(
datesSelected,
onDateSelectionClicked = eatUpdates.onDateSelectionClicked
)
}
item {
SimpleUserInput(
caption = stringResource(R.string.input_select_time),
vectorImageId = R.drawable.ic_time
)
}
item {
SimpleUserInput(
caption = stringResource(R.string.input_select_location),
vectorImageId = R.drawable.ic_restaurant
)
}
}
}
@Composable
private fun CraneSearch(
columns: Int,
content: LazyGridScope.() -> Unit
) {
LazyVerticalGrid(
modifier = Modifier.padding(start = 24.dp, top = 0.dp, end = 24.dp, bottom = 12.dp),
columns = GridCells.Fixed(columns),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
content = content
)
}
|
apache-2.0
|
7a438a1718e085c39e4a0a0d5aa6d0fe
| 29.089744 | 92 | 0.614188 | 5.209767 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/application/impl/AppUIExecutorImpl.kt
|
1
|
9514
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application.impl
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint
import com.intellij.openapi.application.constraints.Expiration
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.impl.PsiDocumentManagerBase
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.Executor
import java.util.function.BooleanSupplier
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
/**
* @author peter
* @author eldar
*/
internal class AppUIExecutorImpl private constructor(private val modality: ModalityState,
private val thread: ExecutionThread,
constraints: Array<ContextConstraint>,
cancellationConditions: Array<BooleanSupplier>,
expirableHandles: Set<Expiration>)
: AppUIExecutor,
BaseExpirableExecutorMixinImpl<AppUIExecutorImpl>(constraints, cancellationConditions, expirableHandles,
getExecutorForThread(thread, modality)) {
constructor(modality: ModalityState, thread: ExecutionThread) : this(modality, thread, emptyArray(), emptyArray(), emptySet())
companion object {
private fun getExecutorForThread(thread: ExecutionThread, modality: ModalityState): Executor {
return when (thread) {
ExecutionThread.EDT -> MyEdtExecutor(modality)
ExecutionThread.WT -> MyWtExecutor(modality)
}
}
}
private class MyWtExecutor(private val modality: ModalityState) : Executor {
override fun execute(command: Runnable) {
if (ApplicationManager.getApplication().isWriteThread
&& (ApplicationImpl.USE_SEPARATE_WRITE_THREAD
|| !TransactionGuard.getInstance().isWriteSafeModality(modality)
|| TransactionGuard.getInstance().isWritingAllowed)
&& !ModalityState.current().dominates(modality)) {
command.run()
}
else {
ApplicationManager.getApplication().invokeLaterOnWriteThread(command, modality)
}
}
}
private class MyEdtExecutor(private val modality: ModalityState) : Executor {
override fun execute(command: Runnable) {
if (ApplicationManager.getApplication().isDispatchThread
&& (!TransactionGuard.getInstance().isWriteSafeModality(modality)
|| TransactionGuard.getInstance().isWritingAllowed)
&& !ModalityState.current().dominates(modality)) {
command.run()
}
else {
ApplicationManager.getApplication().invokeLater(command, modality)
}
}
}
override fun cloneWith(constraints: Array<ContextConstraint>,
cancellationConditions: Array<BooleanSupplier>,
expirationSet: Set<Expiration>): AppUIExecutorImpl {
return AppUIExecutorImpl(modality, thread, constraints, cancellationConditions, expirationSet)
}
override fun dispatchLaterUnconstrained(runnable: Runnable) {
return when (thread) {
ExecutionThread.EDT -> ApplicationManager.getApplication().invokeLater(runnable, modality)
ExecutionThread.WT -> ApplicationManager.getApplication().invokeLaterOnWriteThread(runnable, modality)
}
}
override fun later(): AppUIExecutorImpl {
val edtEventCount = if (ApplicationManager.getApplication().isDispatchThread) IdeEventQueue.getInstance().eventCount else -1
return withConstraint(object : ContextConstraint {
@Volatile
var usedOnce: Boolean = false
override fun isCorrectContext(): Boolean {
return when (thread) {
ExecutionThread.EDT -> when (edtEventCount) {
-1 -> ApplicationManager.getApplication().isDispatchThread
else -> usedOnce || edtEventCount != IdeEventQueue.getInstance().eventCount
}
ExecutionThread.WT -> usedOnce
}
}
override fun schedule(runnable: Runnable) {
dispatchLaterUnconstrained(Runnable {
usedOnce = true
runnable.run()
})
}
override fun toString() = "later"
})
}
override fun withDocumentsCommitted(project: Project): AppUIExecutorImpl {
return withConstraint(WithDocumentsCommitted(project, modality), project)
}
@Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " +
"Use runUndoTransparentWriteAction instead.", ReplaceWith("this"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
fun inUndoTransparentAction(): AppUIExecutorImpl {
return withConstraint(object : ContextConstraint {
override fun isCorrectContext(): Boolean =
CommandProcessor.getInstance().isUndoTransparentActionInProgress
override fun schedule(runnable: Runnable) {
CommandProcessor.getInstance().runUndoTransparentAction(runnable)
}
override fun toString() = "inUndoTransparentAction"
})
}
@Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " +
"Use runWriteAction instead.", ReplaceWith("this"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
fun inWriteAction(): AppUIExecutorImpl {
return withConstraint(object : ContextConstraint {
override fun isCorrectContext(): Boolean =
ApplicationManager.getApplication().isWriteAccessAllowed
override fun schedule(runnable: Runnable) {
ApplicationManager.getApplication().runWriteAction(runnable)
}
override fun toString() = "inWriteAction"
})
}
override fun inSmartMode(project: Project): AppUIExecutorImpl {
return withConstraint(InSmartMode(project), project)
}
}
@Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " +
"Use runUndoTransparentWriteAction instead.", ReplaceWith("this"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
fun AppUIExecutor.inUndoTransparentAction(): AppUIExecutor {
return (this as AppUIExecutorImpl).inUndoTransparentAction()
}
@Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " +
"Use runWriteAction instead.", ReplaceWith("this"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
fun AppUIExecutor.inWriteAction():AppUIExecutor {
return (this as AppUIExecutorImpl).inWriteAction()
}
fun AppUIExecutor.withConstraint(constraint: ContextConstraint): AppUIExecutor {
return (this as AppUIExecutorImpl).withConstraint(constraint)
}
fun AppUIExecutor.withConstraint(constraint: ContextConstraint, parentDisposable: Disposable): AppUIExecutor {
return (this as AppUIExecutorImpl).withConstraint(constraint, parentDisposable)
}
/**
* A [context][CoroutineContext] to be used with the standard [launch], [async], [withContext] coroutine builders.
* Contains: [ContinuationInterceptor].
*/
fun AppUIExecutor.coroutineDispatchingContext(): ContinuationInterceptor {
return (this as AppUIExecutorImpl).asCoroutineDispatcher()
}
internal class WithDocumentsCommitted(private val project: Project, private val modality: ModalityState) : ContextConstraint {
override fun isCorrectContext(): Boolean {
val manager = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase
return !manager.isCommitInProgress && !manager.hasEventSystemEnabledUncommittedDocuments()
}
override fun schedule(runnable: Runnable) {
PsiDocumentManager.getInstance(project).performLaterWhenAllCommitted(modality, runnable)
}
override fun toString(): String {
val isCorrectContext = isCorrectContext()
val details = if (isCorrectContext) {
""
}
else {
val manager = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase
", isCommitInProgress()=${manager.isCommitInProgress}" +
", hasEventSystemEnabledUncommittedDocuments()=${manager.hasEventSystemEnabledUncommittedDocuments()}"
}
return "withDocumentsCommitted {isCorrectContext()=$isCorrectContext$details}"
}
}
internal class InSmartMode(private val project: Project) : ContextConstraint {
init {
check(!LightEdit.owns(project)) {
"InSmartMode can't be used in LightEdit mode, check that LightEdit.owns(project)==false before calling"
}
}
override fun isCorrectContext() = !project.isDisposed && !DumbService.isDumb(project)
override fun schedule(runnable: Runnable) {
DumbService.getInstance(project).runWhenSmart(runnable)
}
override fun toString() = "inSmartMode"
}
internal enum class ExecutionThread {
EDT, WT
}
|
apache-2.0
|
83c3b0119ed17e278de1b1f482d08a63
| 39.832618 | 158 | 0.727244 | 5.480415 | false | false | false | false |
smmribeiro/intellij-community
|
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/importing/ExternalSystemSetupProjectTestCase.kt
|
2
|
5384
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.importing
import com.intellij.ide.actions.ImportModuleAction
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDialog
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.fileChooser.impl.FileChooserFactoryImpl
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.use
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.TestActionEvent
import com.intellij.testFramework.replaceService
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.awt.Component
import java.io.File.separator
import com.intellij.openapi.externalSystem.util.use as utilUse
interface ExternalSystemSetupProjectTestCase {
data class ProjectInfo(val projectFile: VirtualFile, val modules: List<String>) {
constructor(projectFile: VirtualFile, vararg modules: String) : this(projectFile, modules.toList())
}
fun generateProject(id: String): ProjectInfo
fun getSystemId(): ProjectSystemId
fun assertDefaultProjectSettings(project: Project) {}
fun assertDefaultProjectState(project: Project) {}
fun attachProject(project: Project, projectFile: VirtualFile): Project
fun attachProjectFromScript(project: Project, projectFile: VirtualFile): Project
fun waitForImport(action: () -> Project): Project
fun openPlatformProjectFrom(projectDirectory: VirtualFile): Project {
return ProjectManagerEx.getInstanceEx()
.openProject(
projectDirectory.toNioPath(),
OpenProjectTask(
forceOpenInNewFrame = true,
useDefaultProjectAsTemplate = false,
isRefreshVfsNeeded = false
)
)!!
}
fun openProjectFrom(projectFile: VirtualFile) = Companion.openProjectFrom(projectFile)
fun importProjectFrom(projectFile: VirtualFile): Project {
return detectOpenedProject {
ImportModuleAction().perform(selectedFile = projectFile)
}
}
fun assertModules(project: Project, vararg projectInfo: ProjectInfo) {
val expectedNames = projectInfo.flatMap { it.modules }.toList().sorted()
val actual = ModuleManager.getInstance(project).modules
val actualNames = actual.map { it.name }.toList().sorted()
assertEquals(
expectedNames.joinToString(separator = System.lineSeparator()),
actualNames.joinToString(separator = System.lineSeparator())
)
}
fun AnAction.perform(project: Project? = null, selectedFile: VirtualFile? = null) {
invokeAndWaitIfNeeded {
withSelectedFileIfNeeded(selectedFile) {
actionPerformed(TestActionEvent {
when {
ExternalSystemDataKeys.EXTERNAL_SYSTEM_ID.`is`(it) -> getSystemId()
CommonDataKeys.PROJECT.`is`(it) -> project
CommonDataKeys.VIRTUAL_FILE.`is`(it) -> selectedFile
else -> null
}
})
}
}
}
private fun <R> withSelectedFileIfNeeded(selectedFile: VirtualFile?, action: () -> R): R {
if (selectedFile == null) return action()
Disposer.newDisposable().use {
ApplicationManager.getApplication().replaceService(FileChooserFactory::class.java, object : FileChooserFactoryImpl() {
override fun createFileChooser(descriptor: FileChooserDescriptor, project: Project?, parent: Component?): FileChooserDialog {
return object : FileChooserDialog {
override fun choose(toSelect: VirtualFile?, project: Project?): Array<VirtualFile> {
return choose(project, toSelect)
}
override fun choose(project: Project?, vararg toSelect: VirtualFile?): Array<VirtualFile> {
return arrayOf(selectedFile)
}
}
}
}, it)
return action()
}
}
fun cleanupProjectTestResources(project: Project) {}
fun Project.use(save: Boolean = false, action: (Project) -> Unit) {
utilUse(save) {
try {
action(this)
}
finally {
cleanupProjectTestResources(this)
}
}
}
companion object {
fun openProjectFrom(projectFile: VirtualFile): Project {
return detectOpenedProject {
invokeAndWaitIfNeeded {
ProjectUtil.openOrImport(projectFile.toNioPath())
}
}
}
private fun detectOpenedProject(action: () -> Unit): Project {
val projectManager = ProjectManager.getInstance()
val openProjects = projectManager.openProjects.toSet()
action()
return projectManager.openProjects.first { it !in openProjects }
}
}
}
|
apache-2.0
|
8af4403e0b20c64261f88bbf73f8e1ae
| 35.632653 | 140 | 0.731984 | 5.003717 | false | false | false | false |
Fotoapparat/Fotoapparat
|
fotoapparat/src/main/java/io/fotoapparat/parameter/Resolution.kt
|
1
|
808
|
package io.fotoapparat.parameter
import androidx.annotation.IntRange
/**
* Resolution. Units in pixels.
*/
data class Resolution(
@[JvmField IntRange(from = 0L)] val width: Int,
@[JvmField IntRange(from = 0L)] val height: Int
) : Parameter {
/**
* The total area this [Resolution] is covering.
*/
val area: Int get() = width * height
/**
* The aspect ratio for this size. [Float.NaN] if invalid dimensions.
*/
val aspectRatio: Float
get() = when {
width == 0 -> Float.NaN
height == 0 -> Float.NaN
else -> width.toFloat() / height
}
/**
* @return new instance of [Resolution] with width and height being swapped.
*/
fun flipDimensions(): Resolution = Resolution(height, width)
}
|
apache-2.0
|
55f6821c777d009aef6449ab9a69cb7d
| 23.484848 | 80 | 0.587871 | 4.230366 | false | false | false | false |
80998062/Fank
|
presentation/src/main/java/com/sinyuk/fanfou/viewmodel/AccountViewModel.kt
|
1
|
1395
|
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.viewmodel
import android.arch.lifecycle.ViewModel
import com.sinyuk.fanfou.domain.DO.Authorization
import com.sinyuk.fanfou.domain.repo.AccountRepository
import javax.inject.Inject
/**
* Created by sinyuk on 2017/12/6.
*
*/
class AccountViewModel @Inject constructor(private val repo: AccountRepository) : ViewModel() {
val profile = repo.accountLive()
fun authorization(account: String, password: String) = repo.authorization(account, password)
fun verifyCredentials(authorization: Authorization) = repo.verifyCredentials(authorization)
fun admins() = repo.admins()
fun delete(id: String) = repo.delete(uniqueId = id)
fun switch(newId: String) = repo.signIn(newId)
}
|
mit
|
83645c4abd41772b966f147071489dfd
| 28.702128 | 96 | 0.716846 | 3.896648 | false | false | false | false |
AMARJITVS/NoteDirector
|
app/src/main/kotlin/com/amar/notesapp/activities/PrefManager.kt
|
1
|
951
|
package com.amar.notesapp.activities
import android.content.Context
import android.content.SharedPreferences
/**
* Created by DELL on 15-10-2017.
*/
class PrefManager(context: Context) {
internal var pref: SharedPreferences
internal var editor:SharedPreferences.Editor
internal var _context:Context
// shared pref mode
internal var PRIVATE_MODE = 0
fun setFirstTimeLaunch(isFirstTime:Boolean) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime)
editor.commit()
}
fun isFirstTimeLaunch():Boolean {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true)
}
init{
this._context = context
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
editor = pref.edit()
}
companion object {
// Shared preferences file name
private val PREF_NAME = "androidhive-welcome"
private val IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch"
}
}
|
apache-2.0
|
022947384c6e52972d6340f243272447
| 28.75 | 69 | 0.685594 | 4.322727 | false | false | false | false |
CosmoRing/PokemonGoBot
|
src/main/kotlin/ink/abb/pogo/scraper/util/data/EggData.kt
|
1
|
777
|
/**
* 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.util.data
import com.pokegoapi.api.pokemon.EggPokemon
data class EggData (
var isIncubate: Boolean? = null,
var kmWalked: Double? = null,
var kmTarget: Double? = null
) {
fun buildFromEggPokemon(egg: EggPokemon): EggData {
this.isIncubate = egg.isIncubate
this.kmWalked = egg.eggKmWalked
this.kmTarget = egg.eggKmWalkedTarget
return this
}
}
|
gpl-3.0
|
4e484590c5760b5ee2274a7f3ef3787a
| 28.923077 | 97 | 0.702703 | 3.964286 | false | false | false | false |
srodrigo/Kotlin-Wars
|
core/src/main/kotlin/me/srodrigo/kotlinwars/model/people/Person.kt
|
1
|
206
|
package me.srodrigo.kotlinwars.model.people
class Person(
val birthYear: String? = null,
val eyeColor: String? = null,
val height: Int? = null,
val mass: Float? = null,
val name: String? = null)
|
mit
|
ed92308cda07adb19f8126d0ddc23d9f
| 24.75 | 43 | 0.684466 | 3.029412 | false | false | false | false |
JcMinarro/RoundKornerLayouts
|
roundkornerlayout/src/main/java/com/jcminarro/roundkornerlayout/RoundKornerRelativeLayout.kt
|
1
|
2483
|
package com.jcminarro.roundkornerlayout
import android.content.Context
import android.graphics.Canvas
import android.os.Build
import android.util.AttributeSet
import android.widget.RelativeLayout
class RoundKornerRelativeLayout
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
RelativeLayout(context, attrs, defStyleAttr) {
private val canvasRounder: CanvasRounder
init {
val array = context.obtainStyledAttributes(attrs, R.styleable.RoundKornerRelativeLayout, 0, 0)
val cornersHolder = array.getCornerRadius(
R.styleable.RoundKornerRelativeLayout_corner_radius,
R.styleable.RoundKornerRelativeLayout_top_left_corner_radius,
R.styleable.RoundKornerRelativeLayout_top_right_corner_radius,
R.styleable.RoundKornerRelativeLayout_bottom_right_corner_radius,
R.styleable.RoundKornerRelativeLayout_bottom_left_corner_radius
)
array.recycle()
canvasRounder = CanvasRounder(cornersHolder)
updateOutlineProvider(cornersHolder)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
setLayerType(LAYER_TYPE_SOFTWARE, null)
}
}
override fun onSizeChanged(currentWidth: Int, currentHeight: Int, oldWidth: Int, oldheight: Int) {
super.onSizeChanged(currentWidth, currentHeight, oldWidth, oldheight)
canvasRounder.updateSize(currentWidth, currentHeight)
}
override fun draw(canvas: Canvas) = canvasRounder.round(canvas) { super.draw(it) }
override fun dispatchDraw(canvas: Canvas) = canvasRounder.round(canvas) { super.dispatchDraw(it)}
fun setCornerRadius(cornerRadius: Float, cornerType: CornerType = CornerType.ALL) {
when (cornerType) {
CornerType.ALL -> {
canvasRounder.cornerRadius = cornerRadius
}
CornerType.TOP_LEFT -> {
canvasRounder.topLeftCornerRadius = cornerRadius
}
CornerType.TOP_RIGHT -> {
canvasRounder.topRightCornerRadius = cornerRadius
}
CornerType.BOTTOM_RIGHT -> {
canvasRounder.bottomRightCornerRadius = cornerRadius
}
CornerType.BOTTOM_LEFT -> {
canvasRounder.bottomLeftCornerRadius = cornerRadius
}
}
updateOutlineProvider(cornerRadius)
invalidate()
}
}
|
apache-2.0
|
c0bccbe0619f07b9f8c20a9ab293be8b
| 38.412698 | 102 | 0.671768 | 5.194561 | false | false | false | false |
fossasia/rp15
|
app/src/main/java/org/fossasia/openevent/general/search/SearchResultsViewModel.kt
|
1
|
15749
|
package org.fossasia.openevent.general.search
import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.PagedList
import androidx.paging.RxPagedListBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.connectivity.MutableConnectionLiveData
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventId
import org.fossasia.openevent.general.event.EventService
import org.fossasia.openevent.general.event.EventUtils
import org.fossasia.openevent.general.event.types.EventType
import org.fossasia.openevent.general.favorite.FavoriteEvent
import org.fossasia.openevent.general.search.location.SAVED_LOCATION
import org.fossasia.openevent.general.utils.DateTimeUtils
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
import java.util.Date
const val ORDER_COMPLETED_FRAGMENT = "orderCompletedFragment"
class SearchResultsViewModel(
private val eventService: EventService,
private val preference: Preference,
private val mutableConnectionLiveData: MutableConnectionLiveData,
private val resource: Resource,
private val config: PagedList.Config,
private val authHolder: AuthHolder
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableShowShimmerResults = MediatorLiveData<Boolean>()
val showShimmerResults: MediatorLiveData<Boolean> = mutableShowShimmerResults
private val mutablePagedEvents = MutableLiveData<PagedList<Event>>()
val pagedEvents: LiveData<PagedList<Event>> = mutablePagedEvents
private val mutableEventTypes = MutableLiveData<List<EventType>>()
private val mutableMessage = SingleLiveEvent<String>()
val message: LiveData<String> = mutableMessage
val eventTypes: LiveData<List<EventType>> = mutableEventTypes
val connection: LiveData<Boolean> = mutableConnectionLiveData
private val savedNextDate = DateTimeUtils.getNextDate()
private val savedNextToNextDate = DateTimeUtils.getNextToNextDate()
private val savedWeekendDate = DateTimeUtils.getWeekendDate()
private val savedWeekendNextDate = DateTimeUtils.getNextToWeekendDate()
private val savedNextMonth = DateTimeUtils.getNextMonth()
private val savedNextToNextMonth = DateTimeUtils.getNextToNextMonth()
private lateinit var sourceFactory: SearchEventsDataSourceFactory
var searchEvent: String? = null
var savedType: String? = null
var savedTime: String? = null
fun isLoggedIn() = authHolder.isLoggedIn()
fun loadEventTypes() {
compositeDisposable += eventService.getEventTypes()
.withDefaultSchedulers()
.subscribe({
mutableEventTypes.value = it
}, {
Timber.e(it, "Error fetching events types")
})
}
fun loadEvents(
location: String,
time: String,
type: String,
freeEvents: Boolean,
sortBy: String,
sessionsAndSpeakers: Boolean,
callForSpeakers: Boolean
) {
if (mutablePagedEvents.value != null) return
if (!isConnected()) return
preference.putString(SAVED_LOCATION, location)
val freeStuffFilter = if (freeEvents)
""", {
| 'name':'tickets',
| 'op':'any',
| 'val':{
| 'name':'price',
| 'op':'eq',
| 'val':'0'
| }
|}, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }
""".trimIndent()
else ""
val sessionsAndSpeakersFilter = if (sessionsAndSpeakers)
""", {
| 'name':'is-sessions-speakers-enabled',
| 'op':'eq',
| 'val':'true'
| }
""".trimIndent()
else ""
val query: String = when {
TextUtils.isEmpty(location) -> """[{
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
|}, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }]""".trimMargin().replace("'", "'")
time == "Anytime" && type == "Anything" -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
time == "Anytime" -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'event-type',
| 'op':'has',
| 'val': {
| 'name':'name',
| 'op':'eq',
| 'val':'$type'
| }
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
time == "Today" -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'starts-at',
| 'op':'ge',
| 'val':'$time%'
| }, {
| 'name':'starts-at',
| 'op':'lt',
| 'val':'$savedNextDate%'
| }, {
| 'name':'event-type',
| 'op':'has',
| 'val': {
| 'name':'name',
| 'op':'eq',
| 'val':'$type'
| }
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
time == "Tomorrow" -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'starts-at',
| 'op':'ge',
| 'val':'$savedNextDate%'
| }, {
| 'name':'starts-at',
| 'op':'lt',
| 'val':'$savedNextToNextDate%'
| }, {
| 'name':'event-type',
| 'op':'has',
| 'val': {
| 'name':'name',
| 'op':'eq',
| 'val':'$type'
| }
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
time == "This weekend" -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'starts-at',
| 'op':'ge',
| 'val':'$savedWeekendDate%'
| }, {
| 'name':'starts-at',
| 'op':'lt',
| 'val':'$savedWeekendNextDate%'
| }, {
| 'name':'event-type',
| 'op':'has',
| 'val': {
| 'name':'name',
| 'op':'eq',
| 'val':'$type'
| }
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
time == "In the next month" -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'starts-at',
| 'op':'ge',
| 'val':'$savedNextMonth%'
| }, {
| 'name':'starts-at',
| 'op':'lt',
| 'val':'$savedNextToNextMonth%'
| }, {
| 'name':'event-type',
| 'op':'has',
| 'val': {
| 'name':'name',
| 'op':'eq',
| 'val':'$type'
| }
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
else -> """[{
| 'and':[{
| 'name':'location-name',
| 'op':'ilike',
| 'val':'%$location%'
| }, {
| 'name':'name',
| 'op':'ilike',
| 'val':'%$searchEvent%'
| }, {
| 'name':'starts-at',
| 'op':'ge',
| 'val':'$time%'
| }, {
| 'name':'starts-at',
| 'op':'lt',
| 'val':'$savedNextDate%'
| }, {
| 'name':'event-type',
| 'op':'has',
| 'val': {
| 'name':'name',
| 'op':'eq',
| 'val':'$type'
| }
| }, {
| 'name':'ends-at',
| 'op':'ge',
| 'val':'%${EventUtils.getTimeInISO8601(Date())}%'
| }$freeStuffFilter
| $sessionsAndSpeakersFilter]
|}]""".trimMargin().replace("'", "\"")
}
Timber.e(query)
sourceFactory = SearchEventsDataSourceFactory(
compositeDisposable,
eventService,
query,
sortBy,
mutableShowShimmerResults
)
val eventPagedList = RxPagedListBuilder(sourceFactory, config)
.setFetchScheduler(Schedulers.io())
.buildObservable()
.cache()
compositeDisposable += eventPagedList
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.distinctUntilChanged()
.doOnSubscribe {
mutableShowShimmerResults.value = true
}.subscribe({
val currentPagedSearchEvents = mutablePagedEvents.value
if (currentPagedSearchEvents == null) {
mutablePagedEvents.value = it
} else {
currentPagedSearchEvents.addAll(it)
mutablePagedEvents.value = currentPagedSearchEvents
}
}, {
Timber.e(it, "Error fetching events")
mutableMessage.value = resource.getString(R.string.error_fetching_events_message)
})
}
fun setFavorite(event: Event, favorite: Boolean) {
if (favorite) {
addFavorite(event)
} else {
removeFavorite(event)
}
}
private fun addFavorite(event: Event) {
val favoriteEvent = FavoriteEvent(authHolder.getId(), EventId(event.id))
compositeDisposable += eventService.addFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutableMessage.value = resource.getString(R.string.add_event_to_shortlist_message)
}, {
mutableMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on adding like for event ID ${event.id}")
})
}
private fun removeFavorite(event: Event) {
val favoriteEventId = event.favoriteEventId ?: return
val favoriteEvent = FavoriteEvent(favoriteEventId, EventId(event.id))
compositeDisposable += eventService.removeFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutableMessage.value = resource.getString(R.string.remove_event_from_shortlist_message)
}, {
mutableMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on removing like for event ID ${event.id}")
})
}
fun isConnected(): Boolean = mutableConnectionLiveData.value ?: false
fun clearEvents() {
mutablePagedEvents.value = null
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
|
apache-2.0
|
6982b771a9f239825f4e5c7d5c7e576f
| 37.695332 | 103 | 0.433107 | 5.126628 | false | false | false | false |
kpspemu/kpspemu
|
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/ThreadManForUser_Vpl.kt
|
1
|
7165
|
package com.soywiz.kpspemu.hle.modules
import com.soywiz.klock.*
import com.soywiz.kmem.*
import com.soywiz.korio.async.*
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.hle.*
import com.soywiz.kpspemu.hle.error.*
import com.soywiz.kpspemu.hle.manager.*
import com.soywiz.kpspemu.mem.*
import com.soywiz.kpspemu.util.*
class ThreadManForUser_Vpl(val tmodule: ThreadManForUser) : SceSubmodule<ThreadManForUser>(tmodule) {
companion object {
const val PSP_VPL_ATTR_FIFO = 0x0000
const val PSP_VPL_ATTR_PRIORITY = 0x0100
const val PSP_VPL_ATTR_SMALLEST = 0x0200
const val PSP_VPL_ATTR_MASK_ORDER = 0x0300
const val PSP_VPL_ATTR_HIGHMEM = 0x4000
const val PSP_VPL_ATTR_KNOWN = PSP_VPL_ATTR_FIFO or PSP_VPL_ATTR_PRIORITY or PSP_VPL_ATTR_SMALLEST or PSP_VPL_ATTR_HIGHMEM
}
class PspVpl(override val id: Int) : ResourceItem {
val info = SceKernelVplInfo()
lateinit var part: MemoryPartition
data class WaitHandle(val size: Int, val signal: Signal<Unit> = Signal())
val waits = ArrayList<WaitHandle>()
fun getUpdatedInfo() = info.apply {
info.freeSize = part.getTotalFreeMemoryInt()
info.numWaitThreads = waits.size
}
suspend fun waitFree(size: Int, timeout: TimeSpan? = null) {
val wait = WaitHandle(size)
waits += wait
try {
wait.signal.waitOneOpt(timeout)
} finally {
waits -= wait
}
}
fun onFree() {
val availableMem = part.getMaxContiguousFreeMemoryInt()
for (wait in waits) {
if (availableMem >= wait.size) {
waits.remove(wait)
wait.signal(Unit)
return
}
}
}
}
val vpls = ResourceList(
name = "Vpl",
notFound = { sceKernelException(SceKernelErrors.ERROR_KERNEL_NOT_FOUND_VPOOL) }
) { PspVpl(it) }
fun sceKernelCreateVpl(name: String, part: Int, attr: Int, size: Int, param: Ptr): Int {
val vpl = vpls.alloc()
val asize = size - 0x20
vpl.info.name = name
vpl.info.attr = attr
vpl.info.poolSize = asize
vpl.part = memoryManager.userPartition.allocate(
asize, anchor = when {
attr hasFlag PSP_VPL_ATTR_HIGHMEM -> MemoryAnchor.High
else -> MemoryAnchor.Low
}
)
return vpl.id
}
private fun vpl(uid: Int) = vpls.tryGetById(uid)
?: sceKernelException(SceKernelErrors.ERROR_KERNEL_NOT_FOUND_VPOOL)
//val RegisterReader.vpl: PspVpl get() = vpl(int)
// @TODO: Wait for available space when not trying
suspend fun _sceKernelAllocateVpl(uid: Int, size: Int, outPtr: Ptr32, timeoutPtr: Ptr32, doTry: Boolean): Int {
val vpl = vpl(uid)
retry@ while (true) {
try {
if (size !in 1..vpl.info.poolSize) sceKernelException(SceKernelErrors.ERROR_KERNEL_ILLEGAL_MEMSIZE)
val ptr =
vpl.part.allocateHigh((size + 8).nextAlignedTo(8)) // 8 aligned extra bytes to track the allocation
outPtr[0] = ptr.low_i
return 0
} catch (e: OutOfMemoryError) {
//println("OutOfMemory: ${e.message}")
if (!doTry && timeoutPtr.isNotNull && timeoutPtr.get() != 0) {
//println("WAIT! timeout=$timeoutPtr :: timeout=${timeoutPtr.get()}")
try {
vpl.waitFree(size, timeoutPtr.get().microseconds)
continue@retry
} catch (e: TimeoutException) {
timeoutPtr.set(0)
return SceKernelErrors.ERROR_KERNEL_WAIT_TIMEOUT
}
} else {
return SceKernelErrors.ERROR_KERNEL_NO_MEMORY
}
}
}
}
suspend fun sceKernelAllocateVpl(uid: Int, size: Int, outPtr: Ptr32, timeoutPtr: Ptr32): Int {
//println("sceKernelAllocateVpl: $uid, $size, $outPtr, timeoutPtr=$timeoutPtr")
return _sceKernelAllocateVpl(uid, size, outPtr, timeoutPtr, doTry = false)
}
suspend fun sceKernelTryAllocateVpl(uid: Int, size: Int, outPtr: Ptr32): Int {
return _sceKernelAllocateVpl(uid, size, outPtr, Ptr32(nullPtr), doTry = true)
}
fun sceKernelReferVplStatus(uid: Int, info: PtrStruct<SceKernelVplInfo>): Int {
info.set(vpl(uid).getUpdatedInfo())
return 0
}
fun sceKernelDeleteVpl(uid: Int): Int {
val vpl = vpl(uid)
for (wait in vpl.waits) wait.signal(Unit)
vpls.freeById(uid)
return 0
}
fun sceKernelFreeVpl(uid: Int, ptr: Int): Int {
val vpl = vpl(uid)
vpl.part.getAtLow(ptr.unsigned)?.unallocate()
vpl.onFree()
return 0
}
fun sceKernelCancelVpl(cpu: CpuState): Unit = UNIMPLEMENTED(0x1D371B8A)
fun sceKernelAllocateVplCB(cpu: CpuState): Unit = UNIMPLEMENTED(0xEC0A693F)
fun registerSubmodule() = tmodule.apply {
registerFunctionInt("sceKernelCreateVpl", 0x56C039B5, since = 150) {
sceKernelCreateVpl(
istr,
int,
int,
int,
ptr
)
}
registerFunctionSuspendInt("sceKernelAllocateVpl", 0xBED27435, since = 150) {
sceKernelAllocateVpl(
int,
int,
ptr32,
ptr32
)
}
registerFunctionSuspendInt("sceKernelTryAllocateVpl", 0xAF36D708, since = 150) {
sceKernelTryAllocateVpl(
int,
int,
ptr32
)
}
registerFunctionInt("sceKernelReferVplStatus", 0x39810265, since = 150) {
sceKernelReferVplStatus(
int,
ptr(SceKernelVplInfo)
)
}
registerFunctionInt("sceKernelDeleteVpl", 0x89B3D48C, since = 150) { sceKernelDeleteVpl(int) }
registerFunctionInt("sceKernelFreeVpl", 0xB736E9FF, since = 150) { sceKernelFreeVpl(int, int) }
registerFunctionRaw("sceKernelCancelVpl", 0x1D371B8A, since = 150) { sceKernelCancelVpl(it) }
registerFunctionRaw("sceKernelAllocateVplCB", 0xEC0A693F, since = 150) { sceKernelAllocateVplCB(it) }
}
class SceKernelVplInfo(
var size: Int = SceKernelVplInfo.size,
var name: String = "",
var attr: Int = 0,
var poolSize: Int = 0,
var freeSize: Int = 0,
var numWaitThreads: Int = 0
) {
companion object : Struct<SceKernelVplInfo>(
{ SceKernelVplInfo() },
SceKernelVplInfo::size AS INT32,
SceKernelVplInfo::name AS STRINGZ(32),
SceKernelVplInfo::attr AS INT32,
SceKernelVplInfo::poolSize AS INT32,
SceKernelVplInfo::freeSize AS INT32,
SceKernelVplInfo::numWaitThreads AS INT32
)
}
}
|
mit
|
de224a745bd9bee6559c6be6dcbb5d50
| 35.005025 | 130 | 0.575017 | 4.27506 | false | false | false | false |
NephyProject/Penicillin
|
src/main/kotlin/jp/nephy/penicillin/endpoints/friends/ListUsers.kt
|
1
|
8581
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.friends
import jp.nephy.penicillin.core.request.action.CursorJsonObjectApiAction
import jp.nephy.penicillin.core.request.parameters
import jp.nephy.penicillin.core.session.get
import jp.nephy.penicillin.endpoints.Friends
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.models.cursor.CursorUsers
/**
* Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
* At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list)
*
* @param cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." The response from the API will include a previous_cursor and next_cursor to allow paging back and forth. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information.
* @param count The number of users to return per page, up to a maximum of 200.
* @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects.
* @param includeUserEntities The user object entities node will not be included when set to false.
* @param options Optional. Custom parameters of this request.
* @receiver [Friends] endpoint instance.
* @return [CursorJsonObjectApiAction] for [CursorUsers] model.
*/
fun Friends.listUsers(
cursor: Long? = null,
count: Int? = null,
skipStatus: Boolean? = null,
includeUserEntities: Boolean? = null,
vararg options: Option
) = listUsersInternal(null, null, cursor, count, skipStatus, includeUserEntities, *options)
/**
* Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
* At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list)
*
* @param userId The ID of the user for whom to return results.
* @param cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." The response from the API will include a previous_cursor and next_cursor to allow paging back and forth. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information.
* @param count The number of users to return per page, up to a maximum of 200.
* @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects.
* @param includeUserEntities The user object entities node will not be included when set to false.
* @param options Optional. Custom parameters of this request.
* @receiver [Friends] endpoint instance.
* @return [CursorJsonObjectApiAction] for [CursorUsers] model.
* @see listIdsByScreenName
* @see listIds
*/
fun Friends.listUsersByUserId(
userId: Long,
cursor: Long? = null,
count: Int? = null,
skipStatus: Boolean? = null,
includeUserEntities: Boolean? = null,
vararg options: Option
) = listUsersInternal(userId, null, cursor, count, skipStatus, includeUserEntities, *options)
/**
* Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
* At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list)
*
* @param screenName The screen name of the user for whom to return results.
* @param cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." The response from the API will include a previous_cursor and next_cursor to allow paging back and forth. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information.
* @param count The number of users to return per page, up to a maximum of 200.
* @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects.
* @param includeUserEntities The user object entities node will not be included when set to false.
* @param options Optional. Custom parameters of this request.
* @receiver [Friends] endpoint instance.
* @return [CursorJsonObjectApiAction] for [CursorUsers] model.
* @see listIdsByUserId
* @see listIds
*/
fun Friends.listUsersByScreenName(
screenName: String,
cursor: Long? = null,
count: Int? = null,
skipStatus: Boolean? = null,
includeUserEntities: Boolean? = null,
vararg options: Option
) = listUsersInternal(null, screenName, cursor, count, skipStatus, includeUserEntities, *options)
private fun Friends.listUsersInternal(
userId: Long? = null,
screenName: String? = null,
cursor: Long? = null,
count: Int? = null,
skipStatus: Boolean? = null,
includeUserEntities: Boolean? = null,
vararg options: Option
) = client.session.get("/1.1/friends/list.json") {
parameters(
"user_id" to userId,
"screen_name" to screenName,
"cursor" to cursor,
"count" to count,
"skip_status" to skipStatus,
"include_user_entities" to includeUserEntities,
*options
)
}.cursorJsonObject<CursorUsers>()
/**
* Shorthand property to [Friends.listUsers].
* @see Friends.listUsers
*/
val Friends.listUsers
get() = listUsers()
|
mit
|
30de605861bf807cfadbe3fd1774fa23
| 62.518519 | 541 | 0.75965 | 4.357215 | false | false | false | false |
google/private-compute-libraries
|
java/com/google/android/libraries/pcc/chronicle/codegen/backend/api/DaggerModuleContentsProvider.kt
|
1
|
3596
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.backend.api
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterSpec
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier
/**
* Represents a class capable of providing contents into a [TypeSpec.Builder] when generating a
* dagger module.
*/
sealed interface DaggerModuleContentsProvider {
/** Provides the contents into the [moduleSpec]. */
fun provideContentsInto(moduleSpec: TypeSpec.Builder)
/**
* A [DaggerModuleContentsProvider] which generates an `@Provides` method for a dagger module.
*
* @param name the name of the provides method.
* @param providedType the [TypeName] of the value provided by the `@Provides` method to the
* dagger dependency graph.
* @param isSingleton whether or not the `@Provides` method should also be annotated with
* `@Singleton`.
* @param isIntoSet whether or not the `@Provides` method should also be annoated with `@IntoSet`.
* @param qualifierAnnotations list of [ClassNames][ClassName] for additional dependency injection
* qualifier annotations to include on the generated method.
*/
abstract class ProvidesMethod(
val name: String,
val providedType: TypeName,
val isSingleton: Boolean,
val isIntoSet: Boolean = false,
val qualifierAnnotations: List<ClassName> = emptyList(),
) : DaggerModuleContentsProvider {
/**
* List of dependencies required for the dagger provider, as parameters for the provides method.
*/
abstract val parameters: List<ParameterSpec>
/** Provides the body of the `@Provides` method. */
abstract fun provideBody(): CodeBlock
override fun provideContentsInto(moduleSpec: TypeSpec.Builder) {
val method =
MethodSpec.methodBuilder(name)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameters(parameters)
.returns(providedType)
.addAnnotation(PROVIDES_ANNOTATION_CLASS_NAME)
.also {
if (isSingleton) it.addAnnotation(SINGLETON_ANNOTATION_CLASS_NAME)
if (isIntoSet) it.addAnnotation(INTOSET_ANNOTATION_CLASS_NAME)
qualifierAnnotations.forEach { qualifier -> it.addAnnotation(qualifier) }
}
.addCode(provideBody())
.build()
moduleSpec.addMethod(method)
}
}
companion object {
/** Dependency injection qualifier for `@PrivacyReviewed`. */
val PRIVACY_REVIEWED_QUALIFIER =
ClassName.get("com.google.android.libraries.pcc.chronicle.api.qualifier", "PrivacyReviewed")
private val PROVIDES_ANNOTATION_CLASS_NAME = ClassName.get("dagger", "Provides")
private val SINGLETON_ANNOTATION_CLASS_NAME = ClassName.get("javax.inject", "Singleton")
private val INTOSET_ANNOTATION_CLASS_NAME = ClassName.get("dagger.multibindings", "IntoSet")
}
}
|
apache-2.0
|
7318bca6e4a242d8e419b996cfccebbd
| 39.404494 | 100 | 0.724972 | 4.563452 | false | false | false | false |
facebook/fresco
|
animated-drawable/src/main/java/com/facebook/fresco/animation/drawable/KAnimatedDrawable2.kt
|
2
|
3770
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.animation.drawable
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.PixelFormat
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import com.facebook.drawable.base.DrawableWithCaches
import com.facebook.drawee.drawable.DrawableProperties
import com.facebook.fresco.animation.backend.AnimationBackend
import com.facebook.fresco.animation.frame.FrameScheduler
class KAnimatedDrawable2(private val animationBackend: AnimationBackend) :
Drawable(), Animatable, DrawableWithCaches {
private val animatedFrameScheduler = AnimationFrameScheduler(animationBackend)
private val animationListener: AnimationListener = BaseAnimationListener()
private val drawableProperties = DrawableProperties().apply { applyTo(this@KAnimatedDrawable2) }
/**
* Runnable that invalidates the drawable that will be scheduled according to the next target
* frame.
*/
private val invalidateRunnable =
object : Runnable {
override fun run() {
// Remove all potential other scheduled runnables
// (e.g. if the view has been invalidated a lot)
unscheduleSelf(this)
// Draw the next frame
invalidateSelf()
}
}
override fun draw(canvas: Canvas) {
// Render command must be in charge of working this
render(canvas)
}
override fun setAlpha(alpha: Int) {
drawableProperties.setAlpha(alpha)
animationBackend.setAlpha(alpha)
}
override fun setColorFilter(colorFilter: ColorFilter?) {
drawableProperties.setColorFilter(colorFilter)
animationBackend.setColorFilter(colorFilter)
}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun start() {
if (animationBackend.frameCount > 1) {
animatedFrameScheduler.start()
animationListener.onAnimationStart(this)
invalidateSelf()
}
}
override fun stop() {
animatedFrameScheduler.stop()
animationListener.onAnimationStop(this)
unscheduleSelf(invalidateRunnable)
}
override fun isRunning(): Boolean = animatedFrameScheduler.running
override fun dropCaches() {
animationBackend.clear()
}
override fun getIntrinsicWidth(): Int = animationBackend.intrinsicWidth
override fun getIntrinsicHeight(): Int = animationBackend.intrinsicHeight
// Render command should be placed here.
fun render(canvas: Canvas) {
var frameNumber = animatedFrameScheduler.frameToDraw()
// Check if the animation is finished and draw last frame if so
if (frameNumber == FrameScheduler.FRAME_NUMBER_DONE) {
frameNumber = animationBackend.frameCount - 1
animatedFrameScheduler.running = false
animationListener.onAnimationStop(this)
} else if (frameNumber == 0 && animatedFrameScheduler.shouldRepeatAnimation()) {
animationListener.onAnimationRepeat(this)
}
val frameDrawn = animationBackend.drawFrame(this, canvas, frameNumber)
if (frameDrawn) {
// Notify listeners that we draw a new frame and
// that the animation might be repeated
animationListener.onAnimationFrame(this, frameNumber)
animatedFrameScheduler.lastDrawnFrameNumber = frameNumber
} else {
animatedFrameScheduler.onFrameDropped()
}
val nextFrameTime = animatedFrameScheduler.nextRenderTime()
if (nextFrameTime != INVALID_FRAME_TIME) {
scheduleSelf(invalidateRunnable, nextFrameTime)
} else {
animationListener.onAnimationStop(this)
animatedFrameScheduler.running = false
}
}
}
|
mit
|
995ea65df1b48614be1ff49ef8d81832
| 32.362832 | 98 | 0.74191 | 5.108401 | false | false | false | false |
andretietz/retroauth
|
demo-android/src/main/java/com/andretietz/retroauth/demo/screen/main/SwitchAccountContract.kt
|
1
|
1526
|
package com.andretietz.retroauth.demo.screen.main
import android.accounts.Account
import android.accounts.AccountManager
import android.content.Context
import android.content.Intent
import android.webkit.CookieManager
import androidx.activity.result.contract.ActivityResultContract
import androidx.appcompat.app.AppCompatActivity
import com.andretietz.retroauth.demo.R
import com.andretietz.retroauth.demo.auth.LoginActivity
class SwitchAccountContract : ActivityResultContract<Account, Account?>() {
override fun createIntent(context: Context, input: Account?): Intent {
CookieManager.getInstance().removeAllCookies(null)
return if (input != null) {
// this method is the reason for min API 23
AccountManager.newChooseAccountIntent(
input,
null,
arrayOf(input.type),
null,
null,
null,
null
)
} else {
Intent(context, LoginActivity::class.java).also {
it.putExtra(
AccountManager.KEY_ACCOUNT_TYPE,
context.getText(R.string.authentication_ACCOUNT)
)
}
}
}
override fun parseResult(resultCode: Int, data: Intent?): Account? {
return if (resultCode == AppCompatActivity.RESULT_OK) {
val accountType = data?.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE)
val accountName = data?.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
if (accountType != null && accountName != null) {
Account(accountName, accountType)
} else null
} else null
}
}
|
apache-2.0
|
e88f44e2672fabd2d4cba442493a5e90
| 31.468085 | 77 | 0.705111 | 4.652439 | false | false | false | false |
AlmasB/FXGL
|
fxgl-io/src/main/kotlin/com/almasb/fxgl/net/Readers.kt
|
1
|
4014
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.net
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.logging.Logger
import java.io.*
/**
*
* @author Almas Baimagambetov ([email protected])
*/
interface TCPMessageReader<T> {
@Throws(Exception::class)
fun read(): T
}
// we need a factory for tcp message readers since each inpu stream is valid for a single connection
// therefore we cannot reuse the same message reader for each connection
interface TCPReaderFactory<T> {
fun create(input: InputStream): TCPMessageReader<T>
}
interface UDPMessageReader<T> {
fun read(data: ByteArray): T
}
object Readers {
private val log = Logger.get(javaClass)
private val tcpReaders = hashMapOf<Class<*>, TCPReaderFactory<*>>()
private val udpReaders = hashMapOf<Class<*>, UDPMessageReader<*>>()
init {
addTCPReader(Bundle::class.java, object : TCPReaderFactory<Bundle> {
override fun create(input: InputStream): TCPMessageReader<Bundle> = BundleTCPMessageReader(input)
})
addTCPReader(ByteArray::class.java, object : TCPReaderFactory<ByteArray> {
override fun create(input: InputStream): TCPMessageReader<ByteArray> = ByteArrayTCPMessageReader(input)
})
addTCPReader(String::class.java, object : TCPReaderFactory<String> {
override fun create(input: InputStream): TCPMessageReader<String> = StringTCPMessageReader(input)
})
addUDPReader(Bundle::class.java, BundleUDPMessageReader())
}
fun <T> addTCPReader(type: Class<T>, factory: TCPReaderFactory<T>) {
tcpReaders[type] = factory
}
fun <T> addUDPReader(type: Class<T>, reader: UDPMessageReader<T>) {
udpReaders[type] = reader
}
@Suppress("UNCHECKED_CAST")
fun <T> getTCPReader(type: Class<T>, inputStream: InputStream): TCPMessageReader<T> {
log.debug("Getting TCPMessageReader for $type")
val readerFactory = tcpReaders[type] ?: throw RuntimeException("No reader factory for type: $type")
val reader = readerFactory.create(inputStream) as TCPMessageReader<T>
log.debug("Constructed MessageReader for $type: " + reader.javaClass.simpleName)
return reader
}
@Suppress("UNCHECKED_CAST")
fun <T> getUDPReader(type: Class<T>): UDPMessageReader<T> {
log.debug("Getting UDPMessageReader for $type")
val reader = udpReaders[type] as? UDPMessageReader<T>
?: throw RuntimeException("No UDP message reader for type: $type")
log.debug("Constructed UDPMessageReader for $type: " + reader.javaClass.simpleName)
return reader
}
}
class BundleTCPMessageReader(stream: InputStream) : TCPMessageReader<Bundle> {
private val inputStream = ObjectInputStream(stream)
override fun read(): Bundle {
return inputStream.readObject() as Bundle
}
}
class ByteArrayTCPMessageReader(stream: InputStream) : TCPMessageReader<ByteArray> {
private val stream = DataInputStream(stream)
override fun read(): ByteArray {
val len = stream.readInt()
val buffer = ByteArray(len)
var bytesReadSoFar = 0
while (bytesReadSoFar != len) {
val bytesReadNow = stream.read(buffer, bytesReadSoFar, len - bytesReadSoFar)
bytesReadSoFar += bytesReadNow
}
return buffer
}
}
class StringTCPMessageReader(inputStream: InputStream) : TCPMessageReader<String> {
private val reader = ByteArrayTCPMessageReader(inputStream)
override fun read(): String {
val bytes = reader.read()
return String(bytes, Charsets.UTF_16)
}
}
class BundleUDPMessageReader : UDPMessageReader<Bundle> {
override fun read(data: ByteArray): Bundle {
ObjectInputStream(ByteArrayInputStream(data)).use {
return it.readObject() as Bundle
}
}
}
|
mit
|
04a203a3e09af9a29cc282e1abd340c7
| 28.522059 | 115 | 0.682113 | 4.545866 | false | false | false | false |
AsynkronIT/protoactor-kotlin
|
proto-actor/src/test/kotlin/actor/proto/tests/ReceiveTimeoutTests.kt
|
1
|
2146
|
package actor.proto.tests
import actor.proto.Props
import actor.proto.ReceiveTimeout
import actor.proto.Started
import actor.proto.fromFunc
import actor.proto.spawn
import org.junit.jupiter.api.Test
import java.time.Duration
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class ReceiveTimeoutTests {
@Test
fun `receive timeout received within expected time`() {
val cd = CountDownLatch(1)
val props: Props = fromFunc { msg ->
when (msg) {
is Started -> setReceiveTimeout(Duration.ofMillis(150))
is ReceiveTimeout -> cd.countDown()
}
}
spawn(props)
cd.await(1000, TimeUnit.MILLISECONDS)
}
@Test
fun `receive timeout not received within expected_time`() {
val cd = CountDownLatch(1)
val props: Props = fromFunc { msg ->
when (msg) {
is Started -> setReceiveTimeout(Duration.ofMillis(1500))
is ReceiveTimeout -> cd.countDown()
}
}
spawn(props)
cd.await(1000, TimeUnit.MILLISECONDS)
}
@Test
fun `can cancel receive timeout`() {
val cd = CountDownLatch(1)
val props: Props = fromFunc { msg ->
when (msg) {
is Started -> {
setReceiveTimeout(Duration.ofMillis(150))
cancelReceiveTimeout()
}
is ReceiveTimeout -> cd.countDown()
}
}
spawn(props)
cd.await(1000, TimeUnit.MILLISECONDS)
}
@Test
fun `can still set receive timeout after cancelling`() {
val cd = CountDownLatch(1)
val props: Props = fromFunc { msg ->
when (msg) {
is Started -> {
setReceiveTimeout(Duration.ofMillis(150))
cancelReceiveTimeout()
setReceiveTimeout(Duration.ofMillis(150))
}
is ReceiveTimeout -> cd.countDown()
}
}
spawn(props)
cd.await(1000, TimeUnit.MILLISECONDS)
}
}
|
apache-2.0
|
5d4f90092b6ac3241a443638a9f41748
| 26.164557 | 72 | 0.555452 | 4.9447 | false | true | false | false |
ajalt/clikt
|
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/exceptions.kt
|
1
|
8740
|
package com.github.ajalt.clikt.core
import com.github.ajalt.clikt.output.defaultLocalization
import com.github.ajalt.clikt.parameters.arguments.Argument
import com.github.ajalt.clikt.parameters.arguments.convert
import com.github.ajalt.clikt.parameters.options.Option
import com.github.ajalt.clikt.parameters.options.longestName
/**
* An internal error that signals Clikt to abort.
*
* @property error If true, print "Aborted" and exit with an error code. Otherwise, exit with no error code.
*/
class Abort(val error: Boolean = true) : RuntimeException()
/**
* An exception during command line processing that should be shown to the user.
*
* If calling [CliktCommand.main], these exceptions will be caught and the appropriate info will be printed.
*/
open class CliktError(message: String? = null, cause: Exception? = null) : RuntimeException(message, cause)
/**
* An exception that indicates that the command's help should be printed.
*
* Execution should be immediately halted.
*
* @property error If true, execution should halt with an error. Otherwise, execution halt with no error code.
*/
class PrintHelpMessage(val command: CliktCommand, val error: Boolean = false) : CliktError()
/**
* An exception that indicates that a message should be printed.
*
* Execution should be immediately halted.
*
* @property error If true, execution should halt with an error. Otherwise, execution halt with no error code.
*/
open class PrintMessage(message: String, val error: Boolean = false) : CliktError(message)
/**
* Indicate that that the program finished in a controlled manner, and should complete with the given [statusCode]
*/
class ProgramResult(val statusCode: Int) : CliktError()
/**
* An exception that indicates that shell completion code should be printed.
*
* Execution should be immediately halted without an error.
*
* @param forceUnixLineEndings if true, all line endings in the message should be `\n`, regardless
* of the current operating system.
*/
class PrintCompletionMessage(message: String, val forceUnixLineEndings: Boolean) : PrintMessage(message)
/**
* An internal exception that signals a usage error.
*
* The [option] and [argument] properties are used in message formatting, and can be set after the exception
* is created. If this is thrown inside a call to [convert], the [argument] or [option] value will be set
* automatically
*
* @property text Extra text to add to the message. Not all subclasses uses this.
* @property paramName The name of the parameter that caused the error. If possible, this should be set to the
* actual name used. If not set, it will be inferred from [argument] or [option] if either is set.
* @property option The option that caused this error. This may be set after the error is thrown.
* @property argument The argument that caused this error. This may be set after the error is thrown.
* @property statusCode The value to use as the exit code for the process. If you use
* [CliktCommand.main], it will pass this value to `exitProcess` after printing [message]. Defaults to 1.
*/
open class UsageError private constructor(
val text: String? = null,
var paramName: String? = null,
var option: Option? = null,
var argument: Argument? = null,
var context: Context? = null,
val statusCode: Int = 1,
) : CliktError() {
constructor(text: String, paramName: String? = null, context: Context? = null, statusCode: Int = 1)
: this(text, paramName, null, null, context, statusCode)
constructor(text: String, argument: Argument, context: Context? = null, statusCode: Int = 1)
: this(text, null, null, argument, context, statusCode)
constructor(text: String, option: Option, context: Context? = null, statusCode: Int = 1)
: this(text, null, option, null, context, statusCode)
fun helpMessage(): String = buildString {
context?.let { append(it.command.getFormattedUsage()).append("\n\n") }
append(localization.usageError(formatMessage()))
}
override val message: String? get() = formatMessage()
protected open fun formatMessage(): String = text ?: ""
protected fun inferParamName(): String = when {
paramName != null -> paramName!!
option != null -> option?.longestName() ?: ""
argument != null -> argument!!.name
else -> ""
}
protected val localization get() = context?.localization ?: defaultLocalization
}
/**
* A parameter was given the correct number of values, but of invalid format or type.
*/
class BadParameterValue : UsageError {
constructor(text: String, context: Context? = null) : super(text, null, context)
constructor(text: String, paramName: String, context: Context? = null) : super(text, paramName, context)
constructor(text: String, argument: Argument, context: Context? = null) : super(text, argument, context)
constructor(text: String, option: Option, context: Context? = null) : super(text, option, context)
override fun formatMessage(): String {
val m = text.takeUnless { it.isNullOrBlank() }
val p = inferParamName().takeIf { it.isNotBlank() }
return when {
m == null && p == null -> localization.badParameter()
m == null && p != null -> localization.badParameterWithParam(p)
m != null && p == null -> localization.badParameterWithMessage(m)
m != null && p != null -> localization.badParameterWithMessageAndParam(p, m)
else -> error("impossible")
}
}
}
/** A required option was not provided */
class MissingOption(option: Option, context: Context? = null) : UsageError("", option, context) {
override fun formatMessage() = localization.missingOption(inferParamName())
}
/** A required argument was not provided */
class MissingArgument(argument: Argument, context: Context? = null) : UsageError("", argument, context) {
override fun formatMessage() = localization.missingArgument(inferParamName())
}
/** A parameter was provided that does not exist. */
open class NoSuchParameter protected constructor(context: Context?) : UsageError("", context = context)
/** A subcommand was provided that does not exist. */
class NoSuchSubcommand(
private val givenName: String,
private val possibilities: List<String> = emptyList(),
context: Context? = null,
) : NoSuchParameter(context) {
override fun formatMessage(): String {
return localization.noSuchSubcommand(givenName, possibilities)
}
}
/** An option was provided that does not exist. */
class NoSuchOption(
private val givenName: String,
private val possibilities: List<String> = emptyList(),
context: Context? = null,
) : NoSuchParameter(context) {
override fun formatMessage(): String {
return localization.noSuchOption(givenName, possibilities)
}
}
/** An option was supplied but the number of values supplied to the option was incorrect. */
class IncorrectOptionValueCount(
option: Option,
private val givenName: String,
context: Context? = null,
) : UsageError("", option, context) {
override fun formatMessage(): String {
return localization.incorrectOptionValueCount(givenName, option!!.nvalues)
}
}
/** An argument was supplied but the number of values supplied was incorrect. */
class IncorrectArgumentValueCount(
argument: Argument,
context: Context? = null,
) : UsageError("", argument, context) {
override fun formatMessage(): String {
return localization.incorrectArgumentValueCount(inferParamName(), argument!!.nvalues)
}
}
class MutuallyExclusiveGroupException(
private val names: List<String>,
context: Context? = null,
) : UsageError("", context = context) {
init {
require(names.size > 1) { "must provide at least two names" }
}
override fun formatMessage(): String {
return localization.mutexGroupException(names.first(), names.drop(1))
}
}
/** A required configuration file was not found. */
class FileNotFound(
private val filename: String,
context: Context? = null,
) : UsageError("", context = context) {
override fun formatMessage(): String {
return localization.fileNotFound(filename)
}
}
/** A configuration file failed to parse correctly */
class InvalidFileFormat(
private val filename: String,
message: String,
private val lineno: Int? = null,
context: Context? = null,
) : UsageError(message, context = context) {
override fun formatMessage(): String {
return when (lineno) {
null -> localization.invalidFileFormat(filename, text!!)
else -> localization.invalidFileFormat(filename, lineno, text!!)
}
}
}
|
apache-2.0
|
34bac9a23d3ff0b608160ed56aba3f1d
| 38.017857 | 114 | 0.70103 | 4.346096 | false | false | false | false |
nickthecoder/tickle
|
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/resources/ResourceType.kt
|
1
|
4054
|
/*
Tickle
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.tickle.editor.resources
import uk.co.nickthecoder.tickle.*
import uk.co.nickthecoder.tickle.editor.FXCoderStub
import uk.co.nickthecoder.tickle.editor.ScriptStub
import uk.co.nickthecoder.tickle.events.Input
import uk.co.nickthecoder.tickle.graphics.Texture
import uk.co.nickthecoder.tickle.resources.*
import uk.co.nickthecoder.tickle.sound.Sound
import java.io.File
enum class ResourceType(val label: String, val graphicName: String) {
ANY("Resource", "folder2.png"),
GAME_INFO("Game Info", "gameInfo.png"),
PREFERENCES("Editor Preferences", "preferences.png"),
API_Documentation("API Documentation", "api.png"),
TEXTURE("Texture", "texture.png"),
POSE("Pose", "pose.png"),
COSTUME("Costume", "costume.png"),
COSTUME_GROUP("Costume Group", "costumeGroup.png"),
LAYOUT("Layout", "layout.png"),
INPUT("Input", "input.png"),
FONT("Font", "font.png"),
SOUND("Sound", "sound.png"),
SCENE_DIRECTORY("Scene Directory", "folder.png"),
SCENE("Scene", "scene.png"),
SCRIPT_DIRECTORY("Script Directory", "folder.png"),
SCRIPT("Script", "script.png"),
FXCODER_DIRECTORY("Script Directory", "folder.png"),
FXCODER("FXCoder Script", "fxcoder.png");
fun canCreate(): Boolean = this != ANY && this != GAME_INFO && this != PREFERENCES
fun findResource(name: String): Any? {
val resources = Resources.instance
return when (this) {
TEXTURE -> resources.textures.find(name)
POSE -> resources.poses.find(name)
COSTUME -> resources.costumes.find(name)
COSTUME_GROUP -> resources.costumeGroups.find(name)
LAYOUT -> resources.layouts.find(name)
INPUT -> resources.inputs.find(name)
FONT -> resources.fontResources.find(name)
SOUND -> resources.sounds.find(name)
SCENE -> {
val file = resources.scenePathToFile(name)
if (file.exists()) {
SceneStub(file)
} else {
null
}
}
SCRIPT -> {
val file = File(Resources.instance.scriptDirectory(), name)
if (file.exists()) {
ScriptStub(file)
} else {
null
}
}
FXCODER -> {
val file = File(Resources.instance.fxcoderDirectory(), name)
if (file.exists()) {
FXCoderStub(file)
} else {
null
}
}
else -> null
}
}
companion object {
fun resourceType(resource: Any): ResourceType? {
return when (resource) {
is GameInfo -> GAME_INFO
is EditorPreferences -> PREFERENCES
is Texture -> TEXTURE
is Pose -> POSE
is Costume -> COSTUME
is CostumeGroup -> COSTUME_GROUP
is Layout -> LAYOUT
is Input -> INPUT
is FontResource -> FONT
is Sound -> SOUND
is SceneResource -> SCENE
is SceneStub -> SCENE
is ScriptStub -> SCRIPT
is FXCoderStub -> FXCODER
else -> null
}
}
}
}
|
gpl-3.0
|
bc5c5c60eb3c5363f6e36705a414aead
| 34.252174 | 86 | 0.580414 | 4.570462 | false | false | false | false |
luhaoaimama1/AndroidZone
|
JavaTest_Zone/src/a_b_改善/PageKotlin.kt
|
1
|
1609
|
package a_b_改善
/**
* Created by fuzhipeng on 2018/11/13.
*
* page页面为问题
*/
fun main(args: Array<String>) {
// println("==:${Page.HOME.isHome()}")
// println(Page.values()[Page.values().indexOf(Page.HOME)])
// println("==:${Page.STICKY.isHome()}")
// Translates.values().forEach {
// println("name:${it.chinese} \t aaa:${it.name} ")
// }
Translates.valueOf("FEMALE").let {
println("name:${it.chinese} \t aaa:${it.name} ")
}
}
/**
* val pageIndex: Int。已经被 枚举代替了
* @param traceString 页面埋点用的字符串
* @param pageFrom 页面from 上报的数字
*/
enum class Page(val traceString: String, val pageFrom: String) {
HOME("home", "10"),
STICKY("sticky", "11"),
other("other", "-1");
fun isHome() = (this == HOME)
}
enum class Translates(val chinese: String) {
// 男性:MALE,女性:FEMALE
MALE("男性"),
FEMALE("女性"),
// 。会阴区:PERINEUM,
// 右大腿:RIGHTTHIGH,
// 右膝盖:RIGHTKNEE,
// 右小腿:RIGHTCALF,
// 左大腿: LEFTTHIGH,
// 左膝盖:LEFTKNEE,
// 左小腿:LEFTCALF,
// 右足:RIGHTFOOT,
// 左足: LEFTFOOT,
// 腰部:WAIST,
// 臀部:HIP
// ,骶部:CROTCH
PERINEUM("会阴区"),
RIGHTTHIGH("右大腿"),
RIGHTKNEE("右膝盖"),
RIGHTCALF("右小腿"),
LEFTTHIGH("左大腿"),
LEFTKNEE("左膝盖"),
LEFTCALF("左小腿"),
RIGHTFOOT("右足"),
LEFTFOOT("左足"),
WAIST("腰部"),
HIP("臀部"),
CROTCH("骶部")
}
|
epl-1.0
|
c8420a380422d9cb48c4b91daa5bc4d8
| 18.314286 | 64 | 0.553664 | 2.549057 | false | false | false | false |
square/kotlinpoet
|
kotlinpoet/src/test/java/com/squareup/kotlinpoet/LambdaTypeNameTest.kt
|
1
|
5458
|
/*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.kotlinpoet
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.KModifier.VARARG
import javax.annotation.Nullable
import kotlin.test.Test
@OptIn(ExperimentalKotlinPoetApi::class)
class LambdaTypeNameTest {
@Retention(AnnotationRetention.RUNTIME)
annotation class HasSomeAnnotation
@HasSomeAnnotation
inner class IsAnnotated
@Test fun receiverWithoutAnnotationHasNoParens() {
val typeName = LambdaTypeName.get(
receiver = Int::class.asClassName(),
parameters = listOf(),
returnType = Unit::class.asTypeName(),
)
assertThat(typeName.toString()).isEqualTo("kotlin.Int.() -> kotlin.Unit")
}
@Test fun receiverWithAnnotationHasParens() {
val annotation = IsAnnotated::class.java.getAnnotation(HasSomeAnnotation::class.java)
val typeName = LambdaTypeName.get(
receiver = Int::class.asClassName().copy(
annotations = listOf(AnnotationSpec.get(annotation, includeDefaultValues = true)),
),
parameters = listOf(),
returnType = Unit::class.asTypeName(),
)
assertThat(typeName.toString()).isEqualTo(
"(@com.squareup.kotlinpoet.LambdaTypeNameTest.HasSomeAnnotation kotlin.Int).() -> kotlin.Unit",
)
}
@Test fun contextReceiver() {
val typeName = LambdaTypeName.get(
receiver = Int::class.asTypeName(),
parameters = listOf(),
returnType = Unit::class.asTypeName(),
contextReceivers = listOf(STRING),
)
assertThat(typeName.toString()).isEqualTo(
"context(kotlin.String) kotlin.Int.() -> kotlin.Unit",
)
}
@Test fun functionWithMultipleContextReceivers() {
val typeName = LambdaTypeName.get(
Int::class.asTypeName(),
listOf(),
Unit::class.asTypeName(),
listOf(STRING, BOOLEAN),
)
assertThat(typeName.toString()).isEqualTo(
"context(kotlin.String, kotlin.Boolean) kotlin.Int.() -> kotlin.Unit",
)
}
@Test fun functionWithGenericContextReceiver() {
val genericType = TypeVariableName("T")
val typeName = LambdaTypeName.get(
Int::class.asTypeName(),
listOf(),
Unit::class.asTypeName(),
listOf(genericType),
)
assertThat(typeName.toString()).isEqualTo(
"context(T) kotlin.Int.() -> kotlin.Unit",
)
}
@Test fun functionWithAnnotatedContextReceiver() {
val annotatedType = STRING.copy(annotations = listOf(AnnotationSpec.get(FunSpecTest.TestAnnotation())))
val typeName = LambdaTypeName.get(
Int::class.asTypeName(),
listOf(),
Unit::class.asTypeName(),
listOf(annotatedType),
)
assertThat(typeName.toString()).isEqualTo(
"context(@com.squareup.kotlinpoet.FunSpecTest.TestAnnotation kotlin.String) kotlin.Int.() -> kotlin.Unit",
)
}
@Test fun paramsWithAnnotationsForbidden() {
assertThrows<IllegalArgumentException> {
LambdaTypeName.get(
parameters = arrayOf(
ParameterSpec.builder("foo", Int::class)
.addAnnotation(Nullable::class)
.build(),
),
returnType = Unit::class.asTypeName(),
)
}.hasMessageThat().isEqualTo("Parameters with annotations are not allowed")
}
@Test fun paramsWithModifiersForbidden() {
assertThrows<IllegalArgumentException> {
LambdaTypeName.get(
parameters = arrayOf(
ParameterSpec.builder("foo", Int::class)
.addModifiers(VARARG)
.build(),
),
returnType = Unit::class.asTypeName(),
)
}.hasMessageThat().isEqualTo("Parameters with modifiers are not allowed")
}
@Test fun paramsWithDefaultValueForbidden() {
assertThrows<IllegalArgumentException> {
LambdaTypeName.get(
parameters = arrayOf(
ParameterSpec.builder("foo", Int::class)
.defaultValue("42")
.build(),
),
returnType = Unit::class.asTypeName(),
)
}.hasMessageThat().isEqualTo("Parameters with default values are not allowed")
}
@Test fun lambdaReturnType() {
val returnTypeName = LambdaTypeName.get(
parameters = arrayOf(Int::class.asTypeName()),
returnType = Unit::class.asTypeName(),
)
val typeName = LambdaTypeName.get(
parameters = arrayOf(Int::class.asTypeName()),
returnType = returnTypeName,
)
assertThat(typeName.toString())
.isEqualTo("(kotlin.Int) -> ((kotlin.Int) -> kotlin.Unit)")
}
@Test fun lambdaParameterType() {
val parameterTypeName = LambdaTypeName.get(
parameters = arrayOf(Int::class.asTypeName()),
returnType = Int::class.asTypeName(),
)
val typeName = LambdaTypeName.get(
parameters = arrayOf(parameterTypeName),
returnType = Unit::class.asTypeName(),
)
assertThat(typeName.toString())
.isEqualTo("((kotlin.Int) -> kotlin.Int) -> kotlin.Unit")
}
}
|
apache-2.0
|
a1647a14f85931637aa50484056a3e2e
| 30.918129 | 112 | 0.670392 | 4.684979 | false | true | false | false |
waicool20/SKrypton
|
src/main/kotlin/com/waicool20/skrypton/jni/objects/SKryptonKeyEvent.kt
|
1
|
4750
|
/*
* The MIT License (MIT)
*
* Copyright (c) SKrypton by waicool20
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.waicool20.skrypton.jni.objects
import com.waicool20.skrypton.enums.Key
import com.waicool20.skrypton.enums.KeyEventType
import com.waicool20.skrypton.enums.KeyboardModifiers
import com.waicool20.skrypton.jni.CPointer
/**
* An event which indicates that a key action occurred.
*/
class SKryptonKeyEvent private constructor(pointer: Long) : SKryptonEvent(pointer) {
private companion object {
private external fun initialize_N(
type: Int,
key: Long,
modifiers: Long,
character: String,
autoRepeat: Boolean,
count: Int
): Long
}
/**
* This constructor takes a [Key] and other parameters and constructs a [SKryptonKeyEvent].
*
* @param type Type of key event.
* @param key Key that was pressed in the event.
* @param modifiers Modifiers that were involved in the event.
* @param autoRepeat Whether the event was auto repeating (Long press of the key).
* @param count Number of times the event repeated.
*/
constructor(
type: KeyEventType,
key: Key,
modifiers: KeyboardModifiers = KeyboardModifiers.NoModifier,
autoRepeat: Boolean = false,
count: Int = 1
) : this(initialize_N(
type.id, key.code, modifiers.value, key.code.toChar().toString(), autoRepeat, count
))
/**
* This constructor takes a [Char] and other parameters and constructs a [SKryptonKeyEvent].
*
* @param type Type of key event.
* @param char Character that was typed in the event.
* @param modifiers Modifiers that were involved in the event.
* @param autoRepeat Whether the event was auto repeating (Long press of the key).
* @param count Number of times the event repeated.
*/
constructor(
type: KeyEventType,
char: Char,
modifiers: KeyboardModifiers = KeyboardModifiers.NoModifier,
autoRepeat: Boolean = false,
count: Int = 1
) : this(initialize_N(
type.id, Key.getForCode(char.toLong()).code, modifiers.value, char.toString(), autoRepeat, count
))
/**
* Same as [Char] constructor except that it accepts a single character [String].
*
* @param type Type of key event.
* @param char String that was typed in the event.
* @param modifiers Modifiers that were involved in the event.
* @param autoRepeat Whether the event was auto repeating (Long press of the key).
* @param count Number of times the event repeated.
*
* @throws IllegalArgumentException If [char] is not a single character.
*/
constructor(
type: KeyEventType,
char: String,
modifiers: KeyboardModifiers = KeyboardModifiers.NoModifier,
autoRepeat: Boolean = false,
count: Int = 1
) : this(type, char.toCharArray().first(), modifiers, autoRepeat, count) {
require(char.length == 1) { "Only 1 character allowed" }
}
/**
* The key that was involved in this event.
*/
val key by lazy { Key.getForCode(getKey_N()) }
/**
* Character string that was generated when this event occurred.
*/
val character by lazy { getChar_N() }
/**
* Whether or not the event was auto repeating (Long press of the key).
*/
val isAutoRepeat by lazy { isAutoRepeat_N() }
private external fun getKey_N(): Long
private external fun getChar_N(): String
private external fun isAutoRepeat_N(): Boolean
}
|
mit
|
e99de1fbf8cf629ede842b9e678a16e4
| 37.306452 | 108 | 0.662316 | 4.59381 | false | false | false | false |
ujpv/intellij-rust
|
src/main/kotlin/org/rust/ide/typing/RustEnterInLineCommentHandler.kt
|
1
|
4492
|
package org.rust.ide.typing
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType.WHITE_SPACE
import com.intellij.util.text.CharArrayUtil
import org.rust.lang.core.psi.RustTokenElementTypes.*
import org.rust.lang.core.psi.impl.RustFile
import org.rust.lang.core.psi.util.elementType
import org.rust.lang.doc.psi.RustDocKind
class RustEnterInLineCommentHandler : EnterHandlerDelegateAdapter() {
override fun preprocessEnter(
file: PsiFile,
editor: Editor,
caretOffsetRef: Ref<Int>,
caretAdvanceRef: Ref<Int>,
dataContext: DataContext,
originalHandler: EditorActionHandler?
): Result {
// return if this is not a Rust file
if (file !is RustFile) {
return Result.Continue
}
// get current document and commit any changes, so we'll get latest PSI
val document = editor.document
PsiDocumentManager.getInstance(file.project).commitDocument(document)
val caretOffset = caretOffsetRef.get()
val text = document.charsSequence
// skip following spaces and tabs
val offset = CharArrayUtil.shiftForward(text, caretOffset, " \t")
// figure out if the caret is at the end of the line
val isEOL = offset < text.length && text[offset] == '\n'
// find the PsiElement at the caret
var elementAtCaret = file.findElementAt(offset) ?: return Result.Continue
if (isEOL && elementAtCaret.isEolWhitespace(offset)) {
// ... or the previous one if this is end-of-line whitespace
elementAtCaret = elementAtCaret.prevSibling ?: return Result.Continue
}
// check if the element at the caret is a line comment
// and extract the comment token (//, /// or //!) from the comment text
val prefix = when (elementAtCaret.elementType) {
OUTER_EOL_DOC_COMMENT -> RustDocKind.OuterEol.prefix
INNER_EOL_DOC_COMMENT -> RustDocKind.InnerEol.prefix
EOL_COMMENT -> {
// return if caret is at end of line for a non-documentation comment
if (isEOL) {
return Result.Continue
}
"//"
}
else -> return Result.Continue
}
// If caret is currently inside some prefix, do nothing.
if (offset < elementAtCaret.textOffset + prefix.length) {
return Result.Continue
}
if (text.startsWith(prefix, offset)) {
// If caret is currently at the beginning of some sequence which
// starts the same as our prefix, we are at one of these situations:
// a) // comment
// <caret>// comment
// b) // comment <caret>//comment
// Here, we don't want to insert any prefixes, as there is already one
// in code. We only have to insert space after prefix if it's missing
// and update caret position.
val afterPrefix = offset + prefix.length
if (afterPrefix < document.textLength && text[afterPrefix] != ' ') {
document.insertString(afterPrefix, " ")
}
caretOffsetRef.set(offset)
} else {
// Otherwise; add one space, if caret isn't at one
// currently, and insert prefix just before it.
val prefixToAdd = if (text[caretOffset] != ' ') prefix + ' ' else prefix
document.insertString(caretOffset, prefixToAdd)
caretAdvanceRef.set(prefixToAdd.length)
}
return Result.Default
}
// Returns true for
// ```
// fooo <caret>
//
//
// ```
//
// Returns false for
// ```
// fooo
//
// <caret>
// ```
private fun PsiElement.isEolWhitespace(caretOffset: Int): Boolean {
if (node?.elementType != WHITE_SPACE) return false
val pos = node.text.indexOf('\n')
return pos == -1 || caretOffset <= pos + textRange.startOffset
}
}
|
mit
|
9996a38e82d312a1a896dc98d635b319
| 37.393162 | 84 | 0.625557 | 4.693835 | false | false | false | false |
etesync/android
|
app/src/main/java/com/etesync/syncadapter/resource/LocalContact.kt
|
1
|
10861
|
/*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.resource
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds.GroupMembership
import android.provider.ContactsContract.RawContacts.Data
import android.text.TextUtils
import at.bitfire.vcard4android.AndroidAddressBook
import at.bitfire.vcard4android.AndroidContact
import at.bitfire.vcard4android.AndroidContactFactory
import at.bitfire.vcard4android.BatchOperation
import at.bitfire.vcard4android.CachedGroupMembership
import at.bitfire.vcard4android.Contact
import at.bitfire.vcard4android.ContactsStorageException
import at.bitfire.vcard4android.GroupMethod.GROUP_VCARDS
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.model.UnknownProperties
import ezvcard.Ezvcard
import ezvcard.VCardVersion
import java.io.ByteArrayOutputStream
import java.io.FileNotFoundException
import java.util.*
import java.util.logging.Level
class LocalContact : AndroidContact, LocalAddress {
companion object {
init {
Contact.productID = Constants.PRODID_BASE + " ez-vcard/" + Ezvcard.VERSION
}
internal const val COLUMN_HASHCODE = ContactsContract.RawContacts.SYNC3
internal val HASH_HACK = Build.VERSION_CODES.N <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < Build.VERSION_CODES.O
}
private var saveAsDirty = false // When true, the resource will be saved as dirty
internal val cachedGroupMemberships: MutableSet<Long> = HashSet()
internal val groupMemberships: MutableSet<Long> = HashSet()
override// The same now
val uuid: String?
get() = contact?.uid
override val isLocalOnly: Boolean
get() = TextUtils.isEmpty(eTag)
override val content: String
get() {
val contact: Contact
contact = this.contact!!
Logger.log.log(Level.FINE, "Preparing upload of VCard $uuid", contact)
val os = ByteArrayOutputStream()
contact.write(VCardVersion.V4_0, GROUP_VCARDS, os)
return os.toString()
}
constructor(addressBook: AndroidAddressBook<LocalContact,*>, values: ContentValues)
: super(addressBook, values) {}
constructor(addressBook: AndroidAddressBook<LocalContact, *>, contact: Contact, uuid: String?, eTag: String?)
: super(addressBook, contact, uuid, eTag) {}
fun resetDirty() {
val values = ContentValues(1)
values.put(ContactsContract.RawContacts.DIRTY, 0)
addressBook.provider?.update(rawContactSyncURI(), values, null, null)
}
override fun resetDeleted() {
val values = ContentValues(1)
values.put(ContactsContract.RawContacts.DELETED, 0)
addressBook.provider?.update(rawContactSyncURI(), values, null, null)
}
override fun clearDirty(eTag: String?) {
val values = ContentValues(3)
if (eTag != null) {
values.put(AndroidContact.COLUMN_ETAG, eTag)
}
values.put(ContactsContract.RawContacts.DIRTY, 0)
if (LocalContact.HASH_HACK) {
// workaround for Android 7 which sets DIRTY flag when only meta-data is changed
val hashCode = dataHashCode()
values.put(COLUMN_HASHCODE, hashCode)
Logger.log.finer("Clearing dirty flag with eTag = $eTag, contact hash = $hashCode")
}
addressBook.provider?.update(rawContactSyncURI(), values, null, null)
this.eTag = eTag
}
override fun legacyPrepareForUpload(fileName_: String?) {
val uid = UUID.randomUUID().toString()
val values = ContentValues(2)
val fileName = fileName_ ?: uid
values.put(AndroidContact.COLUMN_FILENAME, fileName)
values.put(AndroidContact.COLUMN_UID, uid)
addressBook.provider?.update(rawContactSyncURI(), values, null, null)
this.fileName = fileName
}
override fun prepareForUpload(fileName: String, uid: String) {
val values = ContentValues(2)
values.put(AndroidContact.COLUMN_FILENAME, fileName)
values.put(AndroidContact.COLUMN_UID, uid)
addressBook.provider?.update(rawContactSyncURI(), values, null, null)
contact?.uid = uid
this.fileName = fileName
}
override fun populateData(mimeType: String, row: ContentValues) {
when (mimeType) {
CachedGroupMembership.CONTENT_ITEM_TYPE -> cachedGroupMemberships.add(row.getAsLong(CachedGroupMembership.GROUP_ID))
GroupMembership.CONTENT_ITEM_TYPE -> groupMemberships.add(row.getAsLong(GroupMembership.GROUP_ROW_ID))
UnknownProperties.CONTENT_ITEM_TYPE -> contact?.unknownProperties = row.getAsString(UnknownProperties.UNKNOWN_PROPERTIES)
}
}
override fun insertDataRows(batch: BatchOperation) {
super.insertDataRows(batch)
if (contact?.unknownProperties != null) {
var builder = BatchOperation.CpoBuilder.newInsert(dataSyncURI())
if (id == null) {
builder = builder.withValue(UnknownProperties.RAW_CONTACT_ID, 0)
} else {
builder = builder.withValue(UnknownProperties.RAW_CONTACT_ID, id)
}
builder.withValue(UnknownProperties.MIMETYPE, UnknownProperties.CONTENT_ITEM_TYPE)
.withValue(UnknownProperties.UNKNOWN_PROPERTIES, contact?.unknownProperties)
batch.enqueue(builder)
}
}
fun updateAsDirty(contact: Contact): Uri {
saveAsDirty = true
return this.update(contact)
}
fun createAsDirty(): Uri {
saveAsDirty = true
return this.add()
}
override fun buildContact(builder: BatchOperation.CpoBuilder, update: Boolean) {
super.buildContact(builder, update)
builder.withValue(ContactsContract.RawContacts.DIRTY, if (saveAsDirty) 1 else 0)
}
/**
* Calculates a hash code from the contact's data (VCard) and group memberships.
* Attention: re-reads {@link #contact} from the database, discarding all changes in memory
* @return hash code of contact data (including group memberships)
*/
internal fun dataHashCode(): Int {
if (!LocalContact.HASH_HACK)
throw IllegalStateException("dataHashCode() should not be called on Android != 7")
// reset contact so that getContact() reads from database
contact = null
// groupMemberships is filled by getContact()
val dataHash = contact!!.hashCode()
val groupHash = groupMemberships.hashCode()
Logger.log.finest("Calculated data hash = $dataHash, group memberships hash = $groupHash")
return dataHash xor groupHash
}
fun updateHashCode(batch: BatchOperation?) {
if (!LocalContact.HASH_HACK)
throw IllegalStateException("updateHashCode() should not be called on Android != 7")
val values = ContentValues(1)
val hashCode = dataHashCode()
Logger.log.fine("Storing contact hash = $hashCode")
values.put(COLUMN_HASHCODE, hashCode)
if (batch == null)
addressBook.provider!!.update(rawContactSyncURI(), values, null, null)
else {
val builder = BatchOperation.CpoBuilder
.newUpdate(rawContactSyncURI())
.withValue(COLUMN_HASHCODE, hashCode)
batch.enqueue(builder)
}
}
fun getLastHashCode(): Int {
if (!LocalContact.HASH_HACK)
throw IllegalStateException("getLastHashCode() should not be called on Android != 7")
addressBook.provider!!.query(rawContactSyncURI(), arrayOf(COLUMN_HASHCODE), null, null, null)?.use { c ->
if (c.moveToNext() && !c.isNull(0))
return c.getInt(0)
}
return 0
}
fun addToGroup(batch: BatchOperation, groupID: Long) {
batch.enqueue(BatchOperation.CpoBuilder.newInsert(dataSyncURI())
.withValue(GroupMembership.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE)
.withValue(GroupMembership.RAW_CONTACT_ID, id)
.withValue(GroupMembership.GROUP_ROW_ID, groupID)
)
groupMemberships.add(groupID)
batch.enqueue(BatchOperation.CpoBuilder.newInsert(dataSyncURI())
.withValue(CachedGroupMembership.MIMETYPE, CachedGroupMembership.CONTENT_ITEM_TYPE)
.withValue(CachedGroupMembership.RAW_CONTACT_ID, id)
.withValue(CachedGroupMembership.GROUP_ID, groupID)
)
cachedGroupMemberships.add(groupID)
}
fun removeGroupMemberships(batch: BatchOperation) {
batch.enqueue(BatchOperation.CpoBuilder.newDelete(dataSyncURI())
.withSelection(
Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + " IN (?,?)",
arrayOf(id.toString(), GroupMembership.CONTENT_ITEM_TYPE, CachedGroupMembership.CONTENT_ITEM_TYPE)
)
)
groupMemberships.clear()
cachedGroupMemberships.clear()
}
/**
* Returns the IDs of all groups the contact was member of (cached memberships).
* Cached memberships are kept in sync with memberships by DAVdroid and are used to determine
* whether a membership has been deleted/added when a raw contact is dirty.
* @return set of [GroupMembership.GROUP_ROW_ID] (may be empty)
* @throws ContactsStorageException on contact provider errors
* @throws FileNotFoundException if the current contact can't be found
*/
fun getCachedGroupMemberships(): Set<Long> {
contact
return cachedGroupMemberships
}
/**
* Returns the IDs of all groups the contact is member of.
* @return set of [GroupMembership.GROUP_ROW_ID]s (may be empty)
* @throws ContactsStorageException on contact provider errors
* @throws FileNotFoundException if the current contact can't be found
*/
fun getGroupMemberships(): Set<Long> {
contact
return groupMemberships
}
// factory
object Factory: AndroidContactFactory<LocalContact> {
override fun fromProvider(addressBook: AndroidAddressBook<LocalContact, *>, values: ContentValues) =
LocalContact(addressBook, values)
}
}
|
gpl-3.0
|
cfd1110830ac7b7c8e257cb8a8fe1314
| 37.640569 | 133 | 0.668908 | 4.864695 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/fun/HungerGamesCommand.kt
|
1
|
6309
|
package net.perfectdreams.loritta.morenitta.commands.vanilla.`fun`
import net.perfectdreams.loritta.morenitta.utils.locale.Gender
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.client.statement.*
import net.dv8tion.jda.api.entities.User
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import net.perfectdreams.loritta.morenitta.utils.extensions.toJDA
import org.jsoup.Jsoup
class HungerGamesCommand(m: LorittaBot) : DiscordAbstractCommandBase(m, listOf("hungergames", "jogosvorazes", "hg"), net.perfectdreams.loritta.common.commands.CommandCategory.FUN) {
private val LOCALE_PREFIX = "commands.command.hungergames"
private val WEBSITE_URL = "https://brantsteele.net"
override fun command() = create {
loritta as LorittaBot
localizedDescription("$LOCALE_PREFIX.description")
localizedExamples("$LOCALE_PREFIX.examples")
usage {
repeat(24) {
argument(ArgumentType.USER) {}
}
}
canUseInPrivateChannel = false
executesDiscord {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "hungergames")
val users = mutableListOf<User>()
val copyOfTheGuildUserList = guild.members.map { it.user }
.toMutableList()
for (index in 0 until 24) {
users.add(user(index)?.toJDA() ?: continue)
}
// If there aren't sufficient users in the list, we are going to include some random users
copyOfTheGuildUserList.removeAll(users)
while (24 > users.size) {
if (copyOfTheGuildUserList.isEmpty())
fail(locale["$LOCALE_PREFIX.doesntHaveEnoughUsers"])
val randomUser = copyOfTheGuildUserList.random()
users.add(randomUser)
copyOfTheGuildUserList.remove(randomUser)
}
// First we load the "disclaimer" page to get the cookie
val disclaimer = loritta.http.get("$WEBSITE_URL/hungergames/disclaimer.php")
// The PHPSESSID cookie seems to be always the last one (after the __cfuid cookie)
// So we get the content after PHPSESSID= but before the ;, getting only the ID
val phpSessId = disclaimer.headers.getAll("Set-Cookie")!!.joinToString(" ")
.substringAfter("PHPSESSID=")
.substringBefore(";")
// Then we send a request to the "Agree" page, indicating we are 13 years old
loritta.http.get("$WEBSITE_URL/hungergames/agree.php") {
header("Cookie", "PHPSESSID=$phpSessId")
}
// Create a map of the user -> gender
// If no gender is specified, we default to UNKNOWN
// But because the website only has male/female, we default to male when creating the list
val profiles = users.map {
it to loritta.newSuspendedTransaction { loritta.getLorittaProfile(it.idLong)?.settings?.gender ?: Gender.UNKNOWN }
}.toMap()
// Submit our custom Hunger Games to the page
loritta.http.submitFormWithBinaryData(
"$WEBSITE_URL/hungergames/personalize-24.php",
formData {
// Season Name
append("seasonname", guild.name)
// The URL in the top right corner
append("logourl", guild.iconUrl ?: user.effectiveAvatarUrl)
// 00 (custom?)
append("existinglogo", "00")
for ((index, user) in users.withIndex()) {
val numberWithPadding = (index + 1).toString().padStart(2, '0')
// Character Name
append("cusTribute$numberWithPadding", user.name)
// Character Image
append("cusTribute${numberWithPadding}img", user.effectiveAvatarUrl)
// Character Gender
// 0 = female
// 1 = male
val gender = profiles[user] ?: Gender.UNKNOWN
if (gender == Gender.FEMALE)
append("cusTribute${numberWithPadding}gender", "0")
else
append("cusTribute${numberWithPadding}gender", "1")
// ???
append("cusTribute${numberWithPadding}custom", "000")
// Character Nickname
append("cusTribute${numberWithPadding}nickname", user.name)
// Character Image when Dead
append("cusTribute${numberWithPadding}imgBW", "BW")
}
// Unknown
append("ChangeAll", "028")
}
) {
header("Cookie", "PHPSESSID=$phpSessId")
}
// Try going to the save page
val result3 = loritta.http.get("$WEBSITE_URL/hungergames/save.php") {
header("Cookie", "PHPSESSID=$phpSessId")
}
// Get the season URL, it is inside of the #content element in a <a> tag
val jsoup = Jsoup.parse(result3.bodyAsText())
val saveLink = jsoup.getElementById("content")!!
.getElementsByTag("a")
.first()!!
.attr("href")
// Reply with the simulation URL, have fun!~
reply(
LorittaReply(
locale["$LOCALE_PREFIX.simulationCreated", saveLink],
Emotes.LORI_HAPPY
)
)
}
}
}
|
agpl-3.0
|
e35b954bd276351ff31d1203782c2366
| 43.429577 | 181 | 0.554288 | 5.351145 | false | false | false | false |
authzee/kotlin-guice
|
kotlin-guice/src/test/kotlin/dev/misfitlabs/kotlinguice4/multibindings/KotlinMultibinderSpec.kt
|
1
|
12580
|
/*
* Copyright (C) 2017 John Leacox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.misfitlabs.kotlinguice4.multibindings
import com.google.inject.Guice
import com.google.inject.Key
import com.google.inject.ProvisionException
import com.google.inject.TypeLiteral
import com.google.inject.multibindings.ProvidesIntoSet
import com.google.inject.name.Names
import com.google.inject.spi.ElementSource
import com.google.inject.util.Providers
import dev.misfitlabs.kotlinguice4.KotlinModule
import java.util.concurrent.Callable
import org.amshove.kluent.shouldEqual
import org.amshove.kluent.shouldThrow
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
/**
* @author John Leacox
*/
object KotlinMultibinderSpec : Spek({
describe("KotlinMultibinder") {
it("skips the multibinder classes in the source trace") {
val outerModule = object : KotlinModule() {
override fun configure() {
val aBinder = KotlinMultibinder.newSetBinder<A>(kotlinBinder)
aBinder.addBinding().to<AImpl>()
}
}
val injector = Guice.createInjector(outerModule)
val source = injector.getBinding(Key.get(object : TypeLiteral<Set<A>>() {}))
.source as ElementSource
val stackTraceElement = source.declaringSource as StackTraceElement
stackTraceElement.className shouldEqual outerModule::class.java.name
}
describe("#newSetBinder") {
it("binds simple types into a set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
val aBinder = KotlinMultibinder.newSetBinder<A>(kotlinBinder)
aBinder.addBinding().to<AImpl>()
aBinder.addBinding().to<B>()
val callableBinder = KotlinMultibinder.newSetBinder<Callable<A>>(kotlinBinder)
callableBinder.addBinding().to<ACallable>()
}
})
val setContainer = injector.getInstance(Key
.get(object : TypeLiteral<SetContainer<A>>() {}))
setContainer.set.size shouldEqual 2
}
it("binds complex types into a set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
val callableBinder = KotlinMultibinder.newSetBinder<Callable<A>>(kotlinBinder)
callableBinder.addBinding().to<ACallable>()
callableBinder.addBinding().to<TCallable<A>>()
val aBinder = KotlinMultibinder.newSetBinder<A>(kotlinBinder)
aBinder.addBinding().to<AImpl>()
aBinder.addBinding().to<B>()
}
})
val setContainer = injector.getInstance(Key
.get(object : TypeLiteral<SetContainer<Callable<A>>>() {}))
setContainer.set.size shouldEqual 2
}
it("forbids duplicate elements") {
val module1 = object : KotlinModule() {
override fun configure() {
val stringBinder = KotlinMultibinder.newSetBinder<String>(kotlinBinder)
stringBinder.addBinding().toProvider(Providers.of("Hello World"))
}
}
val module2 = object : KotlinModule() {
override fun configure() {
val stringBinder = KotlinMultibinder.newSetBinder<String>(kotlinBinder)
stringBinder.addBinding().toInstance("Hello World")
}
}
val injector = Guice.createInjector(module1, module2)
val getInstance = {
injector.getInstance(Key.get(object : TypeLiteral<Set<String>>() {}))
}
getInstance shouldThrow ProvisionException::class
}
it("silently ignores duplicates when using permitDuplicates") {
val module1 = object : KotlinModule() {
override fun configure() {
val stringBinder = KotlinMultibinder.newSetBinder<String>(kotlinBinder)
stringBinder.addBinding().toProvider(Providers.of("Hello World"))
}
}
val module2 = object : KotlinModule() {
override fun configure() {
val stringBinder = KotlinMultibinder.newSetBinder<String>(kotlinBinder)
stringBinder.permitDuplicates()
stringBinder.addBinding().toInstance("Hello World")
}
}
val injector = Guice.createInjector(module1, module2)
val set = injector.getInstance(Key.get(object : TypeLiteral<Set<String>>() {}))
set.size shouldEqual 1
set shouldEqual setOf("Hello World")
}
}
describe("#newAnnotatedSetBinder") {
it("binds simple types into an annotated set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
val aBinder = KotlinMultibinder
.newAnnotatedSetBinder<A, Annotated>(kotlinBinder)
aBinder.addBinding().to<AImpl>()
aBinder.addBinding().to<B>()
val unannotatedABinder = KotlinMultibinder.newSetBinder<A>(kotlinBinder)
unannotatedABinder.addBinding().to<AImpl>()
}
})
val set = injector.getInstance(Key
.get(object : TypeLiteral<Set<A>>() {}, Annotated::class.java))
set.size shouldEqual 2
}
it("binds simple types into a named set") {
val named = Names.named("A Name")
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
val aBinder = KotlinMultibinder
.newAnnotatedSetBinder<A>(kotlinBinder, named)
aBinder.addBinding().to<AImpl>()
aBinder.addBinding().to<B>()
val unannotatedABinder = KotlinMultibinder.newSetBinder<A>(kotlinBinder)
unannotatedABinder.addBinding().to<AImpl>()
}
})
val set = injector.getInstance(Key.get(object : TypeLiteral<Set<A>>() {}, named))
set.size shouldEqual 2
}
it("binds complex types into an annotated set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
val callableBinder = KotlinMultibinder
.newAnnotatedSetBinder<Callable<A>, Annotated>(kotlinBinder)
callableBinder.addBinding().to<ACallable>()
callableBinder.addBinding().to<TCallable<A>>()
val unannotatedCallableBinder = KotlinMultibinder
.newSetBinder<Callable<A>>(kotlinBinder)
unannotatedCallableBinder.addBinding().to<ACallable>()
}
})
val set = injector.getInstance(Key
.get(object : TypeLiteral<Set<Callable<A>>>() {},
Annotated::class.java))
set.size shouldEqual 2
}
}
describe("@ProvidesIntoSet") {
it("binds simple types into a set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
install(KotlinMultibindingsScanner.asModule())
}
@ProvidesIntoSet
fun provideAImpl(): A {
return AImpl()
}
@ProvidesIntoSet
fun provideB(): A {
return B()
}
@ProvidesIntoSet
fun provideACallable(): Callable<A> {
return ACallable()
}
})
val setContainer = injector.getInstance(Key
.get(object : TypeLiteral<SetContainer<A>>() {}))
setContainer.set.size shouldEqual 2
}
it("binds complex types into a set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
install(KotlinMultibindingsScanner.asModule())
}
@ProvidesIntoSet
fun provideACallable(): Callable<A> {
return ACallable()
}
@ProvidesIntoSet
fun provideTCallable(): Callable<A> {
return TCallable<A>()
}
@ProvidesIntoSet
fun provideAImpl(): A {
return AImpl()
}
})
val setContainer = injector.getInstance(Key
.get(object : TypeLiteral<SetContainer<Callable<A>>>() {}))
setContainer.set.size shouldEqual 2
}
it("binds simple types into an annotated set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
install(KotlinMultibindingsScanner.asModule())
}
@ProvidesIntoSet
@Annotated
fun provideAImpl(): A {
return AImpl()
}
@ProvidesIntoSet
@Annotated
fun provideB(): A {
return B()
}
@ProvidesIntoSet
fun provideACallable(): Callable<A> {
return ACallable()
}
})
val set = injector.getInstance(Key
.get(object : TypeLiteral<Set<A>>() {},
Annotated::class.java))
set.size shouldEqual 2
}
it("binds complex types into an annotated set") {
val injector = Guice.createInjector(object : KotlinModule() {
override fun configure() {
install(KotlinMultibindingsScanner.asModule())
}
@ProvidesIntoSet
@Annotated
fun provideAnnotatedACallable(): Callable<A> {
return ACallable()
}
@ProvidesIntoSet
@Annotated
fun provideAnnotatedTCallable(): Callable<A> {
return TCallable<A>()
}
@ProvidesIntoSet
fun provideUnannotatedACallable(): Callable<A> {
return ACallable()
}
})
val set = injector.getInstance(Key
.get(object : TypeLiteral<Set<Callable<A>>>() {},
Annotated::class.java))
set.size shouldEqual 2
}
}
}
})
|
apache-2.0
|
d4b226bd1150427a4256e4dbdfbe7b62
| 38.190031 | 102 | 0.502544 | 6.283716 | false | false | false | false |
esafirm/android-image-picker
|
imagepicker/src/main/java/com/esafirm/imagepicker/features/ImagePickerComponentsHolder.kt
|
1
|
1682
|
package com.esafirm.imagepicker.features
import android.content.Context
import com.esafirm.imagepicker.features.camera.CameraModule
import com.esafirm.imagepicker.features.camera.DefaultCameraModule
import com.esafirm.imagepicker.features.fileloader.DefaultImageFileLoader
import com.esafirm.imagepicker.features.fileloader.ImageFileLoader
import com.esafirm.imagepicker.features.imageloader.DefaultImageLoader
import com.esafirm.imagepicker.features.imageloader.ImageLoader
interface ImagePickerComponents {
val appContext: Context
val imageLoader: ImageLoader
val imageFileLoader: ImageFileLoader
val cameraModule: CameraModule
}
open class DefaultImagePickerComponents(context: Context) : ImagePickerComponents {
override val appContext: Context = context.applicationContext
override val imageLoader: ImageLoader by lazy { DefaultImageLoader() }
override val imageFileLoader: ImageFileLoader by lazy { DefaultImageFileLoader(context.applicationContext) }
override val cameraModule: CameraModule by lazy { DefaultCameraModule() }
}
object ImagePickerComponentsHolder : ImagePickerComponents {
private lateinit var internalComponents: ImagePickerComponents
override val appContext: Context
get() = internalComponents.appContext
override val imageLoader: ImageLoader
get() = internalComponents.imageLoader
override val imageFileLoader: ImageFileLoader
get() = internalComponents.imageFileLoader
override val cameraModule: CameraModule
get() = internalComponents.cameraModule
fun setInternalComponent(components: ImagePickerComponents) {
internalComponents = components
}
}
|
mit
|
9ddab6ea05777d69a63d211565f44999
| 37.25 | 112 | 0.806778 | 5.58804 | false | false | false | false |
FurhatRobotics/example-skills
|
Dog/src/main/kotlin/furhatos/app/dog/gestures/barks.kt
|
1
|
1343
|
package furhatos.app.dog.gestures
import furhatos.app.dog.utils._defineGesture
import furhatos.app.dog.utils.getAudioURL
import furhatos.gestures.BasicParams
val bark1 = _defineGesture("bark1", frameTimes = listOf(0.1), audioURL = getAudioURL("Small_dog_1_bark.wav")) {
// This empty frame needs to be here for the audio to not play twice
frame(0.1) { }
frame(0.15) {
BasicParams.SMILE_OPEN to 0.5
BasicParams.NECK_TILT to -14
}
frame(0.30) {
BasicParams.NECK_TILT to -0
}
reset(0.4)
}
val bark2 = _defineGesture("bark2", frameTimes = listOf(0.0), audioURL = getAudioURL("Small_dog_2_barks.wav")) {
// This empty frame needs to be here for the audio to not play twice
frame(0.0) { }
frame(0.15, 0.45) {
BasicParams.SMILE_OPEN to 0.5
BasicParams.NECK_TILT to -14
}
frame(0.3, 0.6) {
BasicParams.NECK_TILT to 6
}
reset(0.7)
}
val bark3 = _defineGesture("bark3", frameTimes = listOf(0.0), audioURL = getAudioURL("Small_dog_3_barks.wav")) {
// This empty frame needs to be here for the audio to not play twice
frame(0.0) { }
frame(0.15, 0.45, 0.8) {
BasicParams.SMILE_OPEN to 0.5
BasicParams.NECK_TILT to -14
}
frame(0.3, 0.65, 0.95) {
BasicParams.NECK_TILT to -6
}
reset(1.0)
}
|
mit
|
0fff8eac1bac65d1392b36bbf48a9cc1
| 24.358491 | 112 | 0.626955 | 3.130536 | false | false | false | false |
alessio-b-zak/myRivers
|
android/app/src/main/java/com/epimorphics/android/myrivers/helpers/FragmentHelper.kt
|
1
|
5761
|
package com.epimorphics.android.myrivers.helpers
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.TableRow
import android.widget.TextView
import com.epimorphics.android.myrivers.R
/**
* Helper class providing base functions used by most fragments
*
*/
abstract class FragmentHelper : Fragment() {
/**
* Used to initialise an element from a resource
*
* @param T a type of the element
* @param res a resource Id
*
* @return an element of type T
*/
fun <T : View> View.bind(@IdRes res: Int): T {
@Suppress("UNCHECKED_CAST")
return findViewById<T>(res)
}
/**
* Creates a new table row
*
* @param position row index
* @param isDoubleRow set to true if two rows act as one like in WIMSDataFragment
* @param offset set to 1 if table contains double rows but the first row is a header row
*
* @return TableRow new table row
*/
fun newTableRow(position: Int, isDoubleRow: Boolean = false, offset: Int = 0): TableRow {
val tableRow: TableRow = TableRow(context)
val lp = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT)
tableRow.layoutParams = lp
tableRow.gravity = Gravity.CENTER
tableRow.setPadding(16, 8, 16, 8)
// If isDoubleRow then set condition to alternate colors every 2 rows
val condition: Int = if (isDoubleRow) {
val inputAsDouble = (position + offset).toDouble()
(Math.floor(inputAsDouble / 2)).toInt() % 2
} else {
position % 2
}
// Set table row background
when (condition) {
0 -> {
if (Build.VERSION.SDK_INT < 21) {
tableRow.background = resources.getDrawable(R.color.tablePrimary)
} else {
tableRow.background = resources.getDrawable(R.color.tablePrimary, null)
}
}
1 -> {
if (Build.VERSION.SDK_INT < 21) {
tableRow.background = resources.getDrawable(R.color.tableSecondary)
} else {
tableRow.background = resources.getDrawable(R.color.tableSecondary, null)
}
}
}
return tableRow
}
/**
* Adds a TextView to a TableRow
*
* @param tableRow a TableRow to which to add a TextView
* @param value a String to be added to the TextView
* @param weight a weighting of the TextView in the given TableRow
* @param style a resource id of a TextView style
* @param gravity a gravity of a TextView inside a TableRow
* @param startPadding a paddingStart property of a TextView
* @param popupText a popup window text
*
*/
fun addTextView(tableRow: TableRow, value: String?, weight: Double = 1.0,
style: Int = R.style.text_view_table_child, gravity: Int = Gravity.CENTER,
startPadding: Int = 0, popupText: String = "") {
val textView: TextView = TextView(context)
val params = TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, weight.toFloat())
textView.layoutParams = params
textView.text = value
textView.gravity = gravity
// basePadding is set to a different value for mobile and tabled devices
val basePadding = context!!.resources.getDimensionPixelSize(R.dimen.table_base_padding)
textView.setPaddingRelative(basePadding + startPadding, 0, basePadding, 0)
// set the style of the TextView
if (Build.VERSION.SDK_INT < 23) {
textView.setTextAppearance(context, style)
} else {
textView.setTextAppearance(style)
}
// if popupText provided then initiate a popup window
if (popupText != "") {
textView.setOnClickListener { view: View -> displayPopupWindow(view, popupText) }
}
tableRow.addView(textView)
}
/**
* Attaches a popup window to a given view
*
* @param view a view to which a popup window is to be attached
* @param inputString a string to be shown inside a popup window
*/
fun displayPopupWindow(view: View, inputString: String) {
val layoutInflater = LayoutInflater.from(context)
val layout = layoutInflater.inflate(R.layout.popup_content, null)
// Initiate a popup window
val popup = PopupWindow(context)
popup.contentView = layout
// Set content width and height
popup.height = WindowManager.LayoutParams.WRAP_CONTENT
popup.width = WindowManager.LayoutParams.WRAP_CONTENT
// Closes the popup window when touch outside of it - when looses focus
popup.isOutsideTouchable = true
popup.isFocusable = true
// Set Text
val textView: TextView = popup.contentView.findViewById<TextView>(R.id.pop_up_window)
textView.text = inputString
// Show anchored to button
popup.setBackgroundDrawable(BitmapDrawable())
popup.showAsDropDown(view)
}
/**
* Converts a date from ISO format to Short Date format
*
* @param date date in ISO format
* @return String date in Short Date format
*/
fun simplifyDate(date: String): String {
val year = date.substring(2, 4)
val month = date.substring(5, 7)
val day = date.substring(8, 10)
return "$day/$month/$year"
}
}
|
mit
|
0d26d20b50320c7cacb28fd9470596a6
| 33.297619 | 99 | 0.630099 | 4.642224 | false | false | false | false |
sta-szek/squash-zg
|
src/main/kotlin/pl/pojo/squash/zg/model/Game.kt
|
1
|
750
|
package pl.pojo.squash.zg.model
import com.fasterxml.jackson.annotation.JsonIgnore
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.ManyToOne
import javax.persistence.Table
@Entity
@Table(name = "games")
data class Game(@Id @GeneratedValue @Column(unique = true) val id: Long = 0,
val dayOfWeek: java.time.DayOfWeek,
@Column(name = "startTime")
val from: java.time.LocalTime,
val to: java.time.LocalTime,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JsonIgnore
var user: User? = null)
|
gpl-3.0
|
7d3d46e8ec41b49387ab705ba6f64c0c
| 34.761905 | 76 | 0.68 | 4.360465 | false | false | false | false |
vhromada/Catalog-Spring
|
src/main/kotlin/cz/vhromada/catalog/web/mapper/impl/MusicMapperImpl.kt
|
1
|
1092
|
package cz.vhromada.catalog.web.mapper.impl
import cz.vhromada.catalog.entity.Music
import cz.vhromada.catalog.web.fo.MusicFO
import cz.vhromada.catalog.web.mapper.MusicMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for music.
*
* @author Vladimir Hromada
*/
@Component("webMusicMapper")
class MusicMapperImpl : MusicMapper {
override fun map(source: Music): MusicFO {
return MusicFO(id = source.id,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toString(),
note = source.note,
position = source.position)
}
override fun mapBack(source: MusicFO): Music {
return Music(id = source.id,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toInt(),
note = source.note,
position = source.position)
}
}
|
mit
|
be0d328cc5764a8857ed81270b573e3a
| 29.333333 | 60 | 0.606227 | 4.55 | false | false | false | false |
yschimke/oksocial
|
src/main/kotlin/com/baulsupp/okurl/services/lyft/LyftAuthInterceptor.kt
|
1
|
2829
|
package com.baulsupp.okurl.services.lyft
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.queryMapValue
import com.baulsupp.okurl.secrets.Secrets
import okhttp3.Credentials
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
/**
* https://developer.lyft.com/docs/authentication
*/
class LyftAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition = Oauth2ServiceDefinition(
"api.lyft.com", "Lyft API", "lyft",
"https://developer.lyft.com/docs", "https://www.lyft.com/developers/manage"
)
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token {
val clientId = Secrets.prompt("Lyft Client Id", "lyft.clientId", "", false)
val clientSecret = Secrets.prompt("Lyft Client Secret", "lyft.clientSecret", "", true)
return if (authArguments == listOf("--client")) {
LyftClientAuthFlow.login(client, clientId, clientSecret)
} else {
val scopes = Secrets.promptArray(
"Scopes", "lyft.scopes", listOf(
"public",
"rides.read",
"offline",
"rides.request",
"profile"
)
)
LyftAuthFlow.login(client, outputHandler, clientId, clientSecret, scopes)
}
}
override suspend fun validate(
client: OkHttpClient,
credentials: Oauth2Token
): ValidatedCredentials =
ValidatedCredentials(
client.queryMapValue<String>(
"https://api.lyft.com/v1/profile",
TokenValue(credentials), "id"
)
)
override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token {
val body = ("{\"grant_type\": \"refresh_token\", \"refresh_token\": \"" +
credentials.refreshToken + "\"}"
).toRequestBody("application/json".toMediaType())
val basic = Credentials.basic(credentials.clientId!!, credentials.clientSecret!!)
val request = Request.Builder().url("https://api.lyft.com/oauth/token")
.post(body)
.header("Authorization", basic)
.build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(
responseMap["access_token"] as String,
credentials.refreshToken, credentials.clientId,
credentials.clientSecret
)
}
}
|
apache-2.0
|
f8a3c52990faeb72d2cda797fcde8472
| 31.895349 | 91 | 0.715801 | 4.338957 | false | false | false | false |
collinx/susi_android
|
app/src/main/java/org/fossasia/susi/ai/skills/SkillsActivity.kt
|
1
|
6860
|
package org.fossasia.susi.ai.skills
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import org.fossasia.susi.ai.R
import android.content.Intent
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import org.fossasia.susi.ai.chat.ChatActivity
import org.fossasia.susi.ai.skills.aboutus.AboutUsFragment
import org.fossasia.susi.ai.skills.settings.ChatSettingsFragment
import org.fossasia.susi.ai.skills.skilldetails.SkillDetailsFragment
import org.fossasia.susi.ai.skills.skilllisting.SkillListingFragment
import android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT
import android.content.Context.INPUT_METHOD_SERVICE
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.EditText
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_skill_listing.*
import org.fossasia.susi.ai.rest.responses.susi.SkillData
/**
* <h1>The Skills activity.</h1>
* <h2>This activity is used to display SUSI Skills in the app.</h2>
*
* Created by mayanktripathi on 07/07/17.
*/
class SkillsActivity : AppCompatActivity() {
val TAG_SETTINGS_FRAGMENT = "SettingsFragment"
val TAG_SKILLS_FRAGMENT = "SkillsFragment"
val TAG_ABOUT_FRAGMENT = "AboutUsFragment"
private var mSearchAction: MenuItem? = null
private var isSearchOpened = false
private var edtSearch: EditText? = null
private var skills : ArrayList<Pair<String, Map<String, SkillData>>> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out)
setContentView(R.layout.activity_skills)
val skillFragment = SkillListingFragment()
skills = skillFragment.skills
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, skillFragment, TAG_SKILLS_FRAGMENT)
.addToBackStack(TAG_SKILLS_FRAGMENT)
.commit()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val menuInflater = menuInflater
menuInflater.inflate(R.menu.skills_activity_menu, menu)
return true
}
fun exitActivity() {
overridePendingTransition(R.anim.trans_right_in, R.anim.trans_right_out)
val intent = Intent(this@SkillsActivity, ChatActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
override fun onBackPressed() {
overridePendingTransition(R.anim.trans_right_in, R.anim.trans_right_out)
if (supportFragmentManager.popBackStackImmediate(TAG_SKILLS_FRAGMENT, 0)) {
title = getString(R.string.skills_activity)
} else {
finish()
exitActivity()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
R.id.menu_settings -> {
val settingsFragment = ChatSettingsFragment()
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, settingsFragment, TAG_SETTINGS_FRAGMENT)
.addToBackStack(TAG_SETTINGS_FRAGMENT)
.commit()
}
R.id.menu_about -> {
val aboutFragment = AboutUsFragment()
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, aboutFragment, TAG_ABOUT_FRAGMENT)
.addToBackStack(TAG_ABOUT_FRAGMENT)
.commit()
}
R.id.action_search -> {
handleMenuSearch();
}
}
return super.onOptionsItemSelected(item);
}
protected fun handleMenuSearch() {
val action = supportActionBar //get the actionbar
if (isSearchOpened) { //test if the search is open
action!!.setDisplayShowCustomEnabled(false) //disable a custom view inside the actionbar
action.setDisplayShowTitleEnabled(true) //show the title in the action bar
//hides the keyboard
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(edtSearch?.getWindowToken(), 0)
//add the search icon in the action bar
mSearchAction?.setIcon(resources.getDrawable(R.drawable.ic_open_search))
isSearchOpened = false
} else { //open the search entry
action!!.setDisplayShowCustomEnabled(true) //enable it to display a
// custom view in the action bar.
action.setCustomView(R.layout.search_bar)//add the custom view
action.setDisplayShowTitleEnabled(false) //hide the title
edtSearch = action.customView.findViewById(R.id.edtSearch) as EditText //the text editor
//this is a listener to do a search when the user clicks on search button
edtSearch?.setOnEditorActionListener(object : TextView.OnEditorActionListener {
override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent?): Boolean {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
doSearch((findViewById(R.id.edtSearch) as EditText).text.toString())
return true
}
return false
}
})
edtSearch?.requestFocus()
//open the keyboard focused in the edtSearch
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(edtSearch, InputMethodManager.SHOW_IMPLICIT)
//add the close icon
mSearchAction?.setIcon(resources.getDrawable(R.drawable.ic_close_search))
isSearchOpened = true
}
}
fun doSearch(query : String) {
var pos = 0
for( item in skills) {
if(query in item.first){
skillGroups.scrollToPosition(pos)
return
}
for (item2 in item.second.keys){
if( query.toLowerCase() in item2){
skillGroups.scrollToPosition(pos)
return
}
}
pos++
}
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
mSearchAction = menu?.findItem(R.id.action_search);
return super.onPrepareOptionsMenu(menu)
}
}
|
apache-2.0
|
b7e6c37619c3ebb09aa3b9979b6519ae
| 34.734375 | 100 | 0.641983 | 4.814035 | false | false | false | false |
wireapp/wire-android
|
app/src/main/kotlin/com/waz/zclient/core/network/ApiService.kt
|
1
|
2785
|
package com.waz.zclient.core.network
import com.waz.zclient.core.exception.BadRequest
import com.waz.zclient.core.exception.Cancelled
import com.waz.zclient.core.exception.Conflict
import com.waz.zclient.core.exception.EmptyResponseBody
import com.waz.zclient.core.exception.Failure
import com.waz.zclient.core.exception.Forbidden
import com.waz.zclient.core.exception.InternalServerError
import com.waz.zclient.core.exception.NetworkConnection
import com.waz.zclient.core.exception.NotFound
import com.waz.zclient.core.exception.ServerError
import com.waz.zclient.core.exception.Unauthorized
import com.waz.zclient.core.functional.Either
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response
abstract class ApiService {
abstract val networkHandler: NetworkHandler
suspend fun <T> request(default: T? = null, call: suspend () -> Response<T>): Either<Failure, T> =
withContext(Dispatchers.IO) {
return@withContext when (networkHandler.isConnected) {
true -> performRequest(call, default)
false, null -> Either.Left(NetworkConnection)
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun <T> performRequest(call: suspend () -> Response<T>, default: T? = null): Either<Failure, T> {
return try {
val response = call()
if (response.isSuccessful) {
response.body()?.let { Either.Right(it) }
?: (default?.let { Either.Right(it) } ?: Either.Left(EmptyResponseBody))
} else {
handleRequestError(response)
}
} catch (exception: Throwable) {
when (exception) {
is CancellationException -> Either.Left(Cancelled)
else -> Either.Left(ServerError)
}
}
}
private fun <T> handleRequestError(response: Response<T>): Either<Failure, T> {
return when (response.code()) {
CODE_BAD_REQUEST -> Either.Left(BadRequest)
CODE_UNAUTHORIZED -> Either.Left(Unauthorized)
CODE_FORBIDDEN -> Either.Left(Forbidden)
CODE_NOT_FOUND -> Either.Left(NotFound)
CODE_CONFLICT -> Either.Left(Conflict)
CODE_INTERNAL_SERVER_ERROR -> Either.Left(InternalServerError)
else -> Either.Left(ServerError)
}
}
companion object {
private const val CODE_BAD_REQUEST = 400
private const val CODE_UNAUTHORIZED = 401
private const val CODE_FORBIDDEN = 403
private const val CODE_NOT_FOUND = 404
private const val CODE_CONFLICT = 409
private const val CODE_INTERNAL_SERVER_ERROR = 500
}
}
|
gpl-3.0
|
089e8ac7bcd945e659c9999413fc85a3
| 39.362319 | 117 | 0.663914 | 4.521104 | false | false | false | false |
yshrsmz/monotweety
|
app/src/main/java/net/yslibrary/monotweety/App.kt
|
1
|
1866
|
package net.yslibrary.monotweety
import android.app.Application
import android.content.Context
import leakcanary.ObjectWatcher
import timber.log.Timber
import javax.inject.Inject
import kotlin.properties.Delegates
open class App : Application() {
companion object {
fun get(context: Context): App = context.applicationContext as App
fun appComponent(context: Context): AppComponent = get(context).appComponent
fun userComponent(context: Context): UserComponent {
val app = get(context)
if (app.userComponent == null) {
app.userComponent = app.appComponent.userComponent()
}
return app.userComponent!!
}
/**
* clear UserComponent
* this method should be called when user is logging out
*/
fun clearUserComponent(context: Context) {
get(context).userComponent = null
}
}
val appComponent: AppComponent by lazy {
DaggerAppComponent.factory().create(Modules.appModule(), this)
}
var userComponent: UserComponent? = null
@set:[Inject]
var lifecycleCallbacks by Delegates.notNull<App.LifecycleCallbacks>()
// inject here just to make sure that LeakCanary is initialized
@set:[Inject]
var refWatcher by Delegates.notNull<ObjectWatcher>()
override fun onCreate() {
super.onCreate()
appComponent(this).inject(this)
lifecycleCallbacks.onCreate()
Timber.d("App#onCreate")
}
override fun onTerminate() {
super.onTerminate()
Timber.d("App#onTerminate")
lifecycleCallbacks.onTerminate()
}
// FIXME: https://youtrack.jetbrains.com/issue/KT-14306
// use ApplicationLifecycleCallbacks for now
interface LifecycleCallbacks {
fun onCreate()
fun onTerminate()
}
}
|
apache-2.0
|
12d109a3fd035701eed365ae14b2c39c
| 26.441176 | 84 | 0.655949 | 5.084469 | false | false | false | false |
Ekito/koin
|
koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/ext/android/ScopeFragmentExt.kt
|
1
|
2624
|
/*
* Copyright 2017-2020 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.koin.androidx.viewmodel.ext.android
import androidx.lifecycle.ViewModel
import org.koin.androidx.scope.ScopeFragment
import org.koin.androidx.viewmodel.ViewModelOwner.Companion.from
import org.koin.androidx.viewmodel.ViewModelOwnerDefinition
import org.koin.androidx.viewmodel.scope.BundleDefinition
import org.koin.androidx.viewmodel.scope.getViewModel
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
import kotlin.reflect.KClass
/**
* ViewModel extensions to help for ViewModel
*
* @author Arnaud Giuliani
*/
inline fun <reified T : ViewModel> ScopeFragment.viewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition = { from(this, this) },
noinline parameters: ParametersDefinition? = null
): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) {
getViewModel<T>(qualifier, state, owner, parameters)
}
}
fun <T : ViewModel> ScopeFragment.viewModel(
qualifier: Qualifier? = null,
state: BundleDefinition? = null,
owner: ViewModelOwnerDefinition = { from(this, this) },
clazz: KClass<T>,
parameters: ParametersDefinition? = null
): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) { getViewModel(qualifier, state, owner, clazz, parameters) }
}
inline fun <reified T : ViewModel> ScopeFragment.getViewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition = { from(this, this) },
noinline parameters: ParametersDefinition? = null
): T {
return getViewModel(qualifier, state, owner, T::class, parameters)
}
fun <T : ViewModel> ScopeFragment.getViewModel(
qualifier: Qualifier? = null,
state: BundleDefinition? = null,
owner: ViewModelOwnerDefinition = { from(this, this) },
clazz: KClass<T>,
parameters: ParametersDefinition? = null
): T {
return scope.getViewModel(qualifier, state, owner, clazz, parameters)
}
|
apache-2.0
|
f717b356e7801ee26c2df5edab24bbe2
| 35.971831 | 103 | 0.744284 | 4.3229 | false | false | false | false |
jainaman224/Algo_Ds_Notes
|
Linear_Search/Linear_Search.kt
|
1
|
965
|
//Function For Linear Search
fun Linear_Search(list: List<Int>, Num: Int):Int {
//If number not found than return -1 otherwise return postion of that number.
var foundAt:Int = -1
for(number in 0 until list.size) {
if(list[number] == Num) {
foundAt = number
}
}
return foundAt
}
//Driver Function For Linear Search
fun main(args:Array<String>) {
val list = listOf(2, 7, 10, 45, 60, 5)
val position: Int
//Let 45 to be searched
position = Linear_Search(list, 45)
if(position == -1) {
println("Number Not Found")
}
else {
println("Number Found at position ${position + 1}")
}
//Now search for 1
val position1: Int
position1 = Linear_Search(list, 1)
if(position1 == -1) {
println("Number Not Found")
}
else {
println("Number Found at position ${position1 + 1}")
}
}
//Output:-
// Number Found at position 4
// Number Not Found
|
gpl-3.0
|
0ee3e5e42d95b7af21e14c2298948564
| 24.394737 | 81 | 0.593782 | 3.655303 | false | false | false | false |
alygin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/types/ty/TyPrimitive.kt
|
1
|
4251
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import com.intellij.psi.PsiElement
import org.rust.ide.presentation.tyToString
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.hasColonColon
import org.rust.lang.core.psi.ext.sizeExpr
import org.rust.lang.core.resolve.ImplLookup
/**
* These are "atomic" ty (not type constructors, singletons).
*
* Definition intentionally differs from the reference: we don't treat
* tuples or arrays as primitive.
*/
interface TyPrimitive : Ty {
override fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult =
UnifyResult.exactIf(this == other)
companion object {
fun fromPath(path: RsPath): TyPrimitive? {
if (path.hasColonColon) return null
if (path.parent !is RsBaseType) return null
val name = path.referenceName
val integerKind = TyInteger.Kind.values().find { it.name == name }
if (integerKind != null) return TyInteger(integerKind)
val floatKind = TyFloat.Kind.values().find { it.name == name }
if (floatKind != null) return TyFloat(floatKind)
return when (name) {
"bool" -> TyBool
"char" -> TyChar
"str" -> TyStr
else -> null
}
}
}
}
object TyBool : TyPrimitive {
override fun toString(): String = tyToString(this)
}
object TyChar : TyPrimitive {
override fun toString(): String = tyToString(this)
}
object TyUnit : TyPrimitive {
override fun toString(): String = tyToString(this)
}
/** The `!` type. E.g. `unimplemented!()` */
object TyNever : TyPrimitive {
override fun toString(): String = tyToString(this)
}
object TyStr : TyPrimitive {
override fun toString(): String = tyToString(this)
}
interface TyNumeric : TyPrimitive {
val isKindWeak: Boolean
override fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult =
UnifyResult.exactIf(this == other || javaClass == other.javaClass && (other as TyNumeric).isKindWeak)
}
class TyInteger(val kind: Kind, override val isKindWeak: Boolean = false) : TyNumeric {
companion object {
fun fromLiteral(literal: PsiElement): TyInteger {
val kind = Kind.values().find { literal.text.endsWith(it.name) }
?: inferKind(literal)
return TyInteger(kind ?: DEFAULT_KIND, kind == null)
}
/**
* Tries to infer the kind of an unsuffixed integer literal by its context.
* Fall back to the default kind if can't infer.
*/
private fun inferKind(literal: PsiElement): Kind? {
val expr = literal.parent as? RsLitExpr ?: return null
return when {
expr.isArraySize -> Kind.usize
expr.isEnumVariantDiscriminant -> Kind.isize
else -> null
}
}
private val RsLitExpr.isArraySize: Boolean get() = (parent as? RsArrayExpr)?.sizeExpr == this
private val RsLitExpr.isEnumVariantDiscriminant: Boolean get() = parent is RsVariantDiscriminant
val DEFAULT_KIND = Kind.i32
}
enum class Kind {
u8, u16, u32, u64, u128, usize,
i8, i16, i32, i64, i128, isize
}
// Ignore `isKindWeak` for the purposes of equality
override fun equals(other: Any?): Boolean = other is TyInteger && other.kind == kind
override fun hashCode(): Int = kind.hashCode()
override fun toString(): String = tyToString(this)
}
class TyFloat(val kind: Kind, override val isKindWeak: Boolean = false) : TyNumeric {
companion object {
fun fromLiteral(literal: PsiElement): TyFloat {
val kind = Kind.values().find { literal.text.endsWith(it.name) }
return TyFloat(kind ?: DEFAULT_KIND, kind == null)
}
val DEFAULT_KIND = Kind.f64
}
enum class Kind { f32, f64 }
// Ignore `isKindWeak` for the purposes of equality
override fun equals(other: Any?): Boolean = other is TyFloat && other.kind == kind
override fun hashCode(): Int = kind.hashCode()
override fun toString(): String = tyToString(this)
}
|
mit
|
c704bb2427106ff114f06695f9319fc6
| 30.962406 | 109 | 0.633733 | 4.229851 | false | false | false | false |
bnsantos/android-offline-example
|
app/app/src/test/java/com/bnsantos/offline/Extensions.kt
|
1
|
1372
|
package com.bnsantos.offline
import com.google.gson.Gson
import com.google.gson.stream.JsonReader
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.Okio
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.reflect.Type
import java.nio.charset.StandardCharsets
fun enqueueResponse(mockWebServer: MockWebServer, fileName: String, loader: ClassLoader){
enqueueResponse(mockWebServer, resourceAsInputStream(loader, fileName), emptyMap<String, String>())
}
fun enqueueResponse(mockWebServer: MockWebServer, inputStream: InputStream, headers: Map<String, String>){
val source = Okio.buffer(Okio.source(inputStream))
val response = MockResponse()
for (key in headers.keys) {
response.addHeader(key, headers[key])
}
mockWebServer.enqueue(response.setBody(source.readString(StandardCharsets.UTF_8)))
}
fun <T> loadFromResource(fileName: String, loader: ClassLoader, type: Type): T {
val resourceAsStream = resourceAsInputStream(loader, fileName)
val targetReader = InputStreamReader(resourceAsStream)
val reader = JsonReader(targetReader)
val data = Gson().fromJson<T>(reader, type)
targetReader.close()
return data
}
private fun resourceAsInputStream(loader: ClassLoader, fileName: String) = loader.getResourceAsStream("api-response/" + fileName)
|
apache-2.0
|
92b0634ecab2be93a9f583ea8c919d2a
| 37.111111 | 129 | 0.781341 | 4.369427 | false | false | false | false |
Zellius/RxLocationManager
|
core/src/main/kotlin/ru/solodovnikov/rxlocationmanager/BaseRxLocationManager.kt
|
1
|
2463
|
package ru.solodovnikov.rxlocationmanager
import android.content.Context
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.os.SystemClock
import java.util.concurrent.TimeoutException
/**
* Abstract class used just to implement rxJava1 and rxJava2
*/
abstract class BaseRxLocationManager<out SINGLE, out MAYBE>(context: Context) {
protected val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
/**
* Get last location from specific provider
* Observable will emit [ElderLocationException] if [howOldCanBe] is not null and location time is not valid.
*
* @param provider provider name
* @param howOldCanBe how old a location can be
* @return observable that emit last known location
* @see ElderLocationException
* @see ProviderHasNoLastLocationException
*/
@JvmOverloads
fun getLastLocation(provider: String, howOldCanBe: LocationTime? = null): MAYBE =
baseGetLastLocation(provider, howOldCanBe)
/**
* Try to get current location by specific provider.
* Observable will emit [TimeoutException] if [timeOut] is not null and timeOut occurs.
* Observable will emit [ProviderDisabledException] if provider is disabled
*
* @param provider provider name
* @param timeOut request timeout
* @return observable that emit current location
* @see TimeoutException
* @see ProviderDisabledException
*/
@JvmOverloads
fun requestLocation(provider: String, timeOut: LocationTime? = null): SINGLE
= baseRequestLocation(provider, timeOut)
protected abstract fun baseGetLastLocation(provider: String, howOldCanBe: LocationTime?): MAYBE
protected abstract fun baseRequestLocation(provider: String, timeOut: LocationTime?): SINGLE
/**
* Check is location not old
* @param howOldCanBe how old the location can be
* @return true if location is not so old as [howOldCanBe]
*/
protected fun Location.isNotOld(howOldCanBe: LocationTime): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos < howOldCanBe.timeUnit.toNanos(howOldCanBe.time)
} else {
System.currentTimeMillis() - time < howOldCanBe.timeUnit.toMillis(howOldCanBe.time)
}
}
}
|
mit
|
0ebfffa0ba36f304da17a4f1b18438d8
| 39.393443 | 122 | 0.72635 | 4.945783 | false | false | false | false |
Aptoide/aptoide-client-v8
|
app/src/main/java/cm/aptoide/pt/autoupdate/AutoUpdateService.kt
|
1
|
1506
|
package cm.aptoide.pt.autoupdate
import cm.aptoide.pt.dataprovider.exception.NoNetworkConnectionException
import retrofit2.http.GET
import retrofit2.http.Path
import rx.Observable
import rx.Single
class AutoUpdateService(private val service: Service, private val packageName: String,
private val clientSdkVersion: Int) {
private var loading = false
fun loadAutoUpdateModel(): Single<AutoUpdateModel> {
if (loading) {
return Single.just(AutoUpdateModel(loading = true))
}
return service.getAutoUpdateResponse(packageName, clientSdkVersion)
.doOnSubscribe { loading = true }
.doOnUnsubscribe { loading = false }
.doOnTerminate { loading = false }
.flatMap {
Observable.just(AutoUpdateModel(it.versioncode, it.uri, it.md5, it.minSdk, packageName))
}
.onErrorReturn { createErrorAutoUpdateModel(it) }
.toSingle()
}
private fun createErrorAutoUpdateModel(throwable: Throwable?): AutoUpdateModel? {
return when (throwable) {
is NoNetworkConnectionException -> AutoUpdateModel(status = Status.ERROR_NETWORK)
else -> AutoUpdateModel(status = Status.ERROR_GENERIC)
}
}
}
interface Service {
@GET("apks/package/autoupdate/get/package_name={package_name}/sdk={client_sdk_version}")
fun getAutoUpdateResponse(
@Path(value = "package_name") packageName: String, @Path(value = "client_sdk_version")
clientSdkVersion: Int): Observable<AutoUpdateJsonResponse>
}
|
gpl-3.0
|
8e6a76956b7efd053e19211e2662dfd0
| 34.046512 | 98 | 0.713147 | 4.468843 | false | false | false | false |
lewinskimaciej/planner
|
app/src/main/java/com/atc/planner/presentation/settings/SettingsPresenter.kt
|
1
|
1803
|
package com.atc.planner.presentation.settings
import com.atc.planner.data.repository.places_repository.SightsFilterDetails
import com.atc.planner.data.repository.user_details_repository.UserDetailsRepository
import com.atc.planner.presentation.base.BaseMvpPresenter
import java.io.Serializable
import javax.inject.Inject
class SettingsPresenter @Inject constructor(private val userDetailsRepository: UserDetailsRepository) : BaseMvpPresenter<SettingsView>() {
private var originalFilterDetails: SightsFilterDetails? = null
private var filterDetails: SightsFilterDetails? = null
override fun onViewCreated(data: Serializable?) {
if (filterDetails == null) {
filterDetails = userDetailsRepository.getFilterDetails()
originalFilterDetails = filterDetails?.copy()
}
view?.setUpValues(filterDetails)
}
private fun updateFilterDetails() {
userDetailsRepository.saveFilterDetails(filterDetails)
}
fun onIAmAChildCheckboxChanges(checked: Boolean) {
filterDetails?.targetsChildren = checked
updateFilterDetails()
}
fun onMuseumCheckboxChanges(checked: Boolean) {
filterDetails?.canBeAMuseum = checked
updateFilterDetails()
}
fun onArtGalleriesCheckboxChanges(checked: Boolean) {
filterDetails?.canBeAnArtGallery = checked
updateFilterDetails()
}
fun onPhysicalActivityCheckboxChanges(checked: Boolean) {
filterDetails?.canBePhysicalActivity = checked
updateFilterDetails()
}
fun onMaxEntryFeeChanges(newMaxEntryFee: Float) {
filterDetails?.maxEntryFee = newMaxEntryFee
updateFilterDetails()
}
fun end() {
view?.endWithResult(originalFilterDetails?.equals(filterDetails) == false)
}
}
|
mit
|
6fd3f7a1017e0059d523201912c6b364
| 31.214286 | 138 | 0.733222 | 5.151429 | false | false | false | false |
Reduks/Reduks
|
src/main/kotlin/com/reduks/reduks/Store.kt
|
1
|
1633
|
package com.reduks.reduks
import com.reduks.reduks.subscription.Subscriber
import com.reduks.reduks.subscription.Subscription
class Store<State>(initialState: State, initialReducer: (state: State, action: Action<State>) -> State, enhancer: Enhancer<State>? = null) {
private val subscribers: MutableList<Subscriber<State>> = mutableListOf()
private var isCurrentDispatching = false
private val reducer: (state: State, action: Action<State>) -> State = enhancer?.enhance(enhanceReducerWithDispatch(initialReducer), this) ?: enhanceReducerWithDispatch(initialReducer)
private var state: State = initialState
fun subscribe(subscriber: Subscriber<State>): Subscription {
subscribers.add(subscriber)
return Subscription { subscribers.remove(subscriber) }
}
fun dispatch(action: Action<State>) : Action<State> {
reducer(state, action)
return action
}
fun getState() : State = state
private fun enhanceReducerWithDispatch(reducer: (state: State, action: Action<State>) -> State): (state: State, action: Action<State>) -> State = { state, action ->
startDispatching()
this.state = reducer(state, action)
stopDispatching()
notifySubscribers()
this.state
}
private fun notifySubscribers() {
subscribers.forEach { it.stateChanged(state) }
}
private fun startDispatching() {
if (isCurrentDispatching) throw IllegalStateException("You can't dispatch inside a dispatch")
isCurrentDispatching = true
}
private fun stopDispatching() {
isCurrentDispatching = false
}
}
|
mit
|
8780b4ddbc339c83d5c61aac64c27cc3
| 35.311111 | 187 | 0.698102 | 4.706052 | false | false | false | false |
yoelglus/notes
|
app/src/main/java/com/yoelglus/notes/presentation/presenter/AddNotePresenter.kt
|
1
|
1306
|
package com.yoelglus.notes.presentation.presenter
import com.yoelglus.notes.domain.AddNote
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
class AddNotePresenter(private val addNote: AddNote) : Presetner<AddNotePresenter.View>() {
private val compositeDisposable = CompositeDisposable()
private var title = ""
private var text = ""
override fun onTakeView() {
val view = view
if (view != null) {
compositeDisposable.add(view.titleChanged().subscribe { title = it })
compositeDisposable.add(view.textChanged().subscribe { text = it })
compositeDisposable.add(view.addButtonClicked().subscribe {
addNote.execute(title, text).doOnSuccess {
view.notifySuccess()
}.doOnError {
view.notifyAddFailed(it.message)
}.subscribe()
})
}
}
override fun onDropView() {
compositeDisposable.dispose()
}
interface View {
fun titleChanged(): Observable<String>
fun textChanged(): Observable<String>
fun addButtonClicked(): Observable<Unit>
fun notifyAddFailed(errorMessage: String?)
fun notifySuccess()
}
}
|
apache-2.0
|
496230b8d598b54007d6acc2f889e02a
| 30.119048 | 91 | 0.638591 | 5.162055 | false | false | false | false |
LordAkkarin/Beacon
|
ui/src/main/kotlin/tv/dotstart/beacon/ui/exposure/PortExposureProvider.kt
|
1
|
5999
|
/*
* Copyright 2020 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.beacon.ui.exposure
import javafx.beans.binding.Bindings
import javafx.beans.property.*
import kotlinx.coroutines.runBlocking
import tv.dotstart.beacon.core.Beacon
import tv.dotstart.beacon.core.delegate.logManager
import tv.dotstart.beacon.core.gateway.InternetGatewayDevice
import tv.dotstart.beacon.core.gateway.InternetGatewayDeviceLocator
import tv.dotstart.beacon.core.upnp.error.*
import tv.dotstart.beacon.ui.delegate.property
import tv.dotstart.beacon.ui.preload.Loader
import tv.dotstart.beacon.ui.preload.error.PreloadError
import tv.dotstart.beacon.ui.repository.model.Service
import tv.dotstart.beacon.ui.util.ErrorReporter
import tv.dotstart.beacon.ui.util.Localization
import tv.dotstart.beacon.ui.util.dialog
import java.io.Closeable
/**
* Manages the port mapping state along with any discovery logic.
*
* @author Johannes Donath
* @date 01/12/2020
*/
class PortExposureProvider : Closeable {
companion object {
private const val leaseDuration = 120L
private const val refreshPeriod = 30L
private val logger by logManager()
}
private val locator = InternetGatewayDeviceLocator()
val internetGatewayDeviceProperty: ObjectProperty<InternetGatewayDevice> =
SimpleObjectProperty()
var internetGatewayDevice: InternetGatewayDevice? by property(internetGatewayDeviceProperty)
private val _externalAddressProperty: StringProperty = SimpleStringProperty()
val externalAddressProperty: ReadOnlyStringProperty
get() = this._externalAddressProperty
val externalAddress: String? by property(_externalAddressProperty)
private val beaconProperty: ObjectProperty<Beacon> = SimpleObjectProperty()
private val beacon: Beacon? by property(beaconProperty)
init {
// TODO: Terminate previous Beacon on change
val beaconBinding = Bindings.createObjectBinding(
{ this.internetGatewayDevice?.let(::Beacon) },
this.internetGatewayDeviceProperty)
this.beaconProperty.bind(beaconBinding)
}
fun refresh(): Boolean {
logger.info("Querying network for compatible internet gateway")
logger.debug("Locating new gateway device within local network")
this.internetGatewayDevice = runBlocking {
locator.locate()
}
logger.debug("Requesting external address from gateway device (if present)")
runBlocking {
_externalAddressProperty.set(internetGatewayDevice?.getExternalAddress())
}
logger.debug("Attempting to initialize beacon instance for new gateway")
val beacon = this.beacon
beacon?.start()
ErrorReporter.trace("exposure", "Internet gateway refresh performed")
return beacon != null
}
fun expose(service: Service) {
val beacon = this.beacon
?: throw IllegalStateException("No active beacon")
try {
runBlocking {
beacon.expose(service)
}
} catch (ex: ActionFailedException) {
logger.error("UPnP action failed for service $service", ex)
dialog(Localization("error.upnp.failed"), Localization("error.upnp.failed.body"))
} catch (ex: DeviceOutOfMemoryException) {
logger.error("UPnP device ran out of memory for service $service", ex)
dialog(Localization("error.upnp.memory"), Localization("error.upnp.memory.body"))
} catch (ex: HumanInterventionRequiredException) {
logger.error("UPnP device requires human intervention for service $service", ex)
dialog(Localization("error.upnp.intervention"), Localization("error.upnp.intervention.body"))
} catch (ex: InvalidActionArgumentException) {
logger.error("UPnP device rejected action arguments for service $service", ex)
dialog(Localization("error.upnp.argument"), Localization("error.upnp.argument.body"))
} catch (ex: InvalidActionException) {
logger.error("UPnP device rejected action for service $service", ex)
dialog(Localization("error.upnp.action"), Localization("error.upnp.action.body"))
} catch (ex: ActionException) {
logger.error("UPnP action failed for service $service", ex)
dialog(Localization("error.upnp.unknown"), Localization("error.upnp.unknown.body"))
}
ErrorReporter.trace("exposure", "Service exposed", data = mapOf(
"service_id" to service.id,
"service_title" to service.title
))
}
operator fun contains(service: Service): Boolean {
val beacon = this.beacon
?: throw IllegalStateException("No active beacon")
return service in beacon
}
fun close(service: Service) {
val beacon = this.beacon
?: throw IllegalStateException("No active beacon")
runBlocking {
beacon.close(service)
}
ErrorReporter.trace("exposure", "Service closed", data = mapOf(
"service_id" to service.id,
"service_title" to service.title
))
}
override fun close() {
this.beacon?.close()
this.internetGatewayDevice?.close()
}
class Preloader(private val provider: PortExposureProvider) : Loader {
override val description = "gateway"
override val priority = Int.MAX_VALUE
override fun load() {
if (!this.provider.refresh()) {
throw PreloadError(
"gateway",
"Failed to locate UPnP compatible internet gateway")
}
}
override fun shutdown() {
this.provider.close()
}
}
}
|
apache-2.0
|
d010e2b403125c4d1bc06ec580cf3ed2
| 33.676301 | 99 | 0.725788 | 4.541257 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-amphibians
|
app/src/main/java/com/example/amphibians/ui/screens/HomeScreen.kt
|
1
|
6283
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.amphibians.ui.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.amphibians.R
import com.example.amphibians.model.Amphibian
import com.example.amphibians.ui.theme.AmphibiansTheme
@Composable
fun HomeScreen(
amphibiansUiState: AmphibiansUiState,
retryAction: () -> Unit,
modifier: Modifier = Modifier
) {
when (amphibiansUiState) {
is AmphibiansUiState.Loading -> LoadingScreen(modifier)
is AmphibiansUiState.Success -> AmphibiansListScreen(amphibiansUiState.amphibians, modifier)
else -> ErrorScreen(retryAction, modifier)
}
}
/**
* The home screen displaying the loading message.
*/
@Composable
fun LoadingScreen(modifier: Modifier = Modifier) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier.fillMaxSize()
) {
Image(
modifier = Modifier.size(200.dp),
painter = painterResource(R.drawable.loading_img),
contentDescription = stringResource(R.string.loading)
)
}
}
/**
* The home screen displaying error message with re-attempt button.
*/
@Composable
fun ErrorScreen(retryAction: () -> Unit, modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(stringResource(R.string.loading_failed))
Button(onClick = retryAction) {
Text(stringResource(R.string.retry))
}
}
}
@Composable
fun AmphibianCard(amphibian: Amphibian, modifier: Modifier = Modifier) {
Card(modifier = modifier.fillMaxWidth(),
elevation = 8.dp,
shape = RoundedCornerShape(8.dp)
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = stringResource(R.string.amphibian_title, amphibian.name, amphibian.type),
style = MaterialTheme.typography.h6,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
modifier = Modifier.padding(top = 16.dp)
)
Text(
text = amphibian.description,
style = MaterialTheme.typography.body1,
textAlign = TextAlign.Justify,
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp)
)
AsyncImage(
modifier = Modifier.fillMaxWidth(),
model = ImageRequest.Builder(context = LocalContext.current)
.data(amphibian.imgSrc)
.crossfade(true)
.build(),
contentDescription = null,
contentScale = ContentScale.FillWidth,
error = painterResource(id = R.drawable.ic_broken_image),
placeholder = painterResource(id = R.drawable.loading_img)
)
}
}
}
@Composable
private fun AmphibiansListScreen(amphibians: List<Amphibian>, modifier: Modifier = Modifier) {
LazyColumn(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(16.dp),
contentPadding = PaddingValues(16.dp)
) {
items(
items = amphibians,
key = { amphibian ->
amphibian.name
}
) { amphibian ->
AmphibianCard(amphibian = amphibian)
}
}
}
@Preview(showBackground = true)
@Composable
fun LoadingScreenPreview() {
AmphibiansTheme {
LoadingScreen()
}
}
@Preview(showBackground = true)
@Composable
fun ErrorScreenPreview() {
AmphibiansTheme {
ErrorScreen({})
}
}
@Preview(showBackground = true)
@Composable
fun AmphibiansListScreenPreview() {
AmphibiansTheme {
val mockData = List(10) {
Amphibian(
"Lorem Ipsum - $it",
"$it",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do" +
" eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad" +
" minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip" +
" ex ea commodo consequat.",
imgSrc = ""
)
}
AmphibiansListScreen(mockData)
}
}
|
apache-2.0
|
d6bda19e89b6a5ed624eddc4e230fac5
| 32.962162 | 100 | 0.67038 | 4.606305 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.