repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
code-disaster/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/CallbackFunction.kt | 2 | 10867 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
class CallbackFunction internal constructor(
module: Module,
className: String,
nativeType: String,
val returns: NativeType,
vararg val signature: Parameter
) : GeneratorTarget(module, className) {
internal var functionDoc: (CallbackFunction) -> String = { "" }
var additionalCode = ""
internal fun nativeType(name: String, separator: String = ", ", prefix: String = "", postfix: String = "") =
"${returns.name} (*$name) (${if (signature.isEmpty()) "void" else signature.asSequence()
.joinToString(separator, prefix = prefix, postfix = postfix) { param ->
param.toNativeType(null).let {
if (it.endsWith('*')) {
"$it${param.name}"
} else {
"$it ${param.name}"
}
}
}
})"
internal val nativeType = if (nativeType === ANONYMOUS)
"${returns.name} (*) (${if (signature.isEmpty()) "void" else signature.asSequence()
.joinToString(", ") { it.toNativeType(null) }
})"
else
nativeType
private val NativeType.libffi
get(): String = when (this) {
is PointerType<*> -> "ffi_type_pointer"
is IntegerType -> when (mapping) {
PrimitiveMapping.BYTE -> if (this.unsigned) "ffi_type_uint8" else "ffi_type_sint8"
PrimitiveMapping.SHORT -> if (this.unsigned) "ffi_type_uint16" else "ffi_type_sint16"
PrimitiveMapping.INT -> if (this.unsigned) "ffi_type_uint32" else "ffi_type_sint32"
PrimitiveMapping.LONG -> if (this.unsigned) "ffi_type_uint64" else "ffi_type_sint64"
PrimitiveMapping.CLONG -> if (this.unsigned) "ffi_type_ulong" else "ffi_type_slong"
PrimitiveMapping.POINTER -> "ffi_type_pointer"
else -> throw IllegalArgumentException("Unsupported callback native type: $this")
}
is PrimitiveType -> when (mapping) {
PrimitiveMapping.BOOLEAN -> "ffi_type_uint8"
PrimitiveMapping.BOOLEAN4 -> "ffi_type_uint32"
PrimitiveMapping.FLOAT -> "ffi_type_float"
PrimitiveMapping.DOUBLE -> "ffi_type_double"
else -> throw IllegalArgumentException("Unsupported callback native type: $this")
}
is StructType -> if (this.definition.nativeLayout)
throw IllegalArgumentException("Unsupported struct type with native layout: $this")
else
"apiCreate${if (this.definition.union) "Union" else "Struct"}(${
this.definition.members.joinToString(", ") { member ->
if (member is StructMemberArray) {
"apiCreateArray(${member.nativeType.libffi}, ${member.size})"
} else {
member.nativeType.libffi
}
}
})"
is VoidType -> "ffi_type_void"
else -> throw IllegalArgumentException("Unsupported native type: $this")
}
private val NativeType.memGetType
get() = if (isPointer) "Address" else when (mapping) {
PrimitiveMapping.BOOLEAN -> "Byte"
PrimitiveMapping.CLONG -> "CLong"
else -> (mapping as PrimitiveMapping).javaMethodName.upperCaseFirst
}
private fun PrintWriter.generateDocumentation(isClass: Boolean) {
val documentation = if (module === Module.VULKAN)
super.documentation
else {
val type =
"""
<h3>Type</h3>
${codeBlock(nativeType("{@link \\#invoke}", ",\n$t", "\n$t", "\n"))}
"""
super.documentation.let {
if (it == null)
type
else
"$it\n\n$type"
}
}
if (documentation != null) {
println(processDocumentation(documentation.let {
if (isClass) {
it.replace("Instances of this interface", "Instances of this class")
} else {
it
}
}).toJavaDoc(indentation = "", see = see, since = since))
}
}
override fun PrintWriter.generateJava() {
print(HEADER)
println("package $packageName;\n")
print("""import javax.annotation.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
""")
preamble.printJava(this)
generateDocumentation(true)
println("""${access.modifier}abstract class $className extends Callback implements ${className}I {""")
print("""
/**
* Creates a {@code $className} instance from the specified function pointer.
*
* @return the new {@code $className}
*/
public static $className create(long functionPointer) {
${className}I instance = Callback.get(functionPointer);
return instance instanceof $className
? ($className)instance
: new Container(functionPointer, instance);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code functionPointer} is {@code NULL}. */
@Nullable
public static $className createSafe(long functionPointer) {
return functionPointer == NULL ? null : create(functionPointer);
}
/** Creates a {@code $className} instance that delegates to the specified {@code ${className}I} instance. */
public static $className create(${className}I instance) {
return instance instanceof $className
? ($className)instance
: new Container(instance.address(), instance);
}
protected $className() {
super(CIF);
}
$className(long functionPointer) {
super(functionPointer);
}
""")
if (additionalCode.isNotEmpty()) {
print("\n$t")
print(additionalCode.trim())
println()
}
print("""
private static final class Container extends $className {
private final ${className}I delegate;
Container(long functionPointer, ${className}I delegate) {
super(functionPointer);
this.delegate = delegate;
}
@Override
public ${if (returns is StructType) "void" else returns.nativeMethodType} invoke(${signature.asSequence()
.map {
"${if (it.nativeType.mapping == PrimitiveMapping.BOOLEAN4) "boolean"
else if (it.nativeType is StructType)
it.nativeType.definition.className
else
it.nativeType.nativeMethodType} ${it.name}"
}
.let { if (returns is StructType) it + "${returns.javaMethodType} $RESULT" else it }
.joinToString(", ")}) {
${if (returns.mapping !== TypeMapping.VOID && returns !is StructType) "return " else ""}delegate.invoke(${signature.asSequence()
.map { it.name }
.let { if (returns is StructType) it + RESULT else it }
.joinToString(", ")
});
}
}
}""")
}
internal fun PrintWriter.generateInterface() {
print(HEADER)
println("package $packageName;\n")
println("import org.lwjgl.system.*;")
println("import org.lwjgl.system.libffi.*;\n")
println("import static org.lwjgl.system.APIUtil.*;")
if (signature.isNotEmpty()) {
println("import static org.lwjgl.system.MemoryUtil.*;")
println("import static org.lwjgl.system.libffi.LibFFI.*;")
}
println()
generateDocumentation(false)
print("""@FunctionalInterface
@NativeType("$nativeType")
${access.modifier}interface ${className}I extends CallbackI {
FFICIF CIF = apiCreateCIF(
${if (module.callingConvention === CallingConvention.STDCALL) "apiStdcall()" else "FFI_DEFAULT_ABI"},
${returns.libffi},
${signature.joinToString(", ") { it.nativeType.libffi }}
);
@Override
default FFICIF getCallInterface() { return CIF; }
@Override
default void callback(long ret, long args) {
""")
if (returns.mapping !== TypeMapping.VOID && returns !is StructType) {
print("${returns.nativeMethodType} $RESULT = ")
}
print("""invoke(${if (signature.none() && returns !is StructType) "" else signature.asSequence()
.mapIndexed { i, it ->
val arg = "memGetAddress(args${
when (i) {
0 -> ""
1 -> " + POINTER_SIZE"
else -> " + $i * POINTER_SIZE"
}
})"
if (it.nativeType is StructType) {
"${it.nativeType.definition.className}.create($arg)"
} else {
"memGet${it.nativeType.memGetType}($arg)${if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN || it.nativeType.mapping === PrimitiveMapping.BOOLEAN4) " != 0" else ""}"
}
}
.let { if (returns is StructType) it + "${returns.javaMethodType}.create(ret)" else it }
.joinToString(",\n$t$t$t", prefix = "\n$t$t$t", postfix = "\n$t$t")
});""")
if (returns.mapping !== TypeMapping.VOID && returns !is StructType) {
print("\n$t${t}apiClosureRet${if (returns.isPointer) "P" else if (returns.mapping === PrimitiveMapping.LONG) "L" else ""}(ret, $RESULT);")
}
print("""
}
""")
val doc = functionDoc(this@CallbackFunction)
if (doc.isNotEmpty()) {
println()
print(doc)
}
print("""
${if (returns is StructType) "void" else returns.annotate(returns.nativeMethodType)} invoke(${signature.asSequence()
.map { "${it.nativeType.annotate(if (it.nativeType.mapping == PrimitiveMapping.BOOLEAN4) "boolean" else if (it.nativeType is StructType) it.nativeType.definition.className else it.nativeType.nativeMethodType)} ${it.name}" }
.let { if (returns is StructType) it + "${returns.annotate(returns.javaMethodType)} $RESULT" else it }
.joinToString(", ")});
}""")
}
}
internal class CallbackInterface(
val callback: CallbackFunction
) : GeneratorTarget(callback.module, "${callback.className}I") {
override fun PrintWriter.generateJava() = callback.run {
[email protected]()
}
} | bsd-3-clause | 6c3ddd83bcec2a3b76f8ab4eddaf5c23 | 38.234657 | 235 | 0.552498 | 4.730953 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/dataitem/ProgramItemAttribute.kt | 1 | 4606 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.program.programindicatorengine.internal.dataitem
import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor
import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemId
import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemType
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramExpressionItem
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorParserUtils.assumeProgramAttributeSyntax
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.getColumnValueCast
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.getDefaultValue
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo
import org.hisp.dhis.parser.expression.antlr.ExpressionParser.ExprContext
internal class ProgramItemAttribute : ProgramExpressionItem() {
override fun evaluate(ctx: ExprContext, visitor: CommonExpressionVisitor): Any? {
assumeProgramAttributeSyntax(ctx)
val attributeUid = ctx.uid0.text
val attributeValue = visitor.programIndicatorContext.attributeValues[attributeUid]
val attribute = visitor.trackedEntityAttributeStore.selectByUid(attributeUid)
val value = attributeValue?.value()
val handledValue = visitor.handleNulls(value)
val strValue = handledValue?.toString()
return formatValue(strValue, attribute!!.valueType())
}
override fun getSql(ctx: ExprContext, visitor: CommonExpressionVisitor): Any {
assumeProgramAttributeSyntax(ctx)
val attributeUid = ctx.uid0.text
// TODO Manage null and boolean values
val attribute = visitor.trackedEntityAttributeStore.selectByUid(attributeUid)
?: throw IllegalArgumentException("Attribute $attributeUid does not exist.")
val valueCastExpression = getColumnValueCast(
TrackedEntityAttributeValueTableInfo.Columns.VALUE,
attribute.valueType()
)
val selectExpression = ProgramIndicatorSQLUtils.getAttributeWhereClause(
column = valueCastExpression,
attributeUid = attributeUid,
programIndicator = visitor.programIndicatorSQLContext.programIndicator
)
return if (visitor.state.replaceNulls) {
"(COALESCE($selectExpression, ${getDefaultValue(attribute.valueType())}))"
} else {
selectExpression
}
}
override fun getItemId(ctx: ExprContext, visitor: CommonExpressionVisitor): Any {
return visitor.itemIds.add(
DimensionalItemId.builder()
.dimensionalItemType(DimensionalItemType.TRACKED_ENTITY_ATTRIBUTE)
.id0(ctx.uid0.text)
.build()
)
}
}
| bsd-3-clause | 4393ec47dbdfb9bc66ebc0ec14110e38 | 48 | 130 | 0.75749 | 4.92094 | false | false | false | false |
google/android-auto-companion-app | android/app/src/main/kotlin/com/google/automotive/companion/CalendarSyncMethodChannel.kt | 1 | 7237 | /*
* 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.automotive.companion
import android.Manifest.permission
import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.IBinder
import android.util.Log
import androidx.core.app.ActivityCompat.requestPermissions
import androidx.core.content.ContextCompat.checkSelfPermission
import com.google.android.libraries.car.calendarsync.feature.CalendarSyncFeature
import com.google.android.libraries.car.connectionservice.FeatureManagerServiceBinder
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.PluginRegistry.Registrar
import java.util.UUID
import org.json.JSONArray
import java.lang.ClassCastException
import kotlin.collections.filterIsInstance
/**
* CalendarSync Flutter Plugin to communicate with the Flutter TrustDeviceApp. Permissions are
* platform specific and require a View to work, and are thus handled are handled in the plugin.
*/
class CalendarSyncMethodChannel(private val registrar: Registrar) : MethodCallHandler {
private val calendarViewItemData: CalendarViewItemData =
CalendarViewItemData(registrar.context().contentResolver)
private var grantPermissionsResult: MethodChannel.Result? = null
private var calendarSyncManager: CalendarSyncFeature? = null
init {
val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val connectedDeviceService = (service as FeatureManagerServiceBinder).getService()
calendarSyncManager = connectedDeviceService.getFeatureManager(CalendarSyncFeature::class.java)
}
override fun onServiceDisconnected(name: ComponentName) {
calendarSyncManager = null
}
}
registrar.context().bindService(
ConnectedDeviceService.createIntent(registrar.context()),
serviceConnection,
Context.BIND_AUTO_CREATE
)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
CalendarSyncConstants.METHOD_HAS_PERMISSIONS -> result.success(hasPermissions())
CalendarSyncConstants.METHOD_REQUEST_PERMISSIONS -> {
if (grantPermissionsResult != null) {
result.error(
"ERROR_ALREADY_REQUESTING_PERMISSIONS",
"A request for permissions is already running, please wait for it to finish before"
+ " making another request",
null)
return
}
grantPermissionsResult = result
requestCalendarPermissions()
}
CalendarSyncConstants.METHOD_RETRIEVE_CALENDARS -> if (hasPermissions()) {
val calendarList = calendarViewItemData.fetchCalendarViewItems()
result.success(toJsonArrayString(calendarList))
} else {
result.error(
"READ_CALENDAR_PERMISSION_NOT_GRANTED",
"Permission to read calendar was not granted.",
null)
}
CalendarSyncConstants.METHOD_DISABLE_CAR -> {
carIdFromMethodCall(call)?.let {
calendarSyncManager?.disableCar(UUID.fromString(it))
}
result.success(null)
}
CalendarSyncConstants.METHOD_ENABLE_CAR -> {
carIdFromMethodCall(call)?.let {
calendarSyncManager?.enableCar(UUID.fromString(it))
}
result.success(null)
}
CalendarSyncConstants.METHOD_IS_CAR_ENABLED -> {
val carId = carIdFromMethodCall(call) ?: return result.success(null)
result.success(calendarSyncManager?.isCarEnabled(UUID.fromString(carId)))
}
CalendarSyncConstants.METHOD_FETCH_CALENDAR_IDS_TO_SYNC -> {
val carId = carIdFromMethodCall(call) ?: return result.success(emptyList<String>())
val calendars = calendarSyncManager?.getCalendarIdsToSync(UUID.fromString(carId))
result.success(calendars?.toList() ?: emptyList<String>())
}
CalendarSyncConstants.METHOD_STORE_CALENDAR_IDS_TO_SYNC -> {
val rawCalendars = call.argument(CalendarSyncConstants.ARGUMENT_CALENDARS) as? Collection<*>
val carId = call.argument(CalendarSyncConstants.ARGUMENT_CAR_ID) as? String
if (rawCalendars == null || carId == null) {
result.success(null)
return
}
val calendarIds = rawCalendars.filterIsInstance<String>().toSet()
calendarSyncManager?.setCalendarIdsToSync(calendarIds, UUID.fromString(carId))
result.success(null)
}
else -> result.notImplemented()
}
}
/**
* Defaulting permission code used to 0 assuming no other permissions are requested at this
* instant.
*/
private fun requestCalendarPermissions() {
requestPermissions(registrar.activity(), arrayOf(permission.READ_CALENDAR), 0)
}
private fun hasPermissions(): Boolean {
return checkSelfPermission(registrar.context(), permission.READ_CALENDAR) ==
PackageManager.PERMISSION_GRANTED
}
private fun handlePermissionsRequest(permissions: Array<String>, grantResults: IntArray) {
if (grantPermissionsResult == null) {
Log.e(
TAG,
"grantPermissionsResult is null. handlePermissionsRequest shouldn't have been called.")
return
}
var granted = true
for (i in permissions.indices) {
granted = granted && grantResults[i] == PackageManager.PERMISSION_GRANTED
}
grantPermissionsResult!!.success(granted)
grantPermissionsResult = null
}
private fun carIdFromMethodCall(call: MethodCall): String? =
try {
call.argument(CalendarSyncConstants.ARGUMENT_CAR_ID)
} catch (e: ClassCastException) {
call.arguments()
}
/** Returns a string of [CalendarViewItem]s converted to a json array */
private fun toJsonArrayString(calendarList: List<CalendarViewItem>): String =
JSONArray(calendarList.map { it.toJson() }).toString()
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), CalendarSyncConstants.CHANNEL)
val callHandler = CalendarSyncMethodChannel(registrar)
channel.setMethodCallHandler(callHandler)
// Assuming READ_CALENDAR is the only permission granted at this exact moment.
registrar.addRequestPermissionsResultListener { _, permissions, grantResults ->
callHandler.handlePermissionsRequest(permissions, grantResults)
true
}
}
private const val TAG = "CalendarSyncMethodChannel"
}
}
| apache-2.0 | b5acabe6f5949a0abb88412439031a8c | 35.923469 | 103 | 0.722537 | 4.853789 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewElement.kt | 10 | 4008 | // 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 com.intellij.codeInsight.hint
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiBinaryFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usages.Usage
import com.intellij.usages.UsageInfo2UsageAdapter
import javax.swing.Icon
/**
* A single element shown in the Show Implementations view.
*/
abstract class ImplementationViewElement {
abstract val project: Project
abstract val isNamed: Boolean
@get:NlsSafe
abstract val name: String?
@get:NlsSafe
abstract val presentableText: String
@get:NlsSafe
open val containerPresentation: String? = null
abstract val containingFile: VirtualFile?
@get:NlsSafe
abstract val text: String?
@get:NlsSafe
abstract val locationText: String?
abstract val locationIcon: Icon?
abstract val containingMemberOrSelf: ImplementationViewElement
abstract val elementForShowUsages: PsiElement?
abstract fun navigate(focusEditor: Boolean)
open val usage: Usage?
get() {
return UsageInfo2UsageAdapter(UsageInfo(elementForShowUsages ?: return null))
}
}
class PsiImplementationViewElement(val psiElement: PsiElement) : ImplementationViewElement() {
override val project: Project
get() = psiElement.project
override val isNamed: Boolean
get() = psiElement is PsiNamedElement
override val name: String?
get() = (psiElement as? PsiNamedElement)?.name
override val containingFile: VirtualFile?
get() = psiElement.containingFile?.originalFile?.virtualFile
override val text: String?
get() = ImplementationViewComponent.getNewText(psiElement)
override val presentableText: String
get() {
val presentation = (psiElement as? NavigationItem)?.presentation
val vFile = containingFile ?: return ""
val presentableName = vFile.presentableName
if (presentation == null) {
return presentableName
}
val elementPresentation = presentation.presentableText
if (elementPresentation == null) {
return presentableName
}
return elementPresentation
}
override val containerPresentation: String?
get() {
val presentation = (psiElement as? NavigationItem)?.presentation ?: return null
return presentation.locationString
}
override val locationText: String?
get() = ElementLocationUtil.renderElementLocation(psiElement, Ref())
override val locationIcon: Icon?
get() = Ref<Icon>().also { ElementLocationUtil.renderElementLocation(psiElement, it) }.get()
override val containingMemberOrSelf: ImplementationViewElement
get() {
val parent = PsiTreeUtil.getStubOrPsiParent(psiElement)
if (parent == null || (parent is PsiFile && parent.virtualFile == containingFile)) {
return this
}
return PsiImplementationViewElement(parent)
}
override fun navigate(focusEditor: Boolean) {
val navigationElement = psiElement.navigationElement
val file = navigationElement.containingFile?.originalFile ?: return
val virtualFile = file.virtualFile ?: return
val project = psiElement.project
val fileEditorManager = FileEditorManagerEx.getInstanceEx(project)
val descriptor = OpenFileDescriptor(project, virtualFile, navigationElement.textOffset)
fileEditorManager.openTextEditor(descriptor, focusEditor)
}
override val elementForShowUsages: PsiElement?
get() = if (psiElement !is PsiBinaryFile) psiElement else null
}
| apache-2.0 | a5eb54fd61bd24babd6b2435dc54d311 | 33.25641 | 140 | 0.760729 | 4.954265 | false | false | false | false |
cdietze/klay | src/main/kotlin/klay/core/Pointer.kt | 1 | 3479 | package klay.core
import react.Signal
/**
* Abstracts over [Mouse] and [Touch] input, providing a least-common-denominator API
* which tracks a single "pointer" with simple interactions. If you want global pointer events,
* you have to create an instance of this class yourself.
*/
open class Pointer(private val plat: Platform) {
/** Contains information on a pointer event. */
class Event(flags: Int, time: Double, x: Float, y: Float,
// NOTE: this enum must match Touch.Event.Kind exactly
/** Whether this event represents a start, move, etc. */
val kind: Event.Kind,
/** Whether this event originated from a touch event. */
var isTouch: Boolean) : klay.core.Event.XY(flags, time, x, y) {
/** Enumerates the different kinds of pointer event. */
enum class Kind constructor(
/** Whether this kind starts or ends an interaction. */
val isStart: Boolean, val isEnd: Boolean) {
START(true, false), DRAG(false, false), END(false, true), CANCEL(false, true)
}
override fun name(): String {
return "Pointer"
}
override fun addFields(builder: StringBuilder) {
super.addFields(builder)
builder.append(", kind=").append(kind)
builder.append(", touch=").append(isTouch)
}
}
/** Allows pointer interaction to be temporarily disabled.
* No pointer events will be dispatched whilst this big switch is in the off position. */
var enabled = true
/** A signal which emits pointer events. */
var events: Signal<Event> = Signal()
init {
// if this platform supports touch events, use those
if (plat.input.hasTouch) {
var active = -1
plat.input.touchEvents.connect { events: Array<Touch.Event> ->
for (event in events) {
if (active == -1 && event.kind.isStart) active = event.id
if (event.id == active) {
forward(Event.Kind.values()[event.kind.ordinal], true, event)
if (event.kind.isEnd) active = -1
}
}
}
} else if (plat.input.hasMouse) {
var dragging: Boolean = false
plat.input.mouseEvents.connect { event: Mouse.Event ->
if (event is Mouse.MotionEvent) {
if (dragging) forward(Event.Kind.DRAG, false, event)
} else if (event is Mouse.ButtonEvent) {
val bevent = event
if (bevent.button == Mouse.ButtonEvent.Id.LEFT) {
dragging = bevent.down
forward(if (bevent.down) Event.Kind.START else Event.Kind.END, false, bevent)
}
}
}
} else
plat.log.warn("Platform has neither mouse nor touch events? [type=${plat.type()}]")// otherwise complain because what's going on?
// otherwise use mouse events if it has those
}
protected fun forward(kind: Event.Kind, isTouch: Boolean, source: klay.core.Event.XY) {
if (!enabled || !events.hasConnections()) return
val event = Event(source.flags, source.time, source.x, source.y, kind, isTouch)
plat.dispatchEvent(events, event)
// TODO: propagate prevent default back to original event
}
}
| apache-2.0 | 25f68a5ce31ea2af965519dac9133a80 | 40.416667 | 141 | 0.569416 | 4.500647 | false | false | false | false |
tinmegali/android_achitecture_components_sample | app/src/main/java/com/tinmegali/myweather/models/WeatherMain.kt | 1 | 1478 | package com.tinmegali.myweather.models
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity( tableName = "weather" )
data class WeatherMain(
@ColumnInfo( name = "date" )
var dt: Long?,
@ColumnInfo( name = "city" )
var name: String?,
@ColumnInfo(name = "temp_min" )
var tempMin: Double?,
@ColumnInfo(name = "temp_max" )
var tempMax: Double?,
@ColumnInfo( name = "main" )
var main: String?,
@ColumnInfo( name = "description" )
var description: String?,
@ColumnInfo( name = "icon" )
var icon: String?
) {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
var id: Long = 0
companion object {
fun factory( weatherResponse: WeatherResponse ) : WeatherMain {
return WeatherMain(
dt = weatherResponse.dt!!,
name = weatherResponse.name,
tempMin = weatherResponse.main!!.tempMin,
tempMax = weatherResponse.main!!.tempMax,
main = weatherResponse.weather!![0].main,
description = weatherResponse.weather!![0].description,
icon = weatherResponse.weather!![0].icon
)
}
}
fun iconUrl() : String {
return "http://openweathermap.org/img/w/$icon.png"
}
} | apache-2.0 | cd98e533e9c2abe0b3bf352d0c706caa | 27.442308 | 75 | 0.569012 | 4.39881 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/utils/RectUtils.kt | 1 | 1500 | /*
* 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.shared.utils
import android.graphics.Rect
import android.graphics.RectF
object RectUtils {
fun fitRectWithin(inner: Rect, outer: Rect): Rect {
val innerAspectRatio = inner.width() / inner.height().toFloat()
val outerAspectRatio = outer.width() / outer.height().toFloat()
val resizeFactor = if (innerAspectRatio >= outerAspectRatio)
outer.width() / inner.width().toFloat()
else
outer.height() / inner.height().toFloat()
val newWidth = inner.width() * resizeFactor
val newHeight = inner.height() * resizeFactor
val newLeft = outer.left + (outer.width() - newWidth) / 2f
val newTop = outer.top + (outer.height() - newHeight) / 2f
return Rect(newLeft.toInt(), newTop.toInt(), (newWidth + newLeft).toInt(), (newHeight + newTop).toInt())
}
}
fun RectF.toClosestRect(): Rect {
return Rect(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}
| gpl-2.0 | ba3508ede2199bca30a1a326577c316b | 34.714286 | 112 | 0.678667 | 4.087193 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/ActColumnCustomize.kt | 1 | 17037 | package jp.juggler.subwaytooter
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import com.jrummyapps.android.colorpicker.ColorPickerDialog
import com.jrummyapps.android.colorpicker.ColorPickerDialogListener
import jp.juggler.subwaytooter.api.TootApiResult
import jp.juggler.subwaytooter.api.runApiTask
import jp.juggler.subwaytooter.column.*
import jp.juggler.util.*
import org.jetbrains.anko.textColor
import java.io.File
import java.io.FileOutputStream
import java.text.NumberFormat
import kotlin.math.max
class ActColumnCustomize : AppCompatActivity(), View.OnClickListener, ColorPickerDialogListener {
companion object {
internal val log = LogCategory("ActColumnCustomize")
internal const val EXTRA_COLUMN_INDEX = "column_index"
internal const val COLOR_DIALOG_ID_HEADER_BACKGROUND = 1
internal const val COLOR_DIALOG_ID_HEADER_FOREGROUND = 2
internal const val COLOR_DIALOG_ID_COLUMN_BACKGROUND = 3
internal const val COLOR_DIALOG_ID_ACCT_TEXT = 4
internal const val COLOR_DIALOG_ID_CONTENT_TEXT = 5
internal const val PROGRESS_MAX = 65536
fun createIntent(activity: ActMain, idx: Int) =
Intent(activity, ActColumnCustomize::class.java).apply {
putExtra(EXTRA_COLUMN_INDEX, idx)
}
}
private var columnIndex: Int = 0
internal lateinit var column: Column
internal lateinit var appState: AppState
internal var density: Float = 0f
private lateinit var flColumnBackground: View
internal lateinit var ivColumnBackground: ImageView
internal lateinit var sbColumnBackgroundAlpha: SeekBar
private lateinit var llColumnHeader: View
private lateinit var ivColumnHeader: ImageView
private lateinit var tvColumnName: TextView
internal lateinit var etAlpha: EditText
private lateinit var tvSampleAcct: TextView
private lateinit var tvSampleContent: TextView
internal var loadingBusy: Boolean = false
private var lastImageUri: String? = null
private var lastImageBitmap: Bitmap? = null
private val arColumnBackgroundImage = ActivityResultHandler(log) { r ->
if (r.isNotOk) return@ActivityResultHandler
r.data?.handleGetContentResult(contentResolver)
?.firstOrNull()?.uri?.let { updateBackground(it) }
}
private fun makeResult() {
val data = Intent()
data.putExtra(EXTRA_COLUMN_INDEX, columnIndex)
setResult(RESULT_OK, data)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
backPressed {
makeResult()
finish()
}
arColumnBackgroundImage.register(this)
App1.setActivityTheme(this)
initUI()
appState = App1.getAppState(this)
density = appState.density
columnIndex = intent.getIntExtra(EXTRA_COLUMN_INDEX, 0)
column = appState.column(columnIndex)!!
show()
}
override fun onDestroy() {
closeBitmaps()
super.onDestroy()
}
override fun onClick(v: View) {
val builder: ColorPickerDialog.Builder
when (v.id) {
R.id.btnHeaderBackgroundEdit -> {
ColorPickerDialog.newBuilder()
.setDialogType(ColorPickerDialog.TYPE_CUSTOM)
.setAllowPresets(true)
.setShowAlphaSlider(false)
.setDialogId(COLOR_DIALOG_ID_HEADER_BACKGROUND)
.setColor(column.getHeaderBackgroundColor())
.show(this)
}
R.id.btnHeaderBackgroundReset -> {
column.headerBgColor = 0
show()
}
R.id.btnHeaderTextEdit -> {
ColorPickerDialog.newBuilder()
.setDialogType(ColorPickerDialog.TYPE_CUSTOM)
.setAllowPresets(true)
.setShowAlphaSlider(false)
.setDialogId(COLOR_DIALOG_ID_HEADER_FOREGROUND)
.setColor(column.getHeaderNameColor())
.show(this)
}
R.id.btnHeaderTextReset -> {
column.headerFgColor = 0
show()
}
R.id.btnColumnBackgroundColor -> {
builder = ColorPickerDialog.newBuilder()
.setDialogType(ColorPickerDialog.TYPE_CUSTOM)
.setAllowPresets(true)
.setShowAlphaSlider(false)
.setDialogId(COLOR_DIALOG_ID_COLUMN_BACKGROUND)
if (column.columnBgColor != 0) builder.setColor(column.columnBgColor)
builder.show(this)
}
R.id.btnColumnBackgroundColorReset -> {
column.columnBgColor = 0
show()
}
R.id.btnAcctColor -> {
ColorPickerDialog.newBuilder()
.setDialogType(ColorPickerDialog.TYPE_CUSTOM)
.setAllowPresets(true)
.setShowAlphaSlider(true)
.setDialogId(COLOR_DIALOG_ID_ACCT_TEXT)
.setColor(column.getAcctColor())
.show(this)
}
R.id.btnAcctColorReset -> {
column.acctColor = 0
show()
}
R.id.btnContentColor -> {
ColorPickerDialog.newBuilder()
.setDialogType(ColorPickerDialog.TYPE_CUSTOM)
.setAllowPresets(true)
.setShowAlphaSlider(true)
.setDialogId(COLOR_DIALOG_ID_CONTENT_TEXT)
.setColor(column.getContentColor())
.show(this)
}
R.id.btnContentColorReset -> {
column.contentColor = 0
show()
}
R.id.btnColumnBackgroundImage -> {
val intent =
intentGetContent(
false,
getString(R.string.pick_image),
arrayOf("image/*")
)
arColumnBackgroundImage.launch(intent)
}
R.id.btnColumnBackgroundImageReset -> {
column.columnBgImage = ""
show()
}
}
}
override fun onColorSelected(dialogId: Int, @ColorInt newColor: Int) {
when (dialogId) {
COLOR_DIALOG_ID_HEADER_BACKGROUND ->
column.headerBgColor = Color.BLACK or newColor
COLOR_DIALOG_ID_HEADER_FOREGROUND ->
column.headerFgColor = Color.BLACK or newColor
COLOR_DIALOG_ID_COLUMN_BACKGROUND ->
column.columnBgColor = Color.BLACK or newColor
COLOR_DIALOG_ID_ACCT_TEXT ->
column.acctColor = newColor.notZero() ?: 1
COLOR_DIALOG_ID_CONTENT_TEXT ->
column.contentColor = newColor.notZero() ?: 1
}
show()
}
override fun onDialogDismissed(dialogId: Int) {}
private fun updateBackground(uriArg: Uri) {
launchMain {
var resultUri: String? = null
runApiTask { client ->
try {
val backgroundDir = getBackgroundImageDir(this@ActColumnCustomize)
val file =
File(backgroundDir, "${column.columnId}:${System.currentTimeMillis()}")
val fileUri = Uri.fromFile(file)
client.publishApiProgress("loading image from $uriArg")
contentResolver.openInputStream(uriArg)?.use { inStream ->
FileOutputStream(file).use { outStream ->
inStream.copyTo(outStream)
}
}
// リサイズや回転が必要ならする
client.publishApiProgress("check resize/rotation…")
val size = (max(
resources.displayMetrics.widthPixels,
resources.displayMetrics.heightPixels
) * 1.5f).toInt()
val bitmap = createResizedBitmap(
this,
fileUri,
size,
skipIfNoNeedToResizeAndRotate = true,
)
if (bitmap != null) {
try {
client.publishApiProgress("save resized(${bitmap.width}x${bitmap.height}) image to $file")
FileOutputStream(file).use { os ->
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os)
}
} finally {
bitmap.recycle()
}
}
resultUri = fileUri.toString()
TootApiResult()
} catch (ex: Throwable) {
log.trace(ex)
TootApiResult(ex.withCaption("can't update background image."))
}
}?.let { result ->
when (val bgUri = resultUri) {
null -> showToast(true, result.error ?: "?")
else -> {
column.columnBgImage = bgUri
show()
}
}
}
}
}
private fun initUI() {
setContentView(R.layout.act_column_customize)
App1.initEdgeToEdge(this)
Styler.fixHorizontalPadding(findViewById(R.id.svContent))
llColumnHeader = findViewById(R.id.llColumnHeader)
ivColumnHeader = findViewById(R.id.ivColumnHeader)
tvColumnName = findViewById(R.id.tvColumnName)
flColumnBackground = findViewById(R.id.flColumnBackground)
ivColumnBackground = findViewById(R.id.ivColumnBackground)
tvSampleAcct = findViewById(R.id.tvSampleAcct)
tvSampleContent = findViewById(R.id.tvSampleContent)
findViewById<View>(R.id.btnHeaderBackgroundEdit).setOnClickListener(this)
findViewById<View>(R.id.btnHeaderBackgroundReset).setOnClickListener(this)
findViewById<View>(R.id.btnHeaderTextEdit).setOnClickListener(this)
findViewById<View>(R.id.btnHeaderTextReset).setOnClickListener(this)
findViewById<View>(R.id.btnColumnBackgroundColor).setOnClickListener(this)
findViewById<View>(R.id.btnColumnBackgroundColorReset).setOnClickListener(this)
findViewById<View>(R.id.btnColumnBackgroundImage).setOnClickListener(this)
findViewById<View>(R.id.btnColumnBackgroundImageReset).setOnClickListener(this)
findViewById<View>(R.id.btnAcctColor).setOnClickListener(this)
findViewById<View>(R.id.btnAcctColorReset).setOnClickListener(this)
findViewById<View>(R.id.btnContentColor).setOnClickListener(this)
findViewById<View>(R.id.btnContentColorReset).setOnClickListener(this)
sbColumnBackgroundAlpha = findViewById(R.id.sbColumnBackgroundAlpha)
sbColumnBackgroundAlpha.max = PROGRESS_MAX
sbColumnBackgroundAlpha.setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (loadingBusy) return
if (!fromUser) return
column.columnBgImageAlpha = progress / PROGRESS_MAX.toFloat()
ivColumnBackground.alpha = column.columnBgImageAlpha
etAlpha.setText(
String.format(
defaultLocale(this@ActColumnCustomize),
"%.4f",
column.columnBgImageAlpha
)
)
}
})
etAlpha = findViewById(R.id.etAlpha)
etAlpha.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
if (loadingBusy) return
try {
var f = NumberFormat.getInstance(defaultLocale(this@ActColumnCustomize))
.parse(etAlpha.text.toString())?.toFloat()
if (f != null && !f.isNaN()) {
if (f < 0f) f = 0f
if (f > 1f) f = 1f
column.columnBgImageAlpha = f
ivColumnBackground.alpha = column.columnBgImageAlpha
sbColumnBackgroundAlpha.progress = (0.5f + f * PROGRESS_MAX).toInt()
}
} catch (ex: Throwable) {
log.e(ex, "alpha parse failed.")
}
}
})
etAlpha.setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_DONE -> {
etAlpha.hideKeyboard()
true
}
else -> false
}
}
}
private fun show() {
try {
loadingBusy = true
column.setHeaderBackground(llColumnHeader)
val c = column.getHeaderNameColor()
tvColumnName.textColor = c
ivColumnHeader.setImageResource(column.getIconId())
ivColumnHeader.imageTintList = ColorStateList.valueOf(c)
tvColumnName.text = column.getColumnName(false)
if (column.columnBgColor != 0) {
flColumnBackground.setBackgroundColor(column.columnBgColor)
} else {
ViewCompat.setBackground(flColumnBackground, null)
}
var alpha = column.columnBgImageAlpha
if (alpha.isNaN()) {
alpha = 1f
column.columnBgImageAlpha = alpha
}
ivColumnBackground.alpha = alpha
sbColumnBackgroundAlpha.progress = (0.5f + alpha * PROGRESS_MAX).toInt()
etAlpha.setText(
String.format(
defaultLocale(this@ActColumnCustomize),
"%.4f",
column.columnBgImageAlpha
)
)
loadImage(ivColumnBackground, column.columnBgImage)
tvSampleAcct.setTextColor(column.getAcctColor())
tvSampleContent.setTextColor(column.getContentColor())
} finally {
loadingBusy = false
}
}
private fun closeBitmaps() {
try {
ivColumnBackground.setImageDrawable(null)
lastImageUri = null
lastImageBitmap?.recycle()
lastImageBitmap = null
} catch (ex: Throwable) {
log.trace(ex)
}
}
private fun loadImage(ivColumnBackground: ImageView, url: String) {
try {
if (url.isEmpty()) {
closeBitmaps()
return
} else if (url == lastImageUri) {
// 今表示してるのと同じ
return
}
// 直前のBitmapを掃除する
closeBitmaps()
val uri = url.mayUri() ?: return
// 画像をロードして、成功したら表示してURLを覚える
val resizeMax = (0.5f + 64f * density).toInt()
lastImageBitmap = createResizedBitmap(this, uri, resizeMax)
if (lastImageBitmap != null) {
ivColumnBackground.setImageBitmap(lastImageBitmap)
lastImageUri = url
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
| apache-2.0 | c8cba91918a0ea437ff11195bb8e1e2d | 34.877996 | 118 | 0.548237 | 5.225996 | false | false | false | false |
airbnb/epoxy | epoxy-processor/src/main/java/com/airbnb/epoxy/processor/HashCodeValidator.kt | 1 | 7259 | package com.airbnb.epoxy.processor
import androidx.room.compiler.processing.XArrayType
import androidx.room.compiler.processing.XProcessingEnv
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XTypeElement
import androidx.room.compiler.processing.isArray
import androidx.room.compiler.processing.isEnum
import androidx.room.compiler.processing.isEnumEntry
import com.airbnb.epoxy.processor.Utils.getMethodOnClass
import com.airbnb.epoxy.processor.Utils.isIterableType
import com.airbnb.epoxy.processor.Utils.isMap
import com.airbnb.epoxy.processor.Utils.throwError
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.TypeName
/** Validates that an attribute implements hashCode and equals. */
internal class HashCodeValidator(
private val environment: XProcessingEnv,
private val memoizer: Memoizer,
val logger: Logger,
) {
fun implementsHashCodeAndEquals(mirror: XType): Boolean {
return try {
validateImplementsHashCode(mirror)
true
} catch (e: EpoxyProcessorException) {
false
}
}
@Throws(EpoxyProcessorException::class)
fun validate(attribute: AttributeInfo) {
try {
validateImplementsHashCode(attribute.xType)
} catch (e: EpoxyProcessorException) {
// Append information about the attribute and class to the existing exception
logger.logError(
e.message +
" (%s) Epoxy requires every model attribute to implement equals and hashCode " +
"so that changes in the model " +
"can be tracked. If you want the attribute to be excluded, use " +
"the option 'DoNotHash'. If you want to ignore this warning use " +
"the option 'IgnoreRequireHashCode'",
attribute
)
}
}
@Throws(EpoxyProcessorException::class)
private fun validateImplementsHashCode(xType: XType) {
if (xType.isError()) {
// The class type cannot be resolved. This may be because it is a generated epoxy model and
// the class hasn't been built yet.
// We just assume that the class will implement hashCode at runtime.
return
}
if (xType.typeName.isPrimitive || xType.typeName.isBoxedPrimitive) {
return
}
if (xType.isArray()) {
validateArrayType(xType)
return
}
val xTypeElement = xType.typeElement ?: return
if (xTypeElement.isDataClass() || xTypeElement.isEnum() || xTypeElement.isEnumEntry() || xTypeElement.isValueClass()) {
return
}
if (xType.isMap(environment)) {
// as part of ksp conversion we need to add this to maintain legacy behavior because
// java Maps implement equals/hashcode so they are automatically approved, even
// though we never verified the key/value type implements it. Not adding it
// now to avoid breaking existing code.
return
}
if (isIterableType(xType, memoizer)) {
validateIterableType(xType)
return
}
if (isAutoValueType(xTypeElement)) {
return
}
if (isWhiteListedType(xTypeElement)) {
return
}
if (!hasHashCodeInClassHierarchy(xTypeElement)) {
throwError("Attribute does not implement hashCode")
}
if (!hasEqualsInClassHierarchy(xTypeElement)) {
throwError("Attribute does not implement equals")
}
}
private fun hasHashCodeInClassHierarchy(clazz: XTypeElement): Boolean {
return hasFunctionInClassHierarchy(clazz, HASH_CODE_METHOD)
}
private fun hasEqualsInClassHierarchy(clazz: XTypeElement): Boolean {
return hasFunctionInClassHierarchy(clazz, EQUALS_METHOD)
}
private fun hasFunctionInClassHierarchy(clazz: XTypeElement, function: MethodSpec): Boolean {
val methodOnClass = getMethodOnClass(clazz, function, environment)
?: return false
val implementingClass = methodOnClass.enclosingElement as? XTypeElement
return implementingClass?.name != "Object" && implementingClass?.type?.isObjectOrAny() != true
// We don't care if the method is abstract or not, as long as it exists and it isn't the Object
// implementation then the runtime value will implement it to some degree (hopefully
// correctly :P)
}
@Throws(EpoxyProcessorException::class)
private fun validateArrayType(mirror: XArrayType) {
// Check that the type of the array implements hashCode
val arrayType = mirror.componentType
try {
validateImplementsHashCode(arrayType)
} catch (e: EpoxyProcessorException) {
throwError(
"Type in array does not implement hashCode. Type: %s",
arrayType.toString()
)
}
}
@Throws(EpoxyProcessorException::class)
private fun validateIterableType(type: XType) {
for (typeParameter in type.typeArguments) {
// check that the type implements hashCode
try {
validateImplementsHashCode(typeParameter)
} catch (e: EpoxyProcessorException) {
throwError(
"Type in Iterable does not implement hashCode. Type: %s",
typeParameter.toString()
)
}
}
// Assume that the iterable class implements hashCode and just return
}
private fun isWhiteListedType(element: XTypeElement): Boolean {
return element.isSubTypeOf(memoizer.charSequenceType)
}
/**
* Returns true if this class is expected to be implemented via a generated autovalue class,
* which implies it will have equals/hashcode at runtime.
*/
private fun isAutoValueType(element: XTypeElement): Boolean {
// For migrating away from autovalue and copying autovalue sources to version control (and therefore
// removing annotations and compile time generation) the annotation lookup no longer works.
// Instead, assume that if a type is abstract then it has a runtime implementation the properly
// implements equals/hashcode.
if (element.isAbstract() && !element.isInterface()) return true
// Only works for classes in the module since AutoValue has a retention of Source so it is
// discarded after compilation.
for (xAnnotation in element.getAllAnnotations()) {
// Avoid type resolution as simple name should be enough
val isAutoValue = xAnnotation.name == "AutoValue"
if (isAutoValue) {
return true
}
}
return false
}
companion object {
private val HASH_CODE_METHOD = MethodSpec.methodBuilder("hashCode")
.returns(TypeName.INT)
.build()
private val EQUALS_METHOD = MethodSpec.methodBuilder("equals")
.addParameter(TypeName.OBJECT, "obj")
.returns(TypeName.BOOLEAN)
.build()
}
}
| apache-2.0 | 0712140a80551d7ca3f48c8424891a1f | 38.026882 | 127 | 0.642926 | 5.115574 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/utils/PluginInfoDetector.kt | 1 | 3163 | // 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.internal.statistic.utils
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.openapi.extensions.PluginId
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported
*/
fun getPluginInfo(clazz: Class<*>): PluginInfo {
val className = clazz.name
if (className.startsWith("java.") || className.startsWith("javax.") ||
className.startsWith("kotlin.") || className.startsWith("groovy.")) {
return platformPlugin
}
val pluginId = PluginManagerCore.getPluginOrPlatformByClassName(className) ?: return unknownPlugin
if (PluginManagerCore.CORE_PLUGIN_ID == pluginId.idString) {
return platformPlugin
}
return getPluginInfoById(pluginId)
}
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported
*/
fun getPluginInfoById(pluginId: PluginId?): PluginInfo {
if (pluginId == null) return unknownPlugin
return getPluginInfoByDescriptor(PluginManager.getPlugin(pluginId))
}
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported
*/
fun getPluginInfoByDescriptor(plugin: IdeaPluginDescriptor?): PluginInfo {
if (plugin == null) return unknownPlugin
val id = plugin.pluginId.idString
if (PluginManagerMain.isDevelopedByJetBrains(plugin)) {
return if (plugin.isBundled) {
PluginInfo(PluginType.JB_BUNDLED, id)
}
else {
PluginInfo(PluginType.JB_NOT_BUNDLED, id)
}
}
// only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance -
// they are also considered bundled) would be reported
val listed = !plugin.isBundled && isSafeToReport(id)
return if (listed) {
PluginInfo(PluginType.LISTED, id)
}
else {
notListedPlugin
}
}
enum class PluginType {
PLATFORM, JB_BUNDLED, JB_NOT_BUNDLED, LISTED, NOT_LISTED, UNKNOWN;
fun isPlatformOrJBBundled(): Boolean {
return this == PLATFORM || this == JB_BUNDLED
}
fun isDevelopedByJetBrains(): Boolean {
return isPlatformOrJBBundled() || this == JB_NOT_BUNDLED
}
fun isSafeToReport(): Boolean {
return isDevelopedByJetBrains() || this == LISTED
}
}
class PluginInfo(val type: PluginType, val id: String?) {
fun isDevelopedByJetBrains(): Boolean {
return type.isDevelopedByJetBrains()
}
fun isSafeToReport(): Boolean {
return type.isSafeToReport()
}
}
val platformPlugin: PluginInfo = PluginInfo(PluginType.PLATFORM, null)
val unknownPlugin: PluginInfo = PluginInfo(PluginType.UNKNOWN, null)
val notListedPlugin: PluginInfo = PluginInfo(PluginType.NOT_LISTED, null) | apache-2.0 | caf55bd790d705bd3f494b3aa346940c | 32.305263 | 140 | 0.745811 | 4.393056 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/impl-base/src/org/jetbrains/kotlin/idea/codeinsights/impl/base/quickFix/GenerateFunctionFix.kt | 1 | 1514 | // 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.codeinsights.impl.base.quickFix
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferences
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
abstract class GenerateFunctionFix(private val functionDefinitionText: String, private val bodyText: String) : LocalQuickFix {
override fun getFamilyName() = name
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return
val klass = descriptor.psiElement.getNonStrictParentOfType<KtClass>() ?: return
val factory = KtPsiFactory(klass)
runWriteAction {
val function = factory.createFunction(functionDefinitionText)
shortenReferences(function)
if (bodyText.isNotEmpty()) function.bodyExpression?.replace(factory.createBlock(bodyText))
klass.addDeclaration(function)
}
}
} | apache-2.0 | 75d809cceb4ecd36f0759a61b0b200e6 | 47.870968 | 126 | 0.784016 | 5.132203 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt | 1 | 5791 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections.branchedTransformations
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.formatter.rightMarginOrDefault
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.*
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import javax.swing.JComponent
class IfThenToElvisInspection @JvmOverloads constructor(
@JvmField var highlightStatement: Boolean = false,
private val inlineWithPrompt: Boolean = true
) : AbstractApplicabilityBasedInspection<KtIfExpression>(KtIfExpression::class.java) {
override fun inspectionText(element: KtIfExpression): String = KotlinBundle.message("if.then.foldable.to")
override val defaultFixText: String get() = INTENTION_TEXT
override fun isApplicable(element: KtIfExpression): Boolean = isApplicableTo(element, expressionShouldBeStable = true)
override fun inspectionHighlightType(element: KtIfExpression): ProblemHighlightType =
if (element.shouldBeTransformed() && (highlightStatement || element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))))
super.inspectionHighlightType(element)
else
ProblemHighlightType.INFORMATION
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
convert(element, editor, inlineWithPrompt)
}
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.fromIfKeywordToRightParenthesisTextRangeInThis()
override fun createOptionsPanel(): JComponent = MultipleCheckboxOptionsPanel(this).also {
it.addCheckbox(KotlinBundle.message("report.also.on.statement"), "highlightStatement")
}
companion object {
val INTENTION_TEXT get() = KotlinBundle.message("replace.if.expression.with.elvis.expression")
fun convert(element: KtIfExpression, editor: Editor?, inlineWithPrompt: Boolean) {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return
val psiFactory = KtPsiFactory(element.project)
val commentSaver = CommentSaver(element, saveLineBreaks = false)
val margin = element.containingKtFile.rightMarginOrDefault
val elvis = runWriteAction {
val replacedBaseClause = ifThenToSelectData.replacedBaseClause(psiFactory)
val negatedClause = ifThenToSelectData.negatedClause!!
val newExpr = element.replaced(
psiFactory.createExpressionByPattern(
elvisPattern(replacedBaseClause.textLength + negatedClause.textLength + 5 >= margin),
replacedBaseClause,
negatedClause
)
)
(KtPsiUtil.deparenthesize(newExpr) as KtBinaryExpression).also {
commentSaver.restore(it)
}
}
if (editor != null) {
elvis.inlineLeftSideIfApplicable(editor, inlineWithPrompt)
with(IfThenToSafeAccessInspection) {
(elvis.left as? KtSafeQualifiedExpression)?.renameLetParameter(editor)
}
}
}
fun isApplicableTo(element: KtIfExpression, expressionShouldBeStable: Boolean): Boolean {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return false
if (expressionShouldBeStable &&
!ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context)
) return false
val type = element.getType(ifThenToSelectData.context) ?: return false
if (KotlinBuiltIns.isUnit(type)) return false
return ifThenToSelectData.clausesReplaceableByElvis()
}
private fun KtExpression.isNullOrBlockExpression(): Boolean {
val innerExpression = this.unwrapBlockOrParenthesis()
return innerExpression is KtBlockExpression || innerExpression.node.elementType == KtNodeTypes.NULL
}
private fun IfThenToSelectData.clausesReplaceableByElvis(): Boolean =
when {
baseClause == null || negatedClause == null || negatedClause.isNullOrBlockExpression() ->
false
negatedClause is KtThrowExpression && negatedClause.throwsNullPointerExceptionWithNoArguments() ->
false
baseClause.evaluatesTo(receiverExpression) ->
true
baseClause.anyArgumentEvaluatesTo(receiverExpression) ->
true
hasImplicitReceiverReplaceableBySafeCall() || baseClause.hasFirstReceiverOf(receiverExpression) ->
!baseClause.hasNullableType(context)
else ->
false
}
}
}
| apache-2.0 | d74d8fc8e1e44bd2fa453bc274a5effb | 48.076271 | 147 | 0.70575 | 5.584378 | false | false | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/Cell.kt | 1 | 29753 | // 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.layout
import com.intellij.BundleBase
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.util.bind
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.emptyText
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsContexts.*
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.*
import com.intellij.ui.components.*
import com.intellij.ui.components.fields.ExpandableTextField
import com.intellij.util.Function
import com.intellij.util.execution.ParametersListUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.awt.Component
import java.awt.Dimension
import java.awt.event.*
import java.util.*
import javax.swing.*
import javax.swing.text.JTextComponent
import kotlin.jvm.internal.CallableReference
import kotlin.reflect.KMutableProperty0
@DslMarker
annotation class CellMarker
data class PropertyBinding<V>(val get: () -> V, val set: (V) -> Unit)
@PublishedApi
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
internal fun <T> createPropertyBinding(prop: KMutableProperty0<T>, propType: Class<T>): PropertyBinding<T> {
if (prop is CallableReference) {
val name = prop.name
val receiver = (prop as CallableReference).boundReceiver
if (receiver != null) {
val baseName = name.removePrefix("is")
val nameCapitalized = StringUtil.capitalize(baseName)
val getterName = if (name.startsWith("is")) name else "get$nameCapitalized"
val setterName = "set$nameCapitalized"
val receiverClass = receiver::class.java
try {
val getter = receiverClass.getMethod(getterName)
val setter = receiverClass.getMethod(setterName, propType)
return PropertyBinding({ getter.invoke(receiver) as T }, { setter.invoke(receiver, it) })
}
catch (e: Exception) {
// ignore
}
try {
val field = receiverClass.getDeclaredField(name)
field.isAccessible = true
return PropertyBinding({ field.get(receiver) as T }, { field.set(receiver, it) })
}
catch (e: Exception) {
// ignore
}
}
}
return PropertyBinding(prop.getter, prop.setter)
}
@Deprecated("Use MutableProperty and Kotlin UI DSL 2")
fun <T> PropertyBinding<T>.toNullable(): PropertyBinding<T?> {
return PropertyBinding<T?>({ get() }, { set(it!!) })
}
inline fun <reified T : Any> KMutableProperty0<T>.toBinding(): PropertyBinding<T> {
return createPropertyBinding(this, T::class.javaPrimitiveType ?: T::class.java)
}
@Deprecated("Use Kotlin UI DSL Version 2")
inline fun <reified T : Any> KMutableProperty0<T?>.toNullableBinding(defaultValue: T): PropertyBinding<T> {
return PropertyBinding({ get() ?: defaultValue }, { set(it) })
}
class ValidationInfoBuilder(val component: JComponent) {
fun error(@DialogMessage message: String): ValidationInfo = ValidationInfo(message, component)
fun warning(@DialogMessage message: String): ValidationInfo = ValidationInfo(message, component).asWarning().withOKEnabled()
}
@JvmDefaultWithCompatibility
interface CellBuilder<out T : JComponent> {
val component: T
@Deprecated("Use Kotlin UI DSL 2")
fun comment(@DetailedDescription text: String, maxLineLength: Int = ComponentPanelBuilder.MAX_COMMENT_WIDTH,
forComponent: Boolean = false): CellBuilder<T>
fun focused(): CellBuilder<T>
fun withValidationOnApply(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T>
fun withValidationOnInput(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T>
fun onApply(callback: () -> Unit): CellBuilder<T>
fun onReset(callback: () -> Unit): CellBuilder<T>
fun onIsModified(callback: () -> Boolean): CellBuilder<T>
/**
* All components of the same group share will get the same BoundSize (min/preferred/max),
* which is that of the biggest component in the group
*/
@Deprecated("Use Kotlin UI DSL Version 2, see Cell.widthGroup()")
fun sizeGroup(name: String): CellBuilder<T>
@Deprecated("Use Kotlin UI DSL Version 2")
fun growPolicy(growPolicy: GrowPolicy): CellBuilder<T>
fun constraints(vararg constraints: CCFlags): CellBuilder<T>
/**
* If this method is called, the value of the component will be stored to the backing property only if the component is enabled.
*/
@Deprecated("Use Kotlin UI DSL Version 2")
fun applyIfEnabled(): CellBuilder<T>
@Deprecated("Use Kotlin UI DSL Version 2")
fun accessibleName(@Nls name: String): CellBuilder<T> {
component.accessibleContext.accessibleName = name
return this
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun accessibleDescription(@Nls description: String): CellBuilder<T> {
component.accessibleContext.accessibleDescription = description
return this
}
fun <V> withBinding(
componentGet: (T) -> V,
componentSet: (T, V) -> Unit,
modelBinding: PropertyBinding<V>
): CellBuilder<T> {
onApply { if (shouldSaveOnApply()) modelBinding.set(componentGet(component)) }
onReset { componentSet(component, modelBinding.get()) }
onIsModified { shouldSaveOnApply() && componentGet(component) != modelBinding.get() }
return this
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun withGraphProperty(property: GraphProperty<*>): CellBuilder<T>
fun enabled(isEnabled: Boolean)
fun enableIf(predicate: ComponentPredicate): CellBuilder<T>
fun visible(isVisible: Boolean)
fun visibleIf(predicate: ComponentPredicate): CellBuilder<T>
@Deprecated("Use Kotlin UI DSL Version 2")
fun withErrorOnApplyIf(@DialogMessage message: String, callback: (T) -> Boolean): CellBuilder<T> {
withValidationOnApply { if (callback(it)) error(message) else null }
return this
}
@Deprecated("Use Kotlin UI DSL Version 2")
@ApiStatus.Internal
fun shouldSaveOnApply(): Boolean
@Deprecated("Use Kotlin UI DSL Version 2")
fun withLargeLeftGap(): CellBuilder<T>
@Deprecated("Use Kotlin UI DSL Version 2")
fun withLeftGap(): CellBuilder<T>
@Deprecated("Prefer not to use hardcoded values")
@ApiStatus.ScheduledForRemoval
fun withLeftGap(gapLeft: Int): CellBuilder<T>
}
@Deprecated("Use Kotlin UI DSL Version 2")
internal interface CheckboxCellBuilder {
@Deprecated("Use Kotlin UI DSL Version 2")
fun actsAsLabel()
}
@Deprecated("Use Kotlin UI DSL Version 2", level = DeprecationLevel.HIDDEN)
fun <T : JCheckBox> CellBuilder<T>.actsAsLabel(): CellBuilder<T> {
(this as CheckboxCellBuilder).actsAsLabel()
return this
}
fun <T : JComponent> CellBuilder<T>.applyToComponent(task: T.() -> Unit): CellBuilder<T> {
return also { task(component) }
}
@Deprecated("Use Kotlin UI DSL Version 2")
internal interface ScrollPaneCellBuilder {
@Deprecated("Use Kotlin UI DSL Version 2")
fun noGrowY()
}
@Deprecated("Use Kotlin UI DSL Version 2", level = DeprecationLevel.HIDDEN)
fun <T : JScrollPane> CellBuilder<T>.noGrowY(): CellBuilder<T> {
(this as ScrollPaneCellBuilder).noGrowY()
return this
}
fun <T : JTextComponent> CellBuilder<T>.withTextBinding(modelBinding: PropertyBinding<String>): CellBuilder<T> {
return withBinding(JTextComponent::getText, JTextComponent::setText, modelBinding)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun <T : AbstractButton> CellBuilder<T>.withSelectedBinding(modelBinding: PropertyBinding<Boolean>): CellBuilder<T> {
return withBinding(AbstractButton::isSelected, AbstractButton::setSelected, modelBinding)
}
@Deprecated("Use Kotlin UI DSL Version 2")
val CellBuilder<AbstractButton>.selected
get() = component.selected
@Deprecated("Use Kotlin UI DSL Version 2")
const val UNBOUND_RADIO_BUTTON = "unbound.radio.button"
// separate class to avoid row related methods in the `cell { } `
@CellMarker
abstract class Cell : BaseBuilder {
/**
* Sets how keen the component should be to grow in relation to other component **in the same cell**. Use `push` in addition if need.
* If this constraint is not set the grow weight is set to 0 and the component will not grow (unless some automatic rule is not applied (see [com.intellij.ui.layout.panel])).
* Grow weight will only be compared against the weights for the same cell.
*/
val growX = CCFlags.growX
val growY = CCFlags.growY
val grow = CCFlags.grow
/**
* Makes the column that the component is residing in grow with `weight`.
*/
val pushX = CCFlags.pushX
/**
* Makes the row that the component is residing in grow with `weight`.
*/
val pushY = CCFlags.pushY
val push = CCFlags.push
fun label(@Label text: String,
style: UIUtil.ComponentStyle? = null,
fontColor: UIUtil.FontColor? = null,
bold: Boolean = false): CellBuilder<JLabel> {
val label = Label(text, style, fontColor, bold)
return component(label)
}
fun label(@Label text: String,
font: JBFont,
fontColor: UIUtil.FontColor? = null): CellBuilder<JLabel> {
val label = Label(text, fontColor = fontColor, font = font)
return component(label)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun link(@LinkLabel text: String,
style: UIUtil.ComponentStyle? = null,
action: () -> Unit): CellBuilder<JComponent> {
val result = Link(text, style, action)
return component(result)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun browserLink(@LinkLabel text: String, url: String): CellBuilder<JComponent> {
val result = BrowserLink(text, url)
return component(result)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun buttonFromAction(@Button text: String, @NonNls actionPlace: String, action: AnAction): CellBuilder<JButton> {
val button = JButton(BundleBase.replaceMnemonicAmpersand(text))
button.addActionListener { ActionUtil.invokeAction(action, button, actionPlace, null, null) }
return component(button)
}
fun button(@Button text: String, actionListener: (event: ActionEvent) -> Unit): CellBuilder<JButton> {
val button = JButton(BundleBase.replaceMnemonicAmpersand(text))
button.addActionListener(actionListener)
return component(button)
}
inline fun checkBox(@Checkbox text: String,
isSelected: Boolean = false,
@DetailedDescription comment: String? = null,
crossinline actionListener: (event: ActionEvent, component: JCheckBox) -> Unit): CellBuilder<JBCheckBox> {
return checkBox(text, isSelected, comment)
.applyToComponent {
addActionListener(ActionListener { actionListener(it, this) })
}
}
@JvmOverloads
fun checkBox(@Checkbox text: String,
isSelected: Boolean = false,
@DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> {
val result = JBCheckBox(text, isSelected)
return result(comment = comment)
}
fun checkBox(@Checkbox text: String, prop: KMutableProperty0<Boolean>, @DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> {
return checkBox(text, prop.toBinding(), comment)
}
fun checkBox(@Checkbox text: String, getter: () -> Boolean, setter: (Boolean) -> Unit, @DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> {
return checkBox(text, PropertyBinding(getter, setter), comment)
}
private fun checkBox(@Checkbox text: String,
modelBinding: PropertyBinding<Boolean>,
@DetailedDescription comment: String?): CellBuilder<JBCheckBox> {
val component = JBCheckBox(text, modelBinding.get())
return component(comment = comment).withSelectedBinding(modelBinding)
}
fun checkBox(@Checkbox text: String,
property: GraphProperty<Boolean>,
@DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> {
val component = JBCheckBox(text, property.get())
return component(comment = comment).withGraphProperty(property).applyToComponent { component.bind(property) }
}
@Deprecated("Use Kotlin UI DSL Version 2")
open fun radioButton(@RadioButton text: String, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text)
component.putClientProperty(UNBOUND_RADIO_BUTTON, true)
return component(comment = comment)
}
@Deprecated("Use Kotlin UI DSL Version 2")
open fun radioButton(@RadioButton text: String, getter: () -> Boolean, setter: (Boolean) -> Unit, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text, getter())
return component(comment = comment).withSelectedBinding(PropertyBinding(getter, setter))
}
@Deprecated("Use Kotlin UI DSL Version 2")
open fun radioButton(@RadioButton text: String, prop: KMutableProperty0<Boolean>, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text, prop.get())
return component(comment = comment).withSelectedBinding(prop.toBinding())
}
fun <T> comboBox(model: ComboBoxModel<T>,
getter: () -> T?,
setter: (T?) -> Unit,
renderer: ListCellRenderer<T?>? = null): CellBuilder<ComboBox<T>> {
return comboBox(model, PropertyBinding(getter, setter), renderer)
}
fun <T> comboBox(model: ComboBoxModel<T>,
modelBinding: PropertyBinding<T?>,
renderer: ListCellRenderer<T?>? = null): CellBuilder<ComboBox<T>> {
return component(ComboBox(model))
.applyToComponent {
this.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() }
selectedItem = modelBinding.get()
}
.withBinding(
{ component -> component.selectedItem as T? },
{ component, value -> component.setSelectedItem(value) },
modelBinding
)
}
inline fun <reified T : Any> comboBox(
model: ComboBoxModel<T>,
prop: KMutableProperty0<T>,
renderer: ListCellRenderer<T?>? = null
): CellBuilder<ComboBox<T>> {
return comboBox(model, prop.toBinding().toNullable(), renderer)
}
fun <T> comboBox(
model: ComboBoxModel<T>,
property: GraphProperty<T>,
renderer: ListCellRenderer<T?>? = null
): CellBuilder<ComboBox<T>> {
return comboBox(model, PropertyBinding(property::get, property::set).toNullable(), renderer)
.withGraphProperty(property)
.applyToComponent { bind(property) }
}
fun textField(prop: KMutableProperty0<String>, columns: Int? = null): CellBuilder<JBTextField> = textField(prop.toBinding(), columns)
fun textField(getter: () -> String, setter: (String) -> Unit, columns: Int? = null) = textField(PropertyBinding(getter, setter), columns)
fun textField(binding: PropertyBinding<String>, columns: Int? = null): CellBuilder<JBTextField> {
return component(JBTextField(binding.get(), columns ?: 0))
.withTextBinding(binding)
}
fun textField(property: GraphProperty<String>, columns: Int? = null): CellBuilder<JBTextField> {
return textField(property::get, property::set, columns)
.withGraphProperty(property)
.applyToComponent { bind(property) }
}
fun textArea(prop: KMutableProperty0<String>, rows: Int? = null, columns: Int? = null): CellBuilder<JBTextArea> = textArea(prop.toBinding(), rows, columns)
fun textArea(getter: () -> String, setter: (String) -> Unit, rows: Int? = null, columns: Int? = null) = textArea(PropertyBinding(getter, setter), rows, columns)
fun textArea(binding: PropertyBinding<String>, rows: Int? = null, columns: Int? = null): CellBuilder<JBTextArea> {
return component(JBTextArea(binding.get(), rows ?: 0, columns ?: 0))
.withTextBinding(binding)
}
fun textArea(property: GraphProperty<String>, rows: Int? = null, columns: Int? = null): CellBuilder<JBTextArea> {
return textArea(property::get, property::set, rows, columns)
.withGraphProperty(property)
.applyToComponent { bind(property) }
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun scrollableTextArea(prop: KMutableProperty0<String>, rows: Int? = null): CellBuilder<JBTextArea> = scrollableTextArea(prop.toBinding(), rows)
@Deprecated("Use Kotlin UI DSL Version 2")
fun scrollableTextArea(getter: () -> String, setter: (String) -> Unit, rows: Int? = null) = scrollableTextArea(PropertyBinding(getter, setter), rows)
private fun scrollableTextArea(binding: PropertyBinding<String>, rows: Int? = null): CellBuilder<JBTextArea> {
val textArea = JBTextArea(binding.get(), rows ?: 0, 0)
val scrollPane = JBScrollPane(textArea)
return component(textArea, scrollPane)
.withTextBinding(binding)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun scrollableTextArea(property: GraphProperty<String>, rows: Int? = null): CellBuilder<JBTextArea> {
return scrollableTextArea(property::get, property::set, rows)
.withGraphProperty(property)
.applyToComponent { bind(property) }
}
@JvmOverloads
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun intTextField(prop: KMutableProperty0<Int>, columns: Int? = null, range: IntRange? = null): CellBuilder<JBTextField> {
val binding = prop.toBinding()
return textField(
{ binding.get().toString() },
{ value -> value.toIntOrNull()?.let { intValue -> binding.set(range?.let { intValue.coerceIn(it.first, it.last) } ?: intValue) } },
columns
).withValidationOnInput {
val value = it.text.toIntOrNull()
when {
value == null -> error(UIBundle.message("please.enter.a.number"))
range != null && value !in range -> error(UIBundle.message("please.enter.a.number.from.0.to.1", range.first, range.last))
else -> null
}
}
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun spinner(prop: KMutableProperty0<Int>, minValue: Int, maxValue: Int, step: Int = 1): CellBuilder<JBIntSpinner> {
val spinner = JBIntSpinner(prop.get(), minValue, maxValue, step)
return component(spinner).withBinding(JBIntSpinner::getNumber, JBIntSpinner::setNumber, prop.toBinding())
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun spinner(getter: () -> Int, setter: (Int) -> Unit, minValue: Int, maxValue: Int, step: Int = 1): CellBuilder<JBIntSpinner> {
val spinner = JBIntSpinner(getter(), minValue, maxValue, step)
return component(spinner).withBinding(JBIntSpinner::getNumber, JBIntSpinner::setNumber, PropertyBinding(getter, setter))
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun textFieldWithHistoryWithBrowseButton(
getter: () -> String,
setter: (String) -> Unit,
@DialogTitle browseDialogTitle: String,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
historyProvider: (() -> List<String>)? = null,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithHistoryWithBrowseButton> {
val textField = textFieldWithHistoryWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, historyProvider, fileChosen)
val modelBinding = PropertyBinding(getter, setter)
textField.text = modelBinding.get()
return component(textField)
.withBinding(TextFieldWithHistoryWithBrowseButton::getText, TextFieldWithHistoryWithBrowseButton::setText, modelBinding)
}
fun textFieldWithBrowseButton(
@DialogTitle browseDialogTitle: String? = null,
value: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithBrowseButton> {
val textField = textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen)
if (value != null) textField.text = value
return component(textField)
}
fun textFieldWithBrowseButton(
prop: KMutableProperty0<String>,
@DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithBrowseButton> {
val modelBinding = prop.toBinding()
return textFieldWithBrowseButton(modelBinding, browseDialogTitle, project, fileChooserDescriptor, fileChosen)
}
fun textFieldWithBrowseButton(
getter: () -> String,
setter: (String) -> Unit,
@DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithBrowseButton> {
val modelBinding = PropertyBinding(getter, setter)
return textFieldWithBrowseButton(modelBinding, browseDialogTitle, project, fileChooserDescriptor, fileChosen)
}
fun textFieldWithBrowseButton(
modelBinding: PropertyBinding<String>,
@DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithBrowseButton> {
val textField = textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen)
textField.text = modelBinding.get()
return component(textField)
.constraints(growX)
.withBinding(TextFieldWithBrowseButton::getText, TextFieldWithBrowseButton::setText, modelBinding)
}
fun textFieldWithBrowseButton(
property: GraphProperty<String>,
emptyTextProperty: GraphProperty<String>,
@DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithBrowseButton> {
return textFieldWithBrowseButton(property, browseDialogTitle, project, fileChooserDescriptor, fileChosen)
.applyToComponent { emptyText.bind(emptyTextProperty) }
.applyToComponent { emptyText.text = emptyTextProperty.get() }
}
fun textFieldWithBrowseButton(
property: GraphProperty<String>,
@DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null
): CellBuilder<TextFieldWithBrowseButton> {
return textFieldWithBrowseButton(property::get, property::set, browseDialogTitle, project, fileChooserDescriptor, fileChosen)
.withGraphProperty(property)
.applyToComponent { bind(property) }
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun gearButton(vararg actions: AnAction): CellBuilder<JComponent> {
val label = JLabel(LayeredIcon.GEAR_WITH_DROPDOWN)
label.disabledIcon = AllIcons.General.GearPlain
object : ClickListener() {
override fun onClick(e: MouseEvent, clickCount: Int): Boolean {
if (!label.isEnabled) return true
JBPopupFactory.getInstance()
.createActionGroupPopup(null, DefaultActionGroup(*actions), DataManager.getInstance().getDataContext(label), true, null, 10)
.showUnderneathOf(label)
return true
}
}.installOn(label)
return component(label)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun expandableTextField(getter: () -> String,
setter: (String) -> Unit,
parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER,
joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER)
: CellBuilder<ExpandableTextField> {
return ExpandableTextField(parser, joiner)()
.withBinding({ editor -> editor.text.orEmpty() },
{ editor, value -> editor.text = value },
PropertyBinding(getter, setter))
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun expandableTextField(prop: KMutableProperty0<String>,
parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER,
joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER)
: CellBuilder<ExpandableTextField> {
return expandableTextField(prop::get, prop::set, parser, joiner)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun expandableTextField(prop: GraphProperty<String>,
parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER,
joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER)
: CellBuilder<ExpandableTextField> {
return expandableTextField(prop::get, prop::set, parser, joiner)
.withGraphProperty(prop)
.applyToComponent { bind(prop) }
}
/**
* @see LayoutBuilder.titledRow
*/
@JvmOverloads
fun panel(@BorderTitle title: String, wrappedComponent: Component, hasSeparator: Boolean = true): CellBuilder<JPanel> {
val panel = Panel(title, hasSeparator)
panel.add(wrappedComponent)
return component(panel)
}
fun scrollPane(component: Component): CellBuilder<JScrollPane> {
return component(JBScrollPane(component))
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun comment(@DetailedDescription text: String, maxLineLength: Int = -1): CellBuilder<JLabel> {
return component(ComponentPanelBuilder.createCommentComponent(text, true, maxLineLength, true))
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2", level = DeprecationLevel.HIDDEN)
fun commentNoWrap(@DetailedDescription text: String): CellBuilder<JLabel> {
return component(ComponentPanelBuilder.createNonWrappingCommentComponent(text))
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun placeholder(): CellBuilder<JComponent> {
return component(JPanel().apply {
minimumSize = Dimension(0, 0)
preferredSize = Dimension(0, 0)
maximumSize = Dimension(0, 0)
})
}
abstract fun <T : JComponent> component(component: T): CellBuilder<T>
abstract fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T>
operator fun <T : JComponent> T.invoke(
vararg constraints: CCFlags,
growPolicy: GrowPolicy? = null,
@DetailedDescription comment: String? = null
): CellBuilder<T> = component(this).apply {
constraints(*constraints)
if (comment != null) comment(comment)
if (growPolicy != null) growPolicy(growPolicy)
}
}
class InnerCell(val cell: Cell) : Cell() {
override fun <T : JComponent> component(component: T): CellBuilder<T> {
return cell.component(component)
}
override fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T> {
return cell.component(component, viewComponent)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2", level = DeprecationLevel.HIDDEN)
override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) {
cell.withButtonGroup(title, buttonGroup, body)
}
}
fun <T> listCellRenderer(renderer: SimpleListCellRenderer<T?>.(value: T, index: Int, isSelected: Boolean) -> Unit): SimpleListCellRenderer<T?> {
return object : SimpleListCellRenderer<T?>() {
override fun customize(list: JList<out T?>, value: T?, index: Int, selected: Boolean, hasFocus: Boolean) {
if (value != null) {
renderer(this, value, index, selected)
}
}
}
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun Cell.slider(min: Int, max: Int, minorTick: Int, majorTick: Int): CellBuilder<JSlider> {
val slider = JSlider()
UIUtil.setSliderIsFilled(slider, true)
slider.paintLabels = true
slider.paintTicks = true
slider.paintTrack = true
slider.minimum = min
slider.maximum = max
slider.minorTickSpacing = minorTick
slider.majorTickSpacing = majorTick
return slider()
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun <T : JSlider> CellBuilder<T>.labelTable(table: Hashtable<Int, JComponent>.() -> Unit): CellBuilder<T> {
component.labelTable = Hashtable<Int, JComponent>().apply(table)
return this
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun <T : JSlider> CellBuilder<T>.withValueBinding(modelBinding: PropertyBinding<Int>): CellBuilder<T> {
return withBinding(JSlider::getValue, JSlider::setValue, modelBinding)
}
| apache-2.0 | c7f2f2dd11cf717f8b370e3d2fbce151 | 40.438719 | 176 | 0.719289 | 4.643102 | false | false | false | false |
AppCraft-Projects/appcraft-kotlin-workshop | src/main/kotlin/workshop/kotlin/_03_data_classes/Size.kt | 1 | 830 | package workshop.kotlin._03_data_classes
import java.util.*
/**
* You can check this class in its original version at:
* https://github.com/Hexworks/zircon/blob/master/src/main/kotlin/org/codetome/zircon/api/Size.kt
*/
// TODO: create a `data class` `Size` based on the java Size class
class Size(val columns: Int, val rows: Int) {
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val size = o as Size?
return columns == size!!.columns && rows == size.rows
}
override fun hashCode(): Int {
return Objects.hash(columns, rows)
}
override fun toString(): String {
return "Size{" +
"columns=" + columns +
", rows=" + rows +
'}'
}
} | agpl-3.0 | e37a145889ad8a00ba152c88ea40fe18 | 27.655172 | 97 | 0.584337 | 3.896714 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/application/options/editor/CheckboxDescriptor.kt | 3 | 2079 | // 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.application.options.editor
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.search.BooleanOptionDescription
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.layout.*
import org.jetbrains.annotations.Nls
import javax.swing.JRadioButton
import kotlin.reflect.KMutableProperty0
class CheckboxDescriptor(@NlsContexts.Checkbox val name: String,
val binding: PropertyBinding<Boolean>,
@NlsContexts.DetailedDescription val comment: String? = null,
@Nls val groupName: String? = null) {
constructor(@NlsContexts.Checkbox name: String, mutableProperty: KMutableProperty0<Boolean>,
@NlsContexts.DetailedDescription comment: String? = null, @Nls groupName: String? = null)
: this(name, mutableProperty.toBinding(), comment, groupName)
fun asUiOptionDescriptor(): BooleanOptionDescription = asOptionDescriptor {
UISettings.instance.fireUISettingsChanged()
}
fun asOptionDescriptor(): BooleanOptionDescription = asOptionDescriptor(null)
fun asOptionDescriptor(fireUpdated: (() -> Unit)?): BooleanOptionDescription {
val optionName = when {
groupName != null -> {
val prefix = groupName.trim().removeSuffix(":")
"$prefix: $name"
}
else -> name
}
return object : BooleanOptionDescription(optionName, ID) {
override fun setOptionState(enabled: Boolean) {
binding.set(enabled)
fireUpdated?.invoke()
}
override fun isOptionEnabled() = binding.get.invoke()
}
}
}
fun Cell.checkBox(ui: CheckboxDescriptor): CellBuilder<JBCheckBox> {
return checkBox(ui.name, ui.binding.get, ui.binding.set, ui.comment)
}
fun Cell.radioButton(ui: CheckboxDescriptor): CellBuilder<JRadioButton> {
return radioButton(ui.name, ui.binding.get, ui.binding.set, ui.comment)
}
| apache-2.0 | 7e9ba48a34fbbf9592f3ed203b8c555f | 38.980769 | 140 | 0.718134 | 4.569231 | false | false | false | false |
allotria/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/execution/target/TargetProjectConnection.kt | 2 | 4083 | // 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.plugins.gradle.execution.target
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener
import com.intellij.openapi.externalSystem.service.execution.TargetEnvironmentConfigurationProvider
import com.intellij.openapi.util.UserDataHolderBase
import org.gradle.tooling.*
import org.gradle.tooling.internal.consumer.ConnectionParameters
import org.gradle.tooling.internal.consumer.PhasedBuildAction.BuildActionWrapper
import org.gradle.tooling.internal.consumer.ProjectConnectionCloseListener
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
@ApiStatus.Internal
internal class TargetProjectConnection(val environmentConfigurationProvider: TargetEnvironmentConfigurationProvider,
val taskId: ExternalSystemTaskId?,
val taskListener: ExternalSystemTaskNotificationListener?,
val distribution: TargetGradleDistribution,
val parameters: ConnectionParameters,
private val connectionCloseListener: ProjectConnectionCloseListener?) : ProjectConnection, UserDataHolderBase() {
override fun close() {
connectionCloseListener?.connectionClosed(this)
}
override fun <T : Any?> getModel(modelType: Class<T>): T = model(modelType).get()
override fun <T : Any?> getModel(modelType: Class<T>, resultHandler: ResultHandler<in T>) = model(modelType).get(resultHandler)
override fun newBuild(): BuildLauncher = TargetBuildLauncher(this)
override fun newTestLauncher(): TestLauncher {
TODO("Not yet implemented")
}
override fun <T : Any?> model(modelType: Class<T>): ModelBuilder<T> {
require(modelType.isInterface) { "Cannot fetch a model of type '${modelType.name}' as this type is not an interface." }
return TargetModelBuilder(this, modelType)
}
override fun <T : Any?> action(buildAction: BuildAction<T?>): BuildActionExecuter<T> = TargetBuildActionExecuter(this, buildAction)
override fun action(): BuildActionExecuter.Builder {
return object : BuildActionExecuter.Builder {
private var projectsLoadedAction: BuildActionWrapper<Any>? = null
private var buildFinishedAction: BuildActionWrapper<Any>? = null
override fun <T : Any?> projectsLoaded(buildAction: BuildAction<T>,
resultHandler: IntermediateResultHandler<in T>) = also {
@Suppress("UNCHECKED_CAST")
projectsLoadedAction = DefaultBuildActionWrapper(buildAction as BuildAction<Any>, resultHandler as IntermediateResultHandler<Any>)
}
override fun <T : Any?> buildFinished(buildAction: BuildAction<T>,
resultHandler: IntermediateResultHandler<in T>) = also {
@Suppress("UNCHECKED_CAST")
buildFinishedAction = DefaultBuildActionWrapper(buildAction as BuildAction<Any>, resultHandler as IntermediateResultHandler<Any>)
}
override fun build(): BuildActionExecuter<Void> = TargetPhasedBuildActionExecuter(this@TargetProjectConnection,
projectsLoadedAction, buildFinishedAction)
}
}
override fun notifyDaemonsAboutChangedPaths(p0: MutableList<Path>?) {
TODO("Not yet implemented")
}
fun disconnect() {
close()
clearUserData()
}
internal class DefaultBuildActionWrapper<T>(private val buildAction: BuildAction<T>,
private val resultHandler: IntermediateResultHandler<T>) : BuildActionWrapper<T> {
override fun getAction(): BuildAction<T> {
return buildAction
}
override fun getHandler(): IntermediateResultHandler<in T> {
return resultHandler
}
}
} | apache-2.0 | f87ff6ea67867667c2f9c19995a9f2eb | 48.804878 | 152 | 0.701445 | 5.316406 | false | false | false | false |
allotria/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenStructureWizardStep.kt | 3 | 4288 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.wizards
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.externalSystem.service.project.wizard.MavenizedStructureWizardStep
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil.createSequentFileName
import com.intellij.ui.layout.*
import icons.OpenapiIcons
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectsManager
import java.io.File
import javax.swing.Icon
class MavenStructureWizardStep(
private val builder: AbstractMavenModuleBuilder,
context: WizardContext
) : MavenizedStructureWizardStep<MavenProject>(context) {
override fun getHelpId() = "reference.dialogs.new.project.fromScratch.maven"
override fun createView(data: MavenProject) = MavenDataView(data)
override fun findAllParents(): List<MavenProject> {
val project = context.project ?: return emptyList()
val projectsManager = MavenProjectsManager.getInstance(project)
return projectsManager.projects
}
override fun updateProjectData() {
context.projectBuilder = builder
builder.aggregatorProject = parentData
builder.parentProject = parentData
builder.projectId = MavenId(groupId, artifactId, version)
builder.setInheritedOptions(
parentData?.mavenId?.groupId == groupId,
parentData?.mavenId?.version == version
)
builder.name = entityName
builder.contentEntryPath = location
}
override fun _init() {
builder.name?.let { entityName = it }
builder.projectId?.let { projectId ->
projectId.groupId?.let { groupId = it }
projectId.artifactId?.let { artifactId = it }
projectId.version?.let { version = it }
}
}
override fun suggestName(): String {
val projectFileDirectory = File(context.projectFileDirectory)
val moduleNames = findAllModules().map { it.name }.toSet()
val artifactIds = parentsData.map { it.mavenId.artifactId }.toSet()
return createSequentFileName(projectFileDirectory, "untitled", "") {
!it.exists() && it.name !in moduleNames && it.name !in artifactIds
}
}
override fun ValidationInfoBuilder.validateName(): ValidationInfo? {
val moduleNames = findAllModules().map { it.name }.toSet()
if (entityName in moduleNames) {
val message = MavenWizardBundle.message("maven.structure.wizard.entity.name.exists.error",
context.presentationName.capitalize(), entityName)
return error(message)
}
return superValidateName()
}
override fun ValidationInfoBuilder.validateGroupId(): ValidationInfo? {
return validateCoordinates() ?: superValidateGroupId()
}
override fun ValidationInfoBuilder.validateArtifactId(): ValidationInfo? {
return validateCoordinates() ?: superValidateArtifactId()
}
private fun ValidationInfoBuilder.validateCoordinates(): ValidationInfo? {
val mavenIds = parentsData.map { it.mavenId.groupId to it.mavenId.artifactId }.toSet()
if (groupId to artifactId in mavenIds) {
val message = MavenWizardBundle.message("maven.structure.wizard.entity.coordinates.already.exists.error",
context.presentationName.capitalize(), "$groupId:$artifactId")
return error(message)
}
return null
}
private fun findAllModules(): List<Module> {
val project = context.project ?: return emptyList()
val moduleManager = ModuleManager.getInstance(project)
return moduleManager.modules.toList()
}
class MavenDataView(override val data: MavenProject) : DataView<MavenProject>() {
override val location: String = data.directory
override val icon: Icon = OpenapiIcons.RepositoryLibraryLogo
override val presentationName: String = data.displayName
override val groupId: String = data.mavenId.groupId ?: ""
override val version: String = data.mavenId.version ?: ""
}
} | apache-2.0 | f6edb4f8becad95f6d5c388e81cc33cc | 39.462264 | 140 | 0.738106 | 4.791061 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkList.kt | 3 | 20568 | // 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 com.intellij.openapi.projectRoots.impl.jdkDownloader
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.common.collect.ImmutableList
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.io.Decompressor
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.write
import com.intellij.util.lang.JavaVersion
import com.intellij.util.system.CpuArch
import org.jetbrains.annotations.NonNls
import org.jetbrains.jps.model.java.JdkVersionDetector
import org.tukaani.xz.XZInputStream
import java.io.ByteArrayInputStream
import java.io.IOException
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
/** describes vendor + product part of the UI **/
data class JdkProduct(
val vendor: String,
val product: String?,
val flavour: String?
) {
val packagePresentationText: String
get() = buildString {
append(vendor)
if (product != null) {
append(" ")
append(product)
}
if (flavour != null) {
append(" (")
append(flavour)
append(")")
}
}
}
/** describes an item behind the version as well as download info **/
data class JdkItem(
val product: JdkProduct,
val isDefaultItem: Boolean = false,
/** there are some JdkList items that are not shown in the downloader but suggested for JdkAuto **/
val isVisibleOnUI: Boolean,
val jdkMajorVersion: Int,
@NlsSafe
val jdkVersion: String,
private val jdkVendorVersion: String?,
val suggestedSdkName: String,
val os: String,
/**
* @see presentableArchIfNeeded
*/
@NlsSafe
val arch: String,
val packageType: JdkPackageType,
val url: String,
val sha256: String,
val archiveSize: Long,
val unpackedSize: Long,
// we should only extract items that has the given prefix removing the prefix
val packageRootPrefix: String,
// the path from the package root to the java home directory (where bin/java is)
val packageToBinJavaPrefix: String,
val archiveFileName: String,
val installFolderName: String,
val sharedIndexAliases: List<String>,
private val saveToFile: (Path) -> Unit
) {
fun writeMarkerFile(file: Path) {
saveToFile(file)
}
override fun toString() = "JdkItem($fullPresentationText, $url)"
override fun hashCode() = sha256.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as JdkItem
if (jdkVersion != other.jdkVersion) return false
if (url != other.url) return false
if (sha256 != other.sha256) return false
return true
}
/**
* the Java Home folder (which contains the `bin` folder and `bin/java` path
* may be deep inside a JDK package, e.g. on macOS
* This method helps to find a traditional Java Home
* from a JDK install directory
*/
fun resolveJavaHome(installDir: Path): Path {
val packageToBinJavaPrefix = packageToBinJavaPrefix
if (packageToBinJavaPrefix.isBlank()) return installDir
return installDir.resolve(packageToBinJavaPrefix)
}
val vendorPrefix
get() = suggestedSdkName.split("-").dropLast(1).joinToString("-")
fun matchesVendor(predicate: String) : Boolean {
val cases = sequence {
yield(product.vendor)
yield(vendorPrefix)
if (product.product != null) {
yield(product.product)
yield("${product.vendor}-${product.product}")
if (product.flavour != null) {
yield("${product.product}-${product.flavour}")
yield("${product.vendor}-${product.product}-${product.flavour}")
}
}
}
val match = predicate.trim()
return cases.any { it.equals(match, ignoreCase = true) }
}
/**
* Returns versionString for the Java Sdk object in specific format
*/
val versionString
get() = JavaVersion.tryParse(jdkVersion)?.let(JdkVersionDetector::formatVersionString) ?: jdkVersion
val presentableVersionString
get() = JavaVersion.tryParse(jdkVersion)?.toFeatureMinorUpdateString() ?: jdkVersion
val presentableMajorVersionString
get() = JavaVersion.tryParse(jdkVersion)?.toFeatureString() ?: jdkMajorVersion.toString()
val versionPresentationText: String
get() = jdkVersion
val downloadSizePresentationText: String
get() = StringUtil.formatFileSize(archiveSize)
/**
* returns Arch if it's expected to be shown, `null` otherwise
*/
val presentableArchIfNeeded: @NlsSafe String?
get() = if (arch != "x86_64") arch else null
val fullPresentationText: @NlsSafe String
get() = product.packagePresentationText + " " + jdkVersion + (presentableArchIfNeeded?.let {" ($it)" } ?: "")
}
enum class JdkPackageType(@NonNls val type: String) {
@Suppress("unused")
ZIP("zip") {
override fun openDecompressor(archiveFile: Path): Decompressor {
val decompressor = Decompressor.Zip(archiveFile)
return when {
SystemInfo.isWindows -> decompressor
else -> decompressor.withZipExtensions()
}
}
},
@Suppress("SpellCheckingInspection", "unused")
TAR_GZ("targz") {
override fun openDecompressor(archiveFile: Path) = Decompressor.Tar(archiveFile)
};
abstract fun openDecompressor(archiveFile: Path): Decompressor
companion object {
fun findType(jsonText: String): JdkPackageType? = values().firstOrNull { it.type.equals(jsonText, ignoreCase = true) }
}
}
data class JdkPlatform(
val os: String,
val arch: String,
)
data class JdkPredicate(
private val ideBuildNumber: BuildNumber,
private val supportedPlatforms: Set<JdkPlatform>,
) {
companion object {
fun none() = JdkPredicate(ApplicationInfoImpl.getShadowInstance().build, emptySet())
fun default() = createInstance(forWsl = false)
fun forWSL() = createInstance(forWsl = true)
/**
* Selects only JDKs that are for the same OS and CPU arch as the current Java process.
*/
fun forCurrentProcess() = JdkPredicate(ApplicationInfoImpl.getShadowInstance().build, setOf(JdkPlatform(currentOS, currentArch)))
private fun createInstance(forWsl: Boolean = false): JdkPredicate {
val x86_64 = "x86_64"
val defaultPlatform = JdkPlatform(currentOS, x86_64)
val platforms = when {
(SystemInfo.isMac && CpuArch.isArm64()) || Registry.`is`("jdk.downloader.assume.m1") -> {
listOf(defaultPlatform, defaultPlatform.copy(arch = "aarch64"))
}
SystemInfo.isWindows && forWsl -> {
listOf(defaultPlatform.copy(os = "linux"))
}
!SystemInfo.isWindows && forWsl -> {
listOf()
}
else -> listOf(defaultPlatform)
}
return JdkPredicate(ApplicationInfoImpl.getShadowInstance().build, platforms.toSet())
}
val currentOS = when {
SystemInfo.isWindows -> "windows"
SystemInfo.isMac -> "macOS"
SystemInfo.isLinux -> "linux"
else -> error("Unsupported OS")
}
val currentArch = when {
(SystemInfo.isMac && CpuArch.isArm64()) || Registry.`is`("jdk.downloader.assume.m1") -> "aarch64"
else -> "x86_64"
}
}
fun testJdkProduct(product: ObjectNode): Boolean {
val filterNode = product["filter"]
return testPredicate(filterNode) == true
}
fun testJdkPackage(pkg: ObjectNode): Boolean {
val os = pkg["os"]?.asText() ?: return false
val arch = pkg["arch"]?.asText() ?: return false
if (JdkPlatform(os, arch) !in supportedPlatforms) return false
if (pkg["package_type"]?.asText()?.let(JdkPackageType.Companion::findType) == null) return false
return testPredicate(pkg["filter"]) == true
}
/**
* tests the predicate from the `filter` or `default` elements an JDK product
* against current IDE instance
*
* returns `null` if there was something unknown detected in the filter
*
* It supports the following predicates with `type` equal to `build_number_range`, `and`, `or`, `not`, e.g.
* { "type": "build_number_range", "since": "192.34", "until": "194.123" }
* or
* { "type": "or"|"and", "items": [ {same as before}, ...] }
* or
* { "type": "not", "item": { same as before } }
* or
* { "type": "const", "value": true | false }
* or (from 2020.3.1)
* { "type": "supports_arch" }
*/
fun testPredicate(filter: JsonNode?): Boolean? {
//no filter means predicate is true
if (filter == null) return true
// used in "default" element
if (filter.isBoolean) return filter.asBoolean()
if (filter !is ObjectNode) return null
val type = filter["type"]?.asText() ?: return null
if (type == "or") {
return foldSubPredicates(filter, false, Boolean::or)
}
if (type == "and") {
return foldSubPredicates(filter, true, Boolean::and)
}
if (type == "not") {
val subResult = testPredicate(filter["item"]) ?: return null
return !subResult
}
if (type == "const") {
return filter["value"]?.asBoolean()
}
if (type == "build_number_range") {
val fromBuild = filter["since"]?.asText()
val untilBuild = filter["until"]?.asText()
if (fromBuild == null && untilBuild == null) return true
if (fromBuild != null) {
val fromBuildSafe = BuildNumber.fromStringOrNull(fromBuild) ?: return null
if (fromBuildSafe > ideBuildNumber) return false
}
if (untilBuild != null) {
val untilBuildSafe = BuildNumber.fromStringOrNull(untilBuild) ?: return null
if (ideBuildNumber > untilBuildSafe) return false
}
return true
}
if (type == "supports_arch") {
// the main fact is that we support that filter,
// the actual test is implemented when the IDE compares
// the actual arch and os attributes
// the older IDEs does not support that predicate and
// ignores the entire element
return true
}
return null
}
private fun foldSubPredicates(filter: ObjectNode,
emptyResult: Boolean,
op: (acc: Boolean, Boolean) -> Boolean): Boolean? {
val items = filter["items"] as? ArrayNode ?: return null
if (items.isEmpty) return false
return items.fold(emptyResult) { acc, subFilter ->
val subResult = testPredicate(subFilter) ?: return null
op(acc, subResult)
}
}
}
object JdkListParser {
fun readTree(rawData: ByteArray) = ObjectMapper().readTree(rawData) as? ObjectNode ?: error("Unexpected JSON data")
fun parseJdkList(tree: ObjectNode, filters: JdkPredicate): List<JdkItem> {
val items = tree["jdks"] as? ArrayNode ?: error("`jdks` element is missing")
val result = mutableListOf<JdkItem>()
for (item in items.filterIsInstance<ObjectNode>()) {
result += parseJdkItem(item, filters)
}
return result.toList()
}
fun parseJdkItem(item: ObjectNode, filters: JdkPredicate): List<JdkItem> {
// check this package is OK to show for that instance of the IDE
if (!filters.testJdkProduct(item)) return emptyList()
val packages = item["packages"] as? ArrayNode ?: return emptyList()
val product = JdkProduct(
vendor = item["vendor"]?.asText() ?: return emptyList(),
product = item["product"]?.asText(),
flavour = item["flavour"]?.asText()
)
val contents = ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(item)
return packages.filterIsInstance<ObjectNode>().filter(filters::testJdkPackage).map { pkg ->
JdkItem(product = product,
isDefaultItem = item["default"]?.let { filters.testPredicate(it) == true } ?: false,
isVisibleOnUI = item["listed"]?.let { filters.testPredicate(it) == true } ?: true,
jdkMajorVersion = item["jdk_version_major"]?.asInt() ?: return emptyList(),
jdkVersion = item["jdk_version"]?.asText() ?: return emptyList(),
jdkVendorVersion = item["jdk_vendor_version"]?.asText(),
suggestedSdkName = item["suggested_sdk_name"]?.asText() ?: return emptyList(),
os = pkg["os"]?.asText() ?: return emptyList(),
arch = pkg["arch"]?.asText() ?: return emptyList(),
packageType = pkg["package_type"]?.asText()?.let(JdkPackageType.Companion::findType) ?: return emptyList(),
url = pkg["url"]?.asText() ?: return emptyList(),
sha256 = pkg["sha256"]?.asText() ?: return emptyList(),
archiveSize = pkg["archive_size"]?.asLong() ?: return emptyList(),
archiveFileName = pkg["archive_file_name"]?.asText() ?: return emptyList(),
packageRootPrefix = pkg["package_root_prefix"]?.asText() ?: return emptyList(),
packageToBinJavaPrefix = pkg["package_to_java_home_prefix"]?.asText() ?: return emptyList(),
unpackedSize = pkg["unpacked_size"]?.asLong() ?: return emptyList(),
installFolderName = pkg["install_folder_name"]?.asText() ?: return emptyList(),
sharedIndexAliases = (item["shared_index_aliases"] as? ArrayNode)?.mapNotNull { it.asText() } ?: listOf(),
saveToFile = { file -> file.write(contents) }
)
}
}
}
@Service
class JdkListDownloader : JdkListDownloaderBase() {
companion object {
@JvmStatic
fun getInstance() = service<JdkListDownloader>()
}
override val feedUrl: String
get() {
val registry = runCatching { Registry.get("jdk.downloader.url").asString() }.getOrNull()
if (!registry.isNullOrBlank()) return registry
return "https://download.jetbrains.com/jdk/feed/v1/jdks.json.xz"
}
}
abstract class JdkListDownloaderBase {
protected abstract val feedUrl: String
private fun downloadJdkList(feedUrl: String, progress: ProgressIndicator?) =
HttpRequests
.request(feedUrl)
.productNameAsUserAgent()
//timeouts are handled inside
.readBytes(progress)
/**
* Returns a list of entries for JDK automatic installation. That set of entries normally
* contains few more entries than the result of the [downloadForUI] call.
* Entries are sorter from the best suggested to the worst suggested items.
*/
fun downloadModelForJdkInstaller(progress: ProgressIndicator?): List<JdkItem> = downloadModelForJdkInstaller(progress, JdkPredicate.default())
/**
* Returns a list of entries for JDK automatic installation. That set of entries normally
* contains few more entries than the result of the [downloadForUI] call.
* Entries are sorter from the best suggested to the worst suggested items.
*/
fun downloadModelForJdkInstaller(progress: ProgressIndicator?, predicate: JdkPredicate): List<JdkItem> {
return downloadJdksListWithCache(predicate, feedUrl, progress)
}
/**
* Lists all entries suitable for UI download, there can be some unlisted entries that are ignored here by intent
*/
fun downloadForUI(progress: ProgressIndicator?, feedUrl: String? = null) : List<JdkItem> = downloadForUI(progress, feedUrl, JdkPredicate.default())
/**
* Lists all entries suitable for UI download, there can be some unlisted entries that are ignored here by intent
*/
fun downloadForUI(progress: ProgressIndicator?, feedUrl: String? = null, predicate: JdkPredicate) : List<JdkItem> {
//we intentionally disable cache here for all user UI requests, as of IDEA-252237
val url = feedUrl ?: this.feedUrl
val raw = downloadJdksListNoCache(url, progress)
//setting value to the cache, just in case
jdksListCache.setValue(url, raw)
val list = raw.getJdks(predicate)
if (ApplicationManager.getApplication().isInternal) {
return list
}
return list.filter { it.isVisibleOnUI }
}
private val jdksListCache = CachedValueWithTTL<RawJdkList>(15 to TimeUnit.MINUTES)
private fun downloadJdksListWithCache(predicate: JdkPredicate, feedUrl: String?, progress: ProgressIndicator?): List<JdkItem> {
@Suppress("NAME_SHADOWING")
val feedUrl = feedUrl ?: this.feedUrl
if (predicate == JdkPredicate.none()) {
return listOf()
}
return jdksListCache.getOrCompute(feedUrl, EmptyRawJdkList) {
downloadJdksListNoCache(feedUrl, progress)
}.getJdks(predicate)
}
private fun downloadJdksListNoCache(feedUrl: String, progress: ProgressIndicator?): RawJdkList {
// download XZ packed version of the data (several KBs packed, several dozen KBs unpacked) and process it in-memory
val rawDataXZ = try {
downloadJdkList(feedUrl, progress)
}
catch (t: IOException) {
Logger.getInstance(javaClass).warn("Failed to download the list of available JDKs from $feedUrl. ${t.message}")
return EmptyRawJdkList
}
val rawData = try {
ByteArrayInputStream(rawDataXZ).use { input ->
XZInputStream(input).use {
it.readBytes()
}
}
}
catch (t: Throwable) {
throw RuntimeException("Failed to unpack the list of available JDKs from $feedUrl. ${t.message}", t)
}
val json = try {
JdkListParser.readTree(rawData)
}
catch (t: Throwable) {
throw RuntimeException("Failed to parse the downloaded list of available JDKs. ${t.message}", t)
}
return RawJdkListImpl(feedUrl, json)
}
}
private interface RawJdkList {
fun getJdks(predicate: JdkPredicate) : List<JdkItem>
}
private object EmptyRawJdkList : RawJdkList {
override fun getJdks(predicate: JdkPredicate) : List<JdkItem> = listOf()
}
private class RawJdkListImpl(
private val feedUrl: String,
private val json: ObjectNode,
) : RawJdkList {
private val cache = ConcurrentHashMap<JdkPredicate, () -> List<JdkItem>>()
override fun getJdks(predicate: JdkPredicate) = cache.computeIfAbsent(predicate) { parseJson(it) }()
private fun parseJson(predicate: JdkPredicate) : () -> List<JdkItem> {
val result = runCatching {
try {
ImmutableList.copyOf(JdkListParser.parseJdkList(json, predicate))
}
catch (t: Throwable) {
throw RuntimeException("Failed to process the downloaded list of available JDKs from $feedUrl. ${t.message}", t)
}
}
return { result.getOrThrow() }
}
}
private class CachedValueWithTTL<T : Any>(
private val ttl: Pair<Int, TimeUnit>
) {
private val lock = ReentrantReadWriteLock()
private var cachedUrl: String? = null
private var value: T? = null
private var computed = 0L
private fun now() = System.currentTimeMillis()
private operator fun Long.plus(ttl: Pair<Int, TimeUnit>): Long = this + ttl.second.toMillis(ttl.first.toLong())
private inline fun readValueOrNull(expectedUrl: String, onValue: (T) -> Unit) {
if (cachedUrl != expectedUrl) {
return
}
val value = this.value
if (value != null && computed + ttl > now()) {
onValue(value)
}
}
fun getOrCompute(url: String, defaultOrFailure: T, compute: () -> T): T {
lock.read {
readValueOrNull(url) { return it }
}
lock.write {
//double checked
readValueOrNull(url) { return it }
val value = runCatching(compute).getOrElse {
if (it is ProcessCanceledException) {
throw it
}
Logger.getInstance(javaClass).warn("Failed to compute value. ${it.message}", it)
defaultOrFailure
}
ProgressManager.checkCanceled()
return setValue(url, value)
}
}
fun setValue(url: String, value: T): T = lock.write {
this.value = value
computed = now()
cachedUrl = url
return value
}
}
| apache-2.0 | 7a04a7994e079e37b01b9a5a32d6321c | 32.553018 | 149 | 0.675515 | 4.264566 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/feature/LocalTemplateFeature.kt | 1 | 1698 | package no.skatteetaten.aurora.boober.feature
import no.skatteetaten.aurora.boober.model.AuroraConfig
import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler
import no.skatteetaten.aurora.boober.model.AuroraConfigFile
import no.skatteetaten.aurora.boober.model.AuroraContextCommand
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
@Service
class LocalTemplateFeature(
@Value("\${openshift.cluster}") c: String
) : AbstractTemplateFeature(c) {
override fun enable(header: AuroraDeploymentSpec) = header.type == TemplateType.localTemplate
override fun templateHandlers(
files: List<AuroraConfigFile>,
auroraConfig: AuroraConfig
): Set<AuroraConfigFieldHandler> {
return setOf(
AuroraConfigFieldHandler("templateFile", validator = { json ->
val fileName = json?.textValue()
if (auroraConfig.files.none { it.name == fileName }) {
IllegalArgumentException("The file named $fileName does not exist in AuroraConfig")
} else {
null
}
})
)
}
override fun createContext(spec: AuroraDeploymentSpec, cmd: AuroraContextCommand, validationContext: Boolean): Map<String, Any> {
val templateFile = spec.get<String>("templateFile").let { fileName ->
cmd.auroraConfig.files.find { it.name == fileName }?.asJsonNode
}
return templateFile?.let {
mapOf("template" to it)
} ?: throw IllegalArgumentException("templateFile is required")
}
}
| apache-2.0 | f840a84502c6e86d7a0945f7fcfdbecf | 39.428571 | 133 | 0.687868 | 4.936047 | false | true | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/RestoreCommandTest.kt | 1 | 4449 | package jetbrains.buildServer.dotnet.test.dotnet
import jetbrains.buildServer.agent.CommandLineArgument
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.agent.ToolPath
import jetbrains.buildServer.dotnet.*
import jetbrains.buildServer.dotnet.test.agent.ArgumentsServiceStub
import jetbrains.buildServer.dotnet.test.agent.runner.ParametersServiceStub
import org.jmock.Mockery
import org.testng.Assert
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class RestoreCommandTest {
private lateinit var _ctx: Mockery
private lateinit var _resultsAnalyzer: ResultsAnalyzer
@BeforeMethod
fun setUp() {
_ctx = Mockery()
_resultsAnalyzer = _ctx.mock<ResultsAnalyzer>(ResultsAnalyzer::class.java)
}
@DataProvider
fun testRestoreArgumentsData(): Array<Array<Any>> {
return arrayOf(
arrayOf(mapOf(Pair(DotnetConstants.PARAM_PATHS, "path/")),
listOf("customArg1")),
arrayOf(mapOf(
Pair(DotnetConstants.PARAM_NUGET_PACKAGES_DIR, "packages/")),
listOf("--packages", "packages/", "customArg1")),
arrayOf(mapOf(Pair(DotnetConstants.PARAM_NUGET_PACKAGE_SOURCES, "http://jb.com")),
listOf("--source", "http://jb.com", "customArg1")),
arrayOf(mapOf(Pair(DotnetConstants.PARAM_NUGET_PACKAGE_SOURCES, "http://jb.com\nhttp://jb.ru")),
listOf("--source", "http://jb.com", "--source", "http://jb.ru", "customArg1")),
arrayOf(mapOf(Pair(DotnetConstants.PARAM_NUGET_PACKAGE_SOURCES, "http://jb.com http://jb.ru")),
listOf("--source", "http://jb.com", "--source", "http://jb.ru", "customArg1")))
}
@Test(dataProvider = "testRestoreArgumentsData")
fun shouldGetArguments(
parameters: Map<String, String>,
expectedArguments: List<String>) {
// Given
val command = createCommand(parameters = parameters, targets = sequenceOf("my.csproj"), arguments = sequenceOf(CommandLineArgument("customArg1")))
// When
val actualArguments = command.getArguments(DotnetBuildContext(ToolPath(Path("wd")), command)).map { it.value }.toList()
// Then
Assert.assertEquals(actualArguments, expectedArguments)
}
@DataProvider
fun projectsArgumentsData(): Array<Array<Any>> {
return arrayOf(
arrayOf(listOf("my.csproj") as Any, listOf(listOf("my.csproj"))),
arrayOf(emptyList<String>() as Any, emptyList<List<String>>()),
arrayOf(listOf("my.csproj", "my2.csproj") as Any, listOf(listOf("my.csproj"), listOf("my2.csproj"))))
}
@Test(dataProvider = "projectsArgumentsData")
fun shouldProvideProjectsArguments(targets: List<String>, expectedArguments: List<List<String>>) {
// Given
val command = createCommand(targets = targets.asSequence())
// When
val actualArguments = command.targetArguments.map { it.arguments.map { it.value }.toList() }.toList()
// Then
Assert.assertEquals(actualArguments, expectedArguments)
}
@Test
fun shouldProvideCommandType() {
// Given
val command = createCommand()
// When
val actualCommand = command.commandType
// Then
Assert.assertEquals(actualCommand, DotnetCommandType.Restore)
}
@Test
fun shouldProvideToolExecutableFile() {
// Given
val command = createCommand()
// When
val actualExecutable = command.toolResolver.executable
// Then
Assert.assertEquals(actualExecutable, ToolPath(Path("dotnet")))
}
fun createCommand(
parameters: Map<String, String> = emptyMap(),
targets: Sequence<String> = emptySequence(),
arguments: Sequence<CommandLineArgument> = emptySequence()): DotnetCommand =
RestoreCommand(
ParametersServiceStub(parameters),
_resultsAnalyzer,
ArgumentsServiceStub(),
TargetServiceStub(targets.map { CommandTarget(Path(it)) }.asSequence()),
ArgumentsProviderStub(arguments),
DotnetToolResolverStub(ToolPlatform.CrossPlatform, ToolPath(Path("dotnet")), true))
} | apache-2.0 | 6c1d1538a13eb1b3c0272fbb958e9914 | 39.454545 | 154 | 0.637447 | 4.727949 | false | true | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/ext/HasComponents.kt | 1 | 8142 | package com.faendir.acra.ui.ext
import com.faendir.acra.dataprovider.QueryDslDataProvider
import com.faendir.acra.model.User
import com.faendir.acra.service.AvatarService
import com.faendir.acra.service.UserService
import com.faendir.acra.ui.component.Box
import com.faendir.acra.ui.component.Card
import com.faendir.acra.ui.component.ConfigurationLabel
import com.faendir.acra.ui.component.DownloadButton
import com.faendir.acra.ui.component.InstallationView
import com.faendir.acra.ui.component.RangeField
import com.faendir.acra.ui.component.tabs.Tab
import com.faendir.acra.ui.component.Translatable
import com.faendir.acra.ui.component.UserEditor
import com.faendir.acra.ui.component.grid.AcrariumGrid
import com.faendir.acra.ui.component.grid.QueryDslAcrariumGrid
import com.github.appreciated.layout.GridLayout
import com.vaadin.flow.component.AbstractField
import com.vaadin.flow.component.ClickEvent
import com.vaadin.flow.component.HasComponents
import com.vaadin.flow.component.Text
import com.vaadin.flow.component.button.Button
import com.vaadin.flow.component.checkbox.Checkbox
import com.vaadin.flow.component.combobox.ComboBox
import com.vaadin.flow.component.formlayout.FormLayout
import com.vaadin.flow.component.grid.Grid
import com.vaadin.flow.component.html.Anchor
import com.vaadin.flow.component.html.Div
import com.vaadin.flow.component.html.Image
import com.vaadin.flow.component.html.Label
import com.vaadin.flow.component.html.Paragraph
import com.vaadin.flow.component.login.LoginForm
import com.vaadin.flow.component.login.LoginI18n
import com.vaadin.flow.component.orderedlayout.FlexLayout
import com.vaadin.flow.component.select.Select
import com.vaadin.flow.component.tabs.Tabs
import com.vaadin.flow.component.textfield.NumberField
import com.vaadin.flow.component.textfield.TextArea
import com.vaadin.flow.component.textfield.TextField
import com.vaadin.flow.server.AbstractStreamResource
fun HasComponents.gridLayout(initializer: GridLayout.() -> Unit = {}) {
add(GridLayout().apply(initializer))
}
fun HasComponents.translatableLabel(captionId: String, vararg params: Any, initializer: Label.() -> Unit = {}) {
add(Translatable.createLabel(captionId, *params).with(initializer))
}
fun HasComponents.label(text: String, initializer: Label.() -> Unit = {}) {
add(Label(text).apply(initializer))
}
fun HasComponents.installationView(avatarService: AvatarService, installationId: String) {
add(InstallationView(avatarService).apply { setInstallationId(installationId) })
}
fun HasComponents.div(initializer: Div.() -> Unit = {}) {
add(Div().apply(initializer))
}
fun <T> HasComponents.forEach(iterable: Iterable<T>, initializer: HasComponents.(T) -> Unit = {}) {
iterable.forEach { initializer(it) }
}
fun HasComponents.anchor(resource: AbstractStreamResource, text: String, initializer: Anchor.() -> Unit = {}) {
add(Anchor(resource, text).apply(initializer))
}
fun HasComponents.card(initializer: Card.() -> Unit = {}) {
add(Card().apply(initializer))
}
fun HasComponents.flexLayout(initializer: FlexLayout.() -> Unit = {}): FlexLayout {
return FlexLayout().apply(initializer).also { add(it) }
}
fun HasComponents.translatableImage(src: String, captionId: String, vararg params: Any, initializer: Image.() -> Unit = {}) {
add(Translatable.createImage(src, captionId, *params).with(initializer))
}
fun HasComponents.loginForm(loginI18n: LoginI18n, initializer: LoginForm.() -> Unit = {}) {
add(LoginForm(loginI18n).apply(initializer))
}
fun HasComponents.userEditor(userService: UserService, user: User, isExistingUser: Boolean, onSuccess: () -> Unit) {
add(UserEditor(userService, user, isExistingUser, onSuccess))
}
fun <T> HasComponents.queryDslAcrariumGrid(dataProvider: QueryDslDataProvider<T>, initializer: QueryDslAcrariumGrid<T>.() -> Unit): QueryDslAcrariumGrid<T> {
val grid = QueryDslAcrariumGrid(dataProvider)
grid.initializer()
add(grid)
return grid
}
fun HasComponents.translatableButton(captionId: String, vararg params: Any, clickListener: ((ClickEvent<Button>) -> Unit) = {}): Translatable<Button> {
return Translatable.createButton(captionId, *params, clickListener = clickListener).also { add(it) }
}
fun HasComponents.formLayout(initializer: FormLayout.() -> Unit = {}) {
add(FormLayout().apply(initializer))
}
fun HasComponents.translatableCheckbox(captionId: String, vararg params: Any, initializer: Checkbox.() -> Unit = {}): Translatable.Value<Checkbox, *, Boolean> {
return Translatable.createCheckbox(captionId, *params).with(initializer).also { add(it) }
}
fun HasComponents.checkbox(initializer: Checkbox.() -> Unit = {}) {
add(Checkbox().apply(initializer))
}
fun <T> HasComponents.translatableSelect(items: Collection<T>, captionId: String, vararg params: Any, initializer: Select<T>.() -> Unit = {}) {
add(Translatable.createSelect(items, captionId, *params).with(initializer))
}
fun HasComponents.tabs(initializer: Tabs.() -> Unit = {}): Tabs {
return Tabs().apply(initializer).also { add(it) }
}
fun HasComponents.tab(captionId: String, vararg params: Any, initializer: Tab.() -> Unit = {}) {
add(Tab(captionId, *params).apply(initializer))
}
fun HasComponents.box(titleId: String, detailsId: String, buttonId: String, clickListener: (ClickEvent<Button>) -> Unit = {}): Box {
return Box(
Translatable.createLabel(titleId),
Translatable.createLabel(detailsId),
Translatable.createButton(buttonId, clickListener = clickListener)
).also { add(it) }
}
fun <T> HasComponents.comboBox(items: Collection<T>, captionId: String, vararg params: Any, initializer: ComboBox<T>.() -> Unit = {})
: Translatable.ValidatedValue<ComboBox<T>, AbstractField.ComponentValueChangeEvent<ComboBox<T>, T>, T> {
return Translatable.createComboBox(items, captionId, *params).with(initializer).also { add(it) }
}
fun HasComponents.downloadButton(resource: AbstractStreamResource, captionId: String, vararg params: Any, initializer: DownloadButton.() -> Unit = {}) {
add(DownloadButton(resource, captionId, *params).apply(initializer))
}
fun HasComponents.translatableTextArea(captionId: String, vararg params: Any, initializer: TextArea.() -> Unit = {})
: Translatable.ValidatedValue<TextArea, AbstractField.ComponentValueChangeEvent<TextArea, String>, String> {
return Translatable.createTextArea(captionId, *params).with(initializer).also { add(it) }
}
fun <T> HasComponents.acrariumGrid(content: Collection<T>, initializer: AcrariumGrid<T>.() -> Unit): Grid<T> {
return AcrariumGrid<T>().apply { setItems(content) }.apply(initializer).also { add(it) }
}
fun HasComponents.translatableText(captionId: String, vararg params: Any, initializer: Text.() -> Unit = {}) {
add(Translatable.createText(captionId, *params).with(initializer))
}
fun HasComponents.configurationLabel(user: User) {
add(ConfigurationLabel.forUser(user))
}
fun HasComponents.translatableRangeField(
captionId: String,
vararg params: Any,
initializer: RangeField.() -> Unit = {}
): Translatable.ValidatedValue<RangeField, *, Double> {
return Translatable.createRangeField(captionId, params).with(initializer).also { add(it) }
}
fun HasComponents.translatableNumberField(
captionId: String,
vararg params: Any,
initializer: NumberField.() -> Unit = {}
): Translatable.ValidatedValue<NumberField, *, Double> {
return Translatable.createNumberField(captionId, params).with(initializer).also { add(it) }
}
fun HasComponents.paragraph(text: String, initializer: Paragraph.() -> Unit = {}) {
add(Paragraph(text).apply(initializer))
}
fun HasComponents.translatableParagraph(captionId: String, vararg params: Any, initializer: Paragraph.() -> Unit = {}) {
add(Translatable.createP(captionId, *params).with(initializer))
}
fun HasComponents.translatableTextField(
captionId: String,
vararg params: Any,
initializer: TextField.() -> Unit = {}
): Translatable.ValidatedValue<TextField, *, String> {
return Translatable.createTextField(captionId, params).with(initializer).also { add(it) }
} | apache-2.0 | afa64d8afcd69f3c4f618d3712ee4ab4 | 41.857895 | 160 | 0.754974 | 3.853289 | false | false | false | false |
Raizlabs/DBFlow | processor/src/main/kotlin/com/dbflow5/processor/definition/provider/TableEndpointDefinition.kt | 1 | 3051 | package com.dbflow5.processor.definition.provider
import com.dbflow5.contentprovider.annotation.ContentUri
import com.dbflow5.contentprovider.annotation.Notify
import com.dbflow5.contentprovider.annotation.NotifyMethod
import com.dbflow5.contentprovider.annotation.TableEndpoint
import com.dbflow5.processor.ProcessorManager
import com.dbflow5.processor.definition.BaseDefinition
import com.dbflow5.processor.utils.annotation
import com.dbflow5.processor.utils.extractTypeNameFromAnnotation
import com.squareup.javapoet.TypeName
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.PackageElement
import javax.lang.model.element.TypeElement
/**
* Description:
*/
class TableEndpointDefinition(tableEndpoint: TableEndpoint,
typeElement: Element, processorManager: ProcessorManager)
: BaseDefinition(typeElement, processorManager) {
var contentUriDefinitions: MutableList<ContentUriDefinition> = mutableListOf()
/**
* Dont want duplicate paths.
*/
internal var pathValidationMap: Map<String, ContentUriDefinition> = mutableMapOf()
var notifyDefinitionPathMap: MutableMap<String, MutableMap<NotifyMethod, MutableList<NotifyDefinition>>> = mutableMapOf()
var tableName: String? = null
var contentProviderName: TypeName? = null
var isTopLevel = false
init {
contentProviderName = tableEndpoint.extractTypeNameFromAnnotation {
tableName = it.name
it.contentProvider
}
isTopLevel = typeElement.enclosingElement is PackageElement
val elements = processorManager.elements.getAllMembers(typeElement as TypeElement)
for (innerElement in elements) {
innerElement.annotation<ContentUri>()?.let { contentUri ->
val contentUriDefinition = ContentUriDefinition(contentUri, innerElement, processorManager)
if (!pathValidationMap.containsKey(contentUriDefinition.path)) {
contentUriDefinitions.add(contentUriDefinition)
} else {
processorManager.logError("There must be unique paths " +
"for the specified @ContentUri ${contentUriDefinition.name} " +
"from $contentProviderName")
}
}
innerElement.annotation<Notify>()?.let { notify ->
if (innerElement is ExecutableElement) {
val notifyDefinition = NotifyDefinition(notify, innerElement, processorManager)
@Suppress("LoopToCallChain")
for (path in notifyDefinition.paths) {
val methodListMap = notifyDefinitionPathMap.getOrPut(path) { mutableMapOf() }
val notifyDefinitionList = methodListMap.getOrPut(notifyDefinition.method) { arrayListOf() }
notifyDefinitionList.add(notifyDefinition)
}
}
}
}
}
}
| mit | 6fabbf476aadf40c92d8a9c0423457aa | 40.794521 | 125 | 0.683055 | 5.371479 | false | false | false | false |
HTWDD/HTWDresden | app/src/main/java/de/htwdd/htwdresden/utils/extensions/NavControllerExtension.kt | 1 | 488 | package de.htwdd.htwdresden.utils.extensions
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.Navigator
fun NavController.navigateSafe(@IdRes resId: Int, args: Bundle? = null, navOptions: NavOptions? = null, navExtras: Navigator.Extras? = null) {
val action = currentDestination?.getAction(resId)
if (action != null) navigate(resId, args, navOptions, navExtras)
} | mit | 4f28c62dd570bd30a7c637979e50c142 | 39.75 | 142 | 0.797131 | 4.206897 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/view/common/MTTransitions.kt | 1 | 4090 | package org.mtransit.android.ui.view.common
import android.content.Context
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.Fragment
import androidx.transition.Transition
import com.google.android.material.transition.Hold
import com.google.android.material.transition.MaterialContainerTransform
import org.mtransit.android.R
import org.mtransit.android.commons.MTLog
import org.mtransit.commons.FeatureFlags
/**
* Android Dev:
* https://developer.android.com/guide/fragments/animate#shared
* https://developer.android.com/guide/navigation/navigation-animate-transitions#set-fragment
* https://android-developers.googleblog.com/2018/02/continuous-shared-element-transitions.html
* https://medium.com/androiddevelopers/fragment-transitions-ea2726c3f36f
* Material:
* https://material.io/develop/android/theming/motion#container-transform
* https://material.io/develop/android/theming/motion#customization
* Blog:
* https://chris.banes.dev/fragmented-transitions/
* https://wykorijnsburger.nl/dev/2019/04/30/shared-element-transition/
*
* TODO:
* - look at visibility changing during transition (enter + exit)
* - POI scree
* - Home screen
*/
object MTTransitions : MTLog.Loggable {
private val LOG_TAG = MTTransitions::class.java.simpleName
override fun getLogTag(): String = LOG_TAG
const val DEBUG_TRANSITION = false
// const val DEBUG_TRANSITION = true // DEBUG
const val DURATION_FACTOR = 1L
// const val DURATION_FACTOR = 2L
const val CAN_OVERRIDE_SCRIM_COLOR = false
val OVERRIDE_SCRIM_COLOR: Int? = if (!DEBUG_TRANSITION) null else Color.TRANSPARENT
// const val OVERRIDE_SCRIM_COLOR = true
@JvmStatic
fun setTransitionName(view: View?, newTransitionName: String?) {
if (!FeatureFlags.F_TRANSITION) {
return
}
view?.apply {
if (transitionName != newTransitionName) {
transitionName = newTransitionName
}
}
}
@JvmStatic
fun newHoldTransition(): Transition? {
if (!FeatureFlags.F_TRANSITION) {
return null
}
return Hold()
}
@JvmStatic
fun setContainerTransformTransition(fragment: Fragment) {
if (!FeatureFlags.F_TRANSITION) {
return
}
fragment.sharedElementEnterTransition = newContainerTransformTransition(fragment.context)
}
@JvmOverloads
@JvmStatic
fun newContainerTransformTransition(
context: Context?,
transitionScrimColor: Int? = context?.let { ContextCompat.getColor(it, R.color.color_background) },
): Transition? {
if (!FeatureFlags.F_TRANSITION) {
return null
}
return MaterialContainerTransform().apply {
duration *= DURATION_FACTOR
if (CAN_OVERRIDE_SCRIM_COLOR) {
transitionScrimColor?.let {
scrimColor = transitionScrimColor
}
} else if (OVERRIDE_SCRIM_COLOR != null) {
scrimColor = OVERRIDE_SCRIM_COLOR
}
if (DEBUG_TRANSITION) {
isDrawDebugEnabled = true
// TODO ? drawingViewId = R.id.scrollview
// TODO ? pathMotion = ArcMotion()
duration *= DURATION_FACTOR // double factor
if (OVERRIDE_SCRIM_COLOR != null) {
scrimColor = OVERRIDE_SCRIM_COLOR
}
}
}
}
@JvmStatic
fun postponeEnterTransition(fragment: Fragment) {
if (!FeatureFlags.F_TRANSITION) {
return
}
fragment.postponeEnterTransition()
}
@JvmStatic
fun startPostponedEnterTransitionOnPreDraw(view: View?, fragment: Fragment?) {
if (!FeatureFlags.F_TRANSITION) {
return
}
(view as? ViewGroup)?.doOnPreDraw {
fragment?.startPostponedEnterTransition()
}
}
} | apache-2.0 | 146ba1d6c297ee0b8d24af99754f28d6 | 31.212598 | 107 | 0.651589 | 4.504405 | false | false | false | false |
rodm/teamcity-gradle-init-scripts-plugin | server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/GradleInitScriptsPage.kt | 1 | 2816 | /*
* Copyright 2017 Rod MacKenzie.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rodm.teamcity.gradle.scripts.server
import com.github.rodm.teamcity.gradle.scripts.server.health.ProjectInspector
import jetbrains.buildServer.controllers.admin.projects.EditProjectTab
import jetbrains.buildServer.web.openapi.PagePlaces
import jetbrains.buildServer.web.openapi.PluginDescriptor
import javax.servlet.http.HttpServletRequest
class GradleInitScriptsPage(pagePlaces: PagePlaces,
descriptor: PluginDescriptor,
val scriptsManager: GradleScriptsManager,
val analyzer: InitScriptsUsageAnalyzer,
val inspector: ProjectInspector) :
EditProjectTab(pagePlaces, descriptor.pluginName, descriptor.getPluginResourcesPath("projectPage.jsp"), "")
{
private val TITLE = "Gradle Init Scripts"
init {
tabTitle = TITLE
addCssFile("/css/admin/buildTypeForm.css")
addJsFile(descriptor.getPluginResourcesPath("initScripts.js"))
}
override fun fillModel(model: MutableMap<String, Any?>, request: HttpServletRequest) {
super.fillModel(model, request)
val project = getProject(request)
if (project != null) {
val fileName = request.getParameter("file")
if (fileName != null) {
val fileContent = scriptsManager.findScript(project, fileName)
if (fileContent != null) {
model.put("fileName", fileName)
model.put("fileContent", fileContent)
}
}
val scripts = scriptsManager.getScriptNames(project)
model.put("scripts", scripts)
val usage = analyzer.getScriptsUsage(scripts)
model.put("usage", usage)
val inspections = inspector.report(project)
model.put("inspections", inspections)
}
}
override fun getTabTitle(request: HttpServletRequest): String {
val project = getProject(request)
if (project != null) {
val count = scriptsManager.getScriptsCount(project)
if (count > 0) {
return "$TITLE ($count)"
}
}
return TITLE
}
}
| apache-2.0 | a1fc6cfab9c09fc0b9694ebd8d52790c | 38.661972 | 115 | 0.648082 | 4.797274 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/Configuration.kt | 1 | 1828 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.wifi.band.WiFiBand
import com.vrem.wifianalyzer.wifi.band.WiFiChannelPair
import com.vrem.wifianalyzer.wifi.band.WiFiChannels
const val SIZE_MIN = 1024
const val SIZE_MAX = 4096
@OpenClass
class Configuration(val largeScreen: Boolean) {
private var wiFiChannelPair = mutableMapOf<WiFiBand, WiFiChannelPair>()
var size = SIZE_MAX
val sizeAvailable: Boolean
get() = size == SIZE_MAX
fun wiFiChannelPair(countryCode: String): Unit =
WiFiBand.values().forEach {
this.wiFiChannelPair[it] = it.wiFiChannels.wiFiChannelPairFirst(countryCode)
}
fun wiFiChannelPair(wiFiBand: WiFiBand): WiFiChannelPair =
this.wiFiChannelPair[wiFiBand]!!
fun wiFiChannelPair(wiFiBand: WiFiBand, wiFiChannelPair: WiFiChannelPair) {
this.wiFiChannelPair[wiFiBand] = wiFiChannelPair
}
init {
WiFiBand.values().forEach {
this.wiFiChannelPair[it] = WiFiChannels.UNKNOWN
}
}
} | gpl-3.0 | 66dbec9db61fad1fdbe4257f04f4291c | 32.254545 | 90 | 0.728665 | 4.231481 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/predicate/MakePredicateTest.kt | 1 | 1818 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.predicate
import com.vrem.wifianalyzer.wifi.model.WiFiDetail
import org.junit.Assert.assertTrue
import org.junit.Test
class MakePredicateTest {
@Test
fun testMakePredicateExpectsTruePredicate() {
// setup
val wiFiDetail = WiFiDetail.EMPTY
val toPredicate: ToPredicate<TestObject> = { truePredicate }
val filters: Set<TestObject> = TestObject.values().toSet()
// execute
val actual: Predicate = makePredicate(TestObject.values(), filters, toPredicate)
// validate
assertTrue(actual(wiFiDetail))
}
@Test
fun testMakePredicateExpectsAnyPredicate() {
// setup
val wiFiDetail = WiFiDetail.EMPTY
val toPredicate: ToPredicate<TestObject> = { truePredicate }
val filters: Set<TestObject> = setOf(TestObject.VALUE1, TestObject.VALUE3)
// execute
val actual: Predicate = makePredicate(TestObject.values(), filters, toPredicate)
// validate
assertTrue(actual(wiFiDetail))
}
} | gpl-3.0 | 0f0ee34dcce4a0a7f5e1f67ae6b21657 | 35.38 | 90 | 0.708471 | 4.328571 | false | true | false | false |
blokadaorg/blokada | android5/app/src/main/java/service/NotificationService.kt | 1 | 2503 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package service
import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import utils.Logger
import utils.NotificationChannels
import utils.NotificationPrototype
object NotificationService {
private val log = Logger("Notification")
private val context = ContextService
private val notificationManager by lazy {
context.requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
private var useChannels: Boolean = false
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.v("Creating notification channels")
NotificationChannels.values().forEach {
createNotificationChannel(it)
}
useChannels = true
}
}
fun show(notification: NotificationPrototype) {
val builder = notification.create(context.requireContext())
if (useChannels) builder.setChannelId(notification.channel.name)
val n = builder.build()
if (notification.autoCancel) n.flags = Notification.FLAG_AUTO_CANCEL
notificationManager.notify(notification.id, n)
}
fun build(notification: NotificationPrototype): Notification {
val builder = notification.create(context.requireContext())
if (useChannels) builder.setChannelId(notification.channel.name)
val n = builder.build()
if (notification.autoCancel) n.flags = Notification.FLAG_AUTO_CANCEL
return n
}
fun cancel(notification: NotificationPrototype) {
notificationManager.cancel(notification.id)
}
@TargetApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channel: NotificationChannels) {
val mChannel = NotificationChannel(
channel.name,
channel.title,
channel.importance
)
notificationManager.createNotificationChannel(mChannel)
}
fun hasPermissions(): Boolean {
return notificationManager.areNotificationsEnabled()
}
} | mpl-2.0 | 76b42c04a88b0c4d2f254b2c7c516cf6 | 31.089744 | 102 | 0.70024 | 4.877193 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/returnByLabel.kt | 2 | 627 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
suspend fun suspendHere(): String = suspendCoroutineOrReturn { x ->
x.resume("OK")
COROUTINE_SUSPENDED
}
fun builder(c: suspend () -> Int): Int {
var res = 0
c.startCoroutine(handleResultContinuation {
res = it
})
return res
}
fun box(): String {
var result = ""
val handledResult = builder {
result = suspendHere()
return@builder 56
}
if (handledResult != 56) return "fail 1: $handledResult"
return result
}
| apache-2.0 | 2c78aa6123a80e9128cea7c25740a9ab | 18.59375 | 67 | 0.650718 | 4.236486 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/HashUtils.kt | 1 | 2192 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.*
import org.jetbrains.kotlin.backend.konan.hash.*
internal fun localHash(data: ByteArray): Long {
memScoped {
val res = alloc<LocalHashVar>()
val bytes = allocArrayOf(data)
MakeLocalHash(bytes, data.size, res.ptr)
return res.value
}
}
internal fun globalHash(data: ByteArray, retValPlacement: NativePlacement): GlobalHash {
val res = retValPlacement.alloc<GlobalHash>()
memScoped {
val bytes = allocArrayOf(data)
MakeGlobalHash(bytes, data.size, res.ptr)
}
return res
}
public fun base64Encode(data: ByteArray): String {
memScoped {
val resultSize = 4 * data.size / 3 + 3 + 1
val result = allocArray<ByteVar>(resultSize)
val bytes = allocArrayOf(data)
EncodeBase64(bytes, data.size, result, resultSize)
// TODO: any better way to do that without two copies?
return result.toKString()
}
}
public fun base64Decode(encoded: String): ByteArray {
memScoped {
val bufferSize: Int = 3 * encoded.length / 4
val result = allocArray<ByteVar>(bufferSize)
val resultSize = allocArray<uint32_tVar>(1)
resultSize[0] = bufferSize
val errorCode = DecodeBase64(encoded, encoded.length, result, resultSize)
if (errorCode != 0) throw Error("Non-zero exit code of DecodeBase64: ${errorCode}")
val realSize = resultSize[0]
return result.readBytes(realSize)
}
}
internal class LocalHash(val value: Long) : ConstValue by Int64(value)
| apache-2.0 | 2a00dc52eb4cbbfa885bd16a498e4eb8 | 33.25 | 91 | 0.687956 | 3.992714 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/MapTest/filter.kt | 2 | 552 | import kotlin.test.*
fun box() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filter { it.key[0] == 'b' }
assertEquals(mapOf("b" to 3), filteredByKey)
val filteredByKey2 = map.filterKeys { it[0] == 'b' }
assertEquals(mapOf("b" to 3), filteredByKey2)
val filteredByValue = map.filter { it.value == 2 }
assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue)
val filteredByValue2 = map.filterValues { it % 2 == 0 }
assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2)
}
| apache-2.0 | 0c07c1617be98741fe86745fe9a8c786 | 31.470588 | 61 | 0.615942 | 3.172414 | false | true | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/WorkSpaces.kt | 1 | 1730 | package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.workspaces.model.CreateWorkspacesRequest
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.WorkSpaces
import java.lang.IllegalArgumentException
class WorkSpacesWorkspaceResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateWorkspacesRequest> {
override val requestClazz = CreateWorkspacesRequest::class
override fun canBuildFrom(request: AmazonWebServiceRequest) = (request as CreateWorkspacesRequest).workspaces.isNotEmpty()
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateWorkspacesRequest).let {
if (request.workspaces.size > 1) {
// TODO: deferred client must throw this too
throw IllegalArgumentException("Creating multiple workspaces in one request not supported, use one CreateWorkspacesRequest per workspace")
}
val workspaceRequest = request.workspaces.first()
WorkSpaces.Workspace(
BundleId = workspaceRequest.bundleId,
DirectoryId = workspaceRequest.directoryId,
RootVolumeEncryptionEnabled = workspaceRequest.rootVolumeEncryptionEnabled?.toString(),
UserName = workspaceRequest.userName,
UserVolumeEncryptionEnabled = workspaceRequest.userVolumeEncryptionEnabled?.toString(),
VolumeEncryptionKey = workspaceRequest.volumeEncryptionKey
)
}
}
| mit | df46600ef3482d6b0b6e0b41579b12f6 | 49.882353 | 154 | 0.717341 | 5.635179 | false | false | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/manyvehicles/ManyVehiclesDemo.kt | 1 | 8675 | package de.fabmax.kool.demo.physics.manyvehicles
import de.fabmax.kool.AssetManager
import de.fabmax.kool.KoolContext
import de.fabmax.kool.demo.DemoLoader
import de.fabmax.kool.demo.DemoScene
import de.fabmax.kool.math.Mat3f
import de.fabmax.kool.math.Mat4f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.math.toRad
import de.fabmax.kool.physics.*
import de.fabmax.kool.physics.geometry.PlaneGeometry
import de.fabmax.kool.physics.vehicle.BatchVehicleUpdater
import de.fabmax.kool.physics.vehicle.Vehicle
import de.fabmax.kool.physics.vehicle.VehicleProperties
import de.fabmax.kool.physics.vehicle.VehicleUtils
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.Texture2d
import de.fabmax.kool.pipeline.ibl.EnvironmentHelper
import de.fabmax.kool.pipeline.ibl.EnvironmentMaps
import de.fabmax.kool.pipeline.shadermodel.PbrMaterialNode
import de.fabmax.kool.pipeline.shadermodel.StageInterfaceNode
import de.fabmax.kool.pipeline.shadermodel.fragmentStage
import de.fabmax.kool.pipeline.shadermodel.vertexStage
import de.fabmax.kool.pipeline.shading.PbrMaterialConfig
import de.fabmax.kool.pipeline.shading.PbrShader
import de.fabmax.kool.pipeline.shading.pbrShader
import de.fabmax.kool.scene.*
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.MdColor
import de.fabmax.kool.util.MutableColor
import kotlin.math.cos
import kotlin.math.sin
class ManyVehiclesDemo : DemoScene("Many Vehicles") {
private lateinit var ibl: EnvironmentMaps
private lateinit var physicsWorld: PhysicsWorld
private lateinit var batchUpdater: BatchVehicleUpdater
private val groundSimFilterData = FilterData(VehicleUtils.COLLISION_FLAG_GROUND, VehicleUtils.COLLISION_FLAG_GROUND_AGAINST)
private val groundQryFilterData = FilterData { VehicleUtils.setupDrivableSurface(this) }
private val numVehicles = 2048
private val chassisInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.COLORS), numVehicles)
private val wheelInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT), numVehicles * 4)
private val vehicleInstances = mutableListOf<VehicleInstance>()
private val vehicleProps = VehicleProperties().apply {
chassisDims = Vec3f(2f, 1f, 5f)
trackWidth = 1.8f
maxBrakeTorqueFront = 3000f
maxBrakeTorqueRear = 1500f
gearFinalRatio = 3f
maxCompression = 0.1f
maxDroop = 0.1f
springStrength = 50000f
springDamperRate = 6000f
wheelRadiusFront = 0.4f
wheelWidthFront = 0.3f
wheelMassFront = 30f
wheelPosFront = 1.7f
wheelRadiusRear = 0.4f
wheelWidthRear = 0.3f
wheelMassRear = 30f
wheelPosRear = -1.7f
updater = { vehicle, _ -> batchUpdater.addVehicle(vehicle) }
updateChassisMoiFromDimensionsAndMass()
updateWheelMoiFromRadiusAndMass()
}
override suspend fun AssetManager.loadResources(ctx: KoolContext) {
showLoadText("Loading IBL maps")
ibl = EnvironmentHelper.hdriEnvironment(mainScene, "${DemoLoader.hdriPath}/syferfontein_0d_clear_1k.rgbe.png", this)
mainScene += Skybox.cube(ibl.reflectionMap, 1f)
Physics.awaitLoaded()
physicsWorld = PhysicsWorld(numWorkers = 16)
physicsWorld.registerHandlers(mainScene)
batchUpdater = BatchVehicleUpdater(numVehicles, physicsWorld)
}
override fun Scene.setupMainScene(ctx: KoolContext) {
(camera as PerspectiveCamera).apply {
clipNear = 1f
clipFar = 1000f
}
defaultCamTransform().apply {
setZoom(100.0, max = 500.0)
}
makeGround()
+mesh(listOf(Attribute.POSITIONS, Attribute.NORMALS)) {
isFrustumChecked = false
instances = chassisInstances
generate {
cube {
size.set(vehicleProps.chassisDims)
centered()
}
}
shader = chassisShader()
}
+colorMesh {
isFrustumChecked = false
instances = wheelInstances
generate {
color = Color.DARK_GRAY.toLinear()
rotate(90f, Vec3f.Z_AXIS)
translate(0f, -vehicleProps.wheelWidthFront * 0.5f, 0f)
cylinder {
radius = vehicleProps.wheelRadiusFront
height = vehicleProps.wheelWidthFront
}
}
shader = wheelsShader()
}
onUpdate += {
chassisInstances.clear()
wheelInstances.clear()
for (i in vehicleInstances.indices) {
val vi = vehicleInstances[i]
vi.addChassisInstance(chassisInstances)
vi.addWheelInstances(wheelInstances)
}
}
for (j in 0 until 8) {
val n = 32
val r = 200f + j * 10
for (i in 0 until n) {
val aDeg = (360f / n * i) + j * 17f
val a = aDeg.toRad()
val pos = Vec3f(sin(a) * r, 1f, cos(a) * r)
spawnVehicle(pos, aDeg - 180f, MdColor.PALETTE[i % MdColor.PALETTE.size].toLinear())
}
}
}
private fun Group.makeGround() {
val groundAlbedo = Texture2d("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine.png")
val groundNormal = Texture2d("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine_normal.png")
onDispose += {
groundAlbedo.dispose()
groundNormal.dispose()
}
val gndMesh = textureMesh(isNormalMapped = true, name = "ground") {
generate {
isCastingShadow = false
vertexModFun = {
texCoord.set(x / 10f, z / 10f)
}
grid {
sizeX = 1000f
sizeY = 1000f
stepsX = sizeX.toInt() / 10
stepsY = sizeY.toInt() / 10
}
}
shader = pbrShader {
useAlbedoMap(groundAlbedo)
useNormalMap(groundNormal)
useImageBasedLighting(ibl)
}
}
+gndMesh
val ground = RigidStatic().apply {
simulationFilterData = groundSimFilterData
queryFilterData = groundQryFilterData
attachShape(Shape(PlaneGeometry(), Physics.defaultMaterial))
setRotation(Mat3f().rotate(90f, Vec3f.Z_AXIS))
}
physicsWorld.addActor(ground)
}
private fun spawnVehicle(pos: Vec3f, dir: Float, color: Color) {
val vehicle = Vehicle(vehicleProps, physicsWorld)
vehicle.position = pos
vehicle.throttleInput = 0.75f
vehicle.steerInput = 0f
vehicle.setRotation(0f, dir, 0f)
physicsWorld.addActor(vehicle)
vehicleInstances += VehicleInstance(vehicle, color)
}
private fun chassisShader(): PbrShader {
val cfg = PbrMaterialConfig().apply {
isInstanced = true
roughness = 1f
useStaticAlbedo(Color.WHITE)
useImageBasedLighting(ibl)
}
val model = PbrShader.defaultPbrModel(cfg).apply {
val ifInstColor: StageInterfaceNode
vertexStage {
ifInstColor = stageInterfaceNode("ifInstColor", instanceAttributeNode(Attribute.COLORS).output)
}
fragmentStage {
findNodeByType<PbrMaterialNode>()!!.inAlbedo = ifInstColor.output
}
}
return PbrShader(cfg, model)
}
private fun wheelsShader(): PbrShader {
val cfg = PbrMaterialConfig().apply {
isInstanced = true
roughness = 0.8f
useImageBasedLighting(ibl)
}
val model = PbrShader.defaultPbrModel(cfg)
return PbrShader(cfg, model)
}
private class VehicleInstance(val vehicle: Vehicle, color: Color) {
private val tmpMat = Mat4f()
private val color = MutableColor(color)
fun addChassisInstance(instanceData: MeshInstanceList) {
instanceData.addInstance {
put(vehicle.transform.matrix)
put(color.array)
}
}
fun addWheelInstances(instanceData: MeshInstanceList) {
for (i in 0..3) {
val wheelInfo = vehicle.wheelInfos[i]
tmpMat.set(vehicle.transform).mul(wheelInfo.transform)
instanceData.addInstance {
put(tmpMat.matrix)
}
}
}
}
} | apache-2.0 | 9534b14384ce8a757d682604289012f9 | 34.125506 | 128 | 0.618213 | 4.307349 | false | false | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/presentation/cli/firebase/test/ios/IosModelsCommand.kt | 1 | 874 | package ftl.presentation.cli.firebase.test.ios
import ftl.presentation.cli.firebase.test.ios.models.IosModelDescribeCommand
import ftl.presentation.cli.firebase.test.ios.models.IosModelsListCommand
import ftl.util.PrintHelpCommand
import picocli.CommandLine
@CommandLine.Command(
name = "models",
headerHeading = "",
synopsisHeading = "%n",
descriptionHeading = "%n@|bold,underline Description:|@%n%n",
parameterListHeading = "%n@|bold,underline Parameters:|@%n",
optionListHeading = "%n@|bold,underline Options:|@%n",
header = ["Information about available models"],
description = ["Information about available models. For example prints list of available models to test against"],
subcommands = [IosModelsListCommand::class, IosModelDescribeCommand::class],
usageHelpAutoWidth = true
)
class IosModelsCommand : PrintHelpCommand()
| apache-2.0 | 51ac25e129ff2bbcf23f7b3d3d1f2f0f | 42.7 | 118 | 0.759725 | 4.242718 | false | true | false | false |
kohesive/kohesive-iac | model-aws/src/test/kotlin/uy/kohesive/iac/model/aws/TestUseCase_DynamoDB_Table_1.kt | 1 | 3678 | package uy.kohesive.iac.model.aws
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement
import com.amazonaws.services.dynamodbv2.model.KeyType
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import junit.framework.TestCase
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationContext
import uy.kohesive.iac.model.aws.cloudformation.TemplateBuilder
import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy
class TestUseCase_DynamoDB_Table_1 : TestCase() {
fun `test making a DynamoDB table using the SDK`() {
// ===[ VARIABLES ]=============================================================================================
val hashKeyNameParam = ParameterizedValue.newString("HaskKeyElementName",
description = "HashType PrimaryKey Name",
allowedPattern = "[a-zA-Z0-9]*".toRegex(),
allowedLength = 1..2048,
constraintDescription = "Must contain only alphanumberic characters"
)
val hashKeyTypeParam = ParameterizedValue.newString("HaskKeyElementType",
description = "HashType PrimaryKey Type",
defaultValue = "S",
allowedPattern = "[S|N]".toRegex(),
allowedLength = 1..1,
constraintDescription = "Must be either S or N"
)
val readCapacityParam = ParameterizedValue.newLong("ReadCapacityUnits",
description = "Provisioned read throughput",
defaultValue = 5,
allowedNumericValues = 5L..10000L,
constraintDescription = "Should be between 5 and 10000"
)
val writeCapacityParam = ParameterizedValue.newLong("WriteCapacityUnits",
description = "Provisioned read throughput",
defaultValue = 10,
allowedNumericValues = 5L..10000L,
constraintDescription = "Should be between 5 and 10000"
)
// ===[ BUILDING ]==============================================================================================
val context = CloudFormationContext("test", "dynamodb-table-myDynamoDBTable") {
addVariables(hashKeyNameParam, hashKeyTypeParam, readCapacityParam, writeCapacityParam)
withDynamoDBContext {
val table = createTable("myDynamoDBTable") {
withKeySchema(KeySchemaElement(hashKeyNameParam.value, KeyType.HASH))
withAttributeDefinitions(AttributeDefinition(hashKeyNameParam.value, hashKeyTypeParam.value))
withProvisionedThroughput(ProvisionedThroughput()
.withReadCapacityUnits(readCapacityParam.value)
.withWriteCapacityUnits(writeCapacityParam.value)
)
}
addAsOutput("TableName", table, "Table name of the newly create DynamoDB table")
}
}
val JsonWriter = jacksonObjectMapper()
.setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.writerWithDefaultPrettyPrinter()
val cfTemplate = TemplateBuilder(context, description = "AWS CloudFormation Sample Template: This template demonstrates the creation of a DynamoDB table.").build()
println(JsonWriter.writeValueAsString(cfTemplate))
}
} | mit | 01f6f098d8b44a6423f01d5774263c08 | 46.779221 | 171 | 0.627787 | 5.481371 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/kotlinPsiElementMapping.kt | 1 | 33959 | // 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.uast.kotlin
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.*
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.kotlin.psi.*
import org.jetbrains.uast.psi.UElementWithLocation
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.classSetOf
import org.jetbrains.uast.util.emptyClassSet
private val checkCanConvert = Registry.`is`("kotlin.uast.use.psi.type.precheck", true)
internal fun canConvert(element: PsiElement, targets: Array<out Class<out UElement>>): Boolean {
if (!checkCanConvert) return true
val originalCls = element.originalElement.javaClass
if (targets.any { getPossibleSourceTypes(it).let { originalCls in it } })
return true
val ktOriginalCls = (element as? KtLightElementBase)?.kotlinOrigin?.javaClass ?: return false
return targets.any { getPossibleSourceTypes(it).let { ktOriginalCls in it } }
}
internal fun getPossibleSourceTypes(uastType: Class<out UElement>) =
possibleSourceTypes[uastType] ?: emptyClassSet()
/**
* For every [UElement] subtype states from which [PsiElement] subtypes it can be obtained.
*
* This map is machine generated by `KotlinUastMappingsAccountantOverLargeProjectTest`
*/
@Suppress("DEPRECATION", "RemoveExplicitTypeArguments", "DuplicatedCode")
private val possibleSourceTypes = mapOf<Class<*>, ClassSet<PsiElement>>(
UAnchorOwner::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtClass::class.java,
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtFile::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
KtTypeReference::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UAnnotated::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KtAnnotatedExpression::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDestructuringDeclarationEntry::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtFile::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UAnnotation::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtLightAnnotationForSourceEntry::class.java
),
UAnnotationEx::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtLightAnnotationForSourceEntry::class.java
),
UAnnotationMethod::class.java to classSetOf<PsiElement>(
KtLightDeclaration::class.java,
KtParameter::class.java
),
UAnonymousClass::class.java to classSetOf<PsiElement>(
KtLightClass::class.java,
KtObjectDeclaration::class.java
),
UArrayAccessExpression::class.java to classSetOf<PsiElement>(
KtArrayAccessExpression::class.java,
KtBlockStringTemplateEntry::class.java
),
UBinaryExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionWithExpression::class.java
),
UBinaryExpressionWithType::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtIsExpression::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java
),
UBlockExpression::class.java to classSetOf<PsiElement>(
KtBlockExpression::class.java
),
UBreakExpression::class.java to classSetOf<PsiElement>(
KtBreakExpression::class.java
),
UCallExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtStringTemplateExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtWhenConditionWithExpression::class.java,
KtLightPsiArrayInitializerMemberValue::class.java
),
UCallExpressionEx::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtStringTemplateExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtWhenConditionWithExpression::class.java,
KtLightPsiArrayInitializerMemberValue::class.java
),
UCallableReferenceExpression::class.java to classSetOf<PsiElement>(
KtCallableReferenceExpression::class.java
),
UCatchClause::class.java to classSetOf<PsiElement>(
KtCatchClause::class.java
),
UClass::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtFile::class.java,
KtLightClass::class.java,
KtObjectDeclaration::class.java
),
UClassInitializer::class.java to classSetOf<PsiElement>(
),
UClassInitializerEx::class.java to classSetOf<PsiElement>(
),
UClassLiteralExpression::class.java to classSetOf<PsiElement>(
KtClassLiteralExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UComment::class.java to classSetOf<PsiElement>(
PsiComment::class.java
),
UContinueExpression::class.java to classSetOf<PsiElement>(
KtContinueExpression::class.java
),
UDeclaration::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtFile::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
KtTypeReference::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UDeclarationEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UDeclarationsExpression::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtDestructuringDeclaration::class.java,
KtEnumEntry::class.java,
KtFunctionLiteral::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameterList::class.java,
KtPrimaryConstructor::class.java,
KtSecondaryConstructor::class.java
),
UDoWhileExpression::class.java to classSetOf<PsiElement>(
KtDoWhileExpression::class.java
),
UElement::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCatchClause::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDestructuringDeclarationEntry::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtFile::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtImportDirective::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java,
LeafPsiElement::class.java,
PsiComment::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UElementWithLocation::class.java to classSetOf<PsiElement>(
),
UEnumConstant::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java
),
UEnumConstantEx::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java
),
UExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java
),
UExpressionList::class.java to classSetOf<PsiElement>(
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtClassBody::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtWhenConditionWithExpression::class.java
),
UField::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtParameter::class.java,
KtProperty::class.java
),
UFieldEx::class.java to classSetOf<PsiElement>(
KtLightFieldForSourceDeclarationSupport::class.java,
KtParameter::class.java,
KtProperty::class.java
),
UFile::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KtFile::class.java
),
UForEachExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtForExpression::class.java
),
UForExpression::class.java to classSetOf<PsiElement>(
),
UIdentifier::class.java to classSetOf<PsiElement>(
LeafPsiElement::class.java
),
UIfExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtIfExpression::class.java
),
UImportStatement::class.java to classSetOf<PsiElement>(
KtImportDirective::class.java
),
UInjectionHost::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UInstanceExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtSuperExpression::class.java,
KtThisExpression::class.java
),
UJumpExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBreakExpression::class.java,
KtContinueExpression::class.java,
KtReturnExpression::class.java
),
ULabeled::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtLabeledExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtSuperExpression::class.java,
KtThisExpression::class.java
),
ULabeledExpression::class.java to classSetOf<PsiElement>(
KtLabeledExpression::class.java
),
ULambdaExpression::class.java to classSetOf<PsiElement>(
KtFunctionLiteral::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtPrimaryConstructor::class.java
),
ULiteralExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtConstantExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
ULocalVariable::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtProperty::class.java,
UastKotlinPsiVariable::class.java
),
ULocalVariableEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtProperty::class.java,
UastKotlinPsiVariable::class.java
),
ULoopExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtDoWhileExpression::class.java,
KtForExpression::class.java,
KtWhileExpression::class.java
),
UMethod::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java
),
UMultiResolvable::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtImportDirective::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtPostfixExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UNamedExpression::class.java to classSetOf<PsiElement>(
),
UObjectLiteralExpression::class.java to classSetOf<PsiElement>(
KtObjectLiteralExpression::class.java,
KtSuperTypeCallEntry::class.java
),
UParameter::class.java to classSetOf<PsiElement>(
KtLightParameter::class.java,
KtParameter::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java
),
UParameterEx::class.java to classSetOf<PsiElement>(
KtLightParameter::class.java,
KtParameter::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java
),
UParenthesizedExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtParenthesizedExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UPolyadicExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionWithExpression::class.java
),
UPostfixExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtPostfixExpression::class.java
),
UPrefixExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtPrefixExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UQualifiedReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtDotQualifiedExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallableReferenceExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtLabelReferenceExpression::class.java,
KtNameReferenceExpression::class.java,
KtOperationReferenceExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UResolvable::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtImportDirective::class.java,
KtLabelReferenceExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtNameReferenceExpression::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtPostfixExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UReturnExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtReturnExpression::class.java
),
USimpleNameReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtLabelReferenceExpression::class.java,
KtNameReferenceExpression::class.java,
KtOperationReferenceExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
USuperExpression::class.java to classSetOf<PsiElement>(
KtSuperExpression::class.java
),
USwitchClauseExpression::class.java to classSetOf<PsiElement>(
KtWhenEntry::class.java
),
USwitchClauseExpressionWithBody::class.java to classSetOf<PsiElement>(
KtWhenEntry::class.java
),
USwitchExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtWhenExpression::class.java
),
UThisExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtThisExpression::class.java
),
UThrowExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtThrowExpression::class.java
),
UTryExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtTryExpression::class.java
),
UTypeReferenceExpression::class.java to classSetOf<PsiElement>(
KtTypeReference::class.java
),
UUnaryExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UVariable::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UVariableEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UWhileExpression::class.java to classSetOf<PsiElement>(
KtWhileExpression::class.java
),
UYieldExpression::class.java to classSetOf<PsiElement>(
),
UastEmptyExpression::class.java to classSetOf<PsiElement>(
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtClass::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtObjectDeclaration::class.java,
KtStringTemplateExpression::class.java
),
UnknownKotlinExpression::class.java to classSetOf<PsiElement>(
KtClassInitializer::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtLightDeclaration::class.java,
KtParameter::class.java,
KtPropertyAccessor::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java
)
)
| apache-2.0 | 1a15529d315582b698afba64a2c0c669 | 39.767107 | 158 | 0.702877 | 5.582607 | false | false | false | false |
JetBrains/kotlin-native | Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/StubIrBridgeBuilder.kt | 2 | 16250 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform
import org.jetbrains.kotlin.native.interop.indexer.*
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class BridgeBuilderResult(
val kotlinFile: KotlinFile,
val nativeBridges: NativeBridges,
val propertyAccessorBridgeBodies: Map<PropertyAccessor, String>,
val functionBridgeBodies: Map<FunctionStub, List<String>>,
val excludedStubs: Set<StubIrElement>
)
/**
* Generates [NativeBridges] and corresponding function bodies and property accessors.
*/
class StubIrBridgeBuilder(
private val context: StubIrContext,
private val builderResult: StubIrBuilderResult) {
private val globalAddressExpressions = mutableMapOf<Pair<String, PropertyAccessor>, KotlinExpression>()
private val wrapperGenerator = CWrappersGenerator(context)
private fun getGlobalAddressExpression(cGlobalName: String, accessor: PropertyAccessor) =
globalAddressExpressions.getOrPut(Pair(cGlobalName, accessor)) {
simpleBridgeGenerator.kotlinToNative(
nativeBacked = accessor,
returnType = BridgedType.NATIVE_PTR,
kotlinValues = emptyList(),
independent = false
) {
"&$cGlobalName"
}
}
private val declarationMapper = builderResult.declarationMapper
private val kotlinFile = object : KotlinFile(
context.configuration.pkgName,
namesToBeDeclared = builderResult.stubs.computeNamesToBeDeclared(context.configuration.pkgName)
) {
override val mappingBridgeGenerator: MappingBridgeGenerator
get() = [email protected]
}
private val simpleBridgeGenerator: SimpleBridgeGenerator =
SimpleBridgeGeneratorImpl(
context.platform,
context.configuration.pkgName,
context.jvmFileClassName,
context.libraryForCStubs,
topLevelNativeScope = object : NativeScope {
override val mappingBridgeGenerator: MappingBridgeGenerator
get() = [email protected]
},
topLevelKotlinScope = kotlinFile
)
private val mappingBridgeGenerator: MappingBridgeGenerator =
MappingBridgeGeneratorImpl(declarationMapper, simpleBridgeGenerator)
private val propertyAccessorBridgeBodies = mutableMapOf<PropertyAccessor, String>()
private val functionBridgeBodies = mutableMapOf<FunctionStub, List<String>>()
private val excludedStubs = mutableSetOf<StubIrElement>()
private val bridgeGeneratingVisitor = object : StubIrVisitor<StubContainer?, Unit> {
override fun visitClass(element: ClassStub, data: StubContainer?) {
element.annotations.filterIsInstance<AnnotationStub.ObjC.ExternalClass>().firstOrNull()?.let {
val origin = element.origin
if (it.protocolGetter.isNotEmpty() && origin is StubOrigin.ObjCProtocol && !origin.isMeta) {
val protocol = (element.origin as StubOrigin.ObjCProtocol).protocol
// TODO: handle the case when protocol getter stub can't be compiled.
generateProtocolGetter(it.protocolGetter, protocol)
}
}
element.children.forEach {
it.accept(this, element)
}
}
override fun visitTypealias(element: TypealiasStub, data: StubContainer?) {
}
override fun visitFunction(element: FunctionStub, data: StubContainer?) {
try {
when {
element.external -> tryProcessCCallAnnotation(element)
element.isOptionalObjCMethod() -> { }
element.origin is StubOrigin.Synthetic.EnumByValue -> { }
data != null && data.isInterface -> { }
else -> generateBridgeBody(element)
}
} catch (e: Throwable) {
context.log("Warning: cannot generate bridge for ${element.name}.")
excludedStubs += element
}
}
private fun tryProcessCCallAnnotation(function: FunctionStub) {
val origin = function.origin as? StubOrigin.Function
?: return
val cCallAnnotation = function.annotations.firstIsInstanceOrNull<AnnotationStub.CCall.Symbol>()
?: return
val wrapper = wrapperGenerator.generateCCalleeWrapper(origin.function, cCallAnnotation.symbolName)
simpleBridgeGenerator.insertNativeBridge(function, emptyList(), wrapper.lines)
}
override fun visitProperty(element: PropertyStub, data: StubContainer?) {
try {
when (val kind = element.kind) {
is PropertyStub.Kind.Constant -> {
}
is PropertyStub.Kind.Val -> {
visitPropertyAccessor(kind.getter, data)
}
is PropertyStub.Kind.Var -> {
visitPropertyAccessor(kind.getter, data)
visitPropertyAccessor(kind.setter, data)
}
}
} catch (e: Throwable) {
context.log("Warning: cannot generate bridge for ${element.name}.")
excludedStubs += element
}
}
override fun visitConstructor(constructorStub: ConstructorStub, data: StubContainer?) {
}
override fun visitPropertyAccessor(propertyAccessor: PropertyAccessor, data: StubContainer?) {
when (propertyAccessor) {
is PropertyAccessor.Getter.SimpleGetter -> {
when (propertyAccessor) {
in builderResult.bridgeGenerationComponents.getterToBridgeInfo -> {
val extra = builderResult.bridgeGenerationComponents.getterToBridgeInfo.getValue(propertyAccessor)
val typeInfo = extra.typeInfo
propertyAccessorBridgeBodies[propertyAccessor] = typeInfo.argFromBridged(simpleBridgeGenerator.kotlinToNative(
nativeBacked = propertyAccessor,
returnType = typeInfo.bridgedType,
kotlinValues = emptyList(),
independent = false
) {
typeInfo.cToBridged(expr = extra.cGlobalName)
}, kotlinFile, nativeBacked = propertyAccessor)
}
in builderResult.bridgeGenerationComponents.arrayGetterInfo -> {
val extra = builderResult.bridgeGenerationComponents.arrayGetterInfo.getValue(propertyAccessor)
val typeInfo = extra.typeInfo
val getAddressExpression = getGlobalAddressExpression(extra.cGlobalName, propertyAccessor)
propertyAccessorBridgeBodies[propertyAccessor] = typeInfo.argFromBridged(getAddressExpression, kotlinFile, nativeBacked = propertyAccessor) + "!!"
}
}
}
is PropertyAccessor.Getter.ReadBits -> {
val extra = builderResult.bridgeGenerationComponents.getterToBridgeInfo.getValue(propertyAccessor)
val rawType = extra.typeInfo.bridgedType
val readBits = "readBits(this.rawPtr, ${propertyAccessor.offset}, ${propertyAccessor.size}, ${propertyAccessor.signed}).${rawType.convertor!!}()"
val getExpr = extra.typeInfo.argFromBridged(readBits, kotlinFile, object : NativeBacked {})
propertyAccessorBridgeBodies[propertyAccessor] = getExpr
}
is PropertyAccessor.Setter.SimpleSetter -> when (propertyAccessor) {
in builderResult.bridgeGenerationComponents.setterToBridgeInfo -> {
val extra = builderResult.bridgeGenerationComponents.setterToBridgeInfo.getValue(propertyAccessor)
val typeInfo = extra.typeInfo
val bridgedValue = BridgeTypedKotlinValue(typeInfo.bridgedType, typeInfo.argToBridged("value"))
val setter = simpleBridgeGenerator.kotlinToNative(
nativeBacked = propertyAccessor,
returnType = BridgedType.VOID,
kotlinValues = listOf(bridgedValue),
independent = false
) { nativeValues ->
out("${extra.cGlobalName} = ${typeInfo.cFromBridged(
nativeValues.single(),
scope,
nativeBacked = propertyAccessor
)};")
""
}
propertyAccessorBridgeBodies[propertyAccessor] = setter
}
}
is PropertyAccessor.Setter.WriteBits -> {
val extra = builderResult.bridgeGenerationComponents.setterToBridgeInfo.getValue(propertyAccessor)
val rawValue = extra.typeInfo.argToBridged("value")
propertyAccessorBridgeBodies[propertyAccessor] = "writeBits(this.rawPtr, ${propertyAccessor.offset}, ${propertyAccessor.size}, $rawValue.toLong())"
}
is PropertyAccessor.Getter.InterpretPointed -> {
val getAddressExpression = getGlobalAddressExpression(propertyAccessor.cGlobalName, propertyAccessor)
propertyAccessorBridgeBodies[propertyAccessor] = getAddressExpression
}
is PropertyAccessor.Getter.ExternalGetter -> {
if (propertyAccessor in builderResult.wrapperGenerationComponents.getterToWrapperInfo) {
val extra = builderResult.wrapperGenerationComponents.getterToWrapperInfo.getValue(propertyAccessor)
val cCallAnnotation = propertyAccessor.annotations.firstIsInstanceOrNull<AnnotationStub.CCall.Symbol>()
?: error("external getter for ${extra.global.name} wasn't marked with @CCall")
val wrapper = if (extra.passViaPointer) {
wrapperGenerator.generateCGlobalByPointerGetter(extra.global, cCallAnnotation.symbolName)
} else {
wrapperGenerator.generateCGlobalGetter(extra.global, cCallAnnotation.symbolName)
}
simpleBridgeGenerator.insertNativeBridge(propertyAccessor, emptyList(), wrapper.lines)
}
}
is PropertyAccessor.Setter.ExternalSetter -> {
if (propertyAccessor in builderResult.wrapperGenerationComponents.setterToWrapperInfo) {
val extra = builderResult.wrapperGenerationComponents.setterToWrapperInfo.getValue(propertyAccessor)
val cCallAnnotation = propertyAccessor.annotations.firstIsInstanceOrNull<AnnotationStub.CCall.Symbol>()
?: error("external setter for ${extra.global.name} wasn't marked with @CCall")
val wrapper = wrapperGenerator.generateCGlobalSetter(extra.global, cCallAnnotation.symbolName)
simpleBridgeGenerator.insertNativeBridge(propertyAccessor, emptyList(), wrapper.lines)
}
}
}
}
override fun visitSimpleStubContainer(simpleStubContainer: SimpleStubContainer, data: StubContainer?) {
simpleStubContainer.classes.forEach {
it.accept(this, simpleStubContainer)
}
simpleStubContainer.functions.forEach {
it.accept(this, simpleStubContainer)
}
simpleStubContainer.properties.forEach {
it.accept(this, simpleStubContainer)
}
simpleStubContainer.typealiases.forEach {
it.accept(this, simpleStubContainer)
}
simpleStubContainer.simpleContainers.forEach {
it.accept(this, simpleStubContainer)
}
}
}
private fun isCValuesRef(type: StubType): Boolean =
(type as? ClassifierStubType)?.let { it.classifier == KotlinTypes.cValuesRef }
?: false
private fun generateBridgeBody(function: FunctionStub) {
assert(context.platform == KotlinPlatform.JVM) { "Function ${function.name} was not marked as external." }
assert(function.origin is StubOrigin.Function) { "Can't create bridge for ${function.name}" }
val origin = function.origin as StubOrigin.Function
val bodyGenerator = KotlinCodeBuilder(scope = kotlinFile)
val bridgeArguments = mutableListOf<TypedKotlinValue>()
var isVararg = false
function.parameters.forEachIndexed { index, parameter ->
isVararg = isVararg or parameter.isVararg
val parameterName = parameter.name.asSimpleName()
val bridgeArgument = when {
parameter in builderResult.bridgeGenerationComponents.cStringParameters -> {
bodyGenerator.pushMemScoped()
"$parameterName?.cstr?.getPointer(memScope)"
}
parameter in builderResult.bridgeGenerationComponents.wCStringParameters -> {
bodyGenerator.pushMemScoped()
"$parameterName?.wcstr?.getPointer(memScope)"
}
isCValuesRef(parameter.type) -> {
bodyGenerator.pushMemScoped()
bodyGenerator.getNativePointer(parameterName)
}
else -> {
parameterName
}
}
bridgeArguments += TypedKotlinValue(origin.function.parameters[index].type, bridgeArgument)
}
// TODO: Improve assertion message.
assert(!isVararg || context.platform != KotlinPlatform.NATIVE) {
"Function ${function.name} was processed incorrectly."
}
val result = mappingBridgeGenerator.kotlinToNative(
bodyGenerator,
function,
origin.function.returnType,
bridgeArguments,
independent = false
) { nativeValues ->
"${origin.function.name}(${nativeValues.joinToString()})"
}
bodyGenerator.returnResult(result)
functionBridgeBodies[function] = bodyGenerator.build()
}
private fun generateProtocolGetter(protocolGetterName: String, protocol: ObjCProtocol) {
val builder = NativeCodeBuilder(simpleBridgeGenerator.topLevelNativeScope)
val nativeBacked = object : NativeBacked {}
with(builder) {
out("Protocol* $protocolGetterName() {")
out(" return @protocol(${protocol.name});")
out("}")
}
simpleBridgeGenerator.insertNativeBridge(nativeBacked, emptyList(), builder.lines)
}
fun build(): BridgeBuilderResult {
bridgeGeneratingVisitor.visitSimpleStubContainer(builderResult.stubs, null)
return BridgeBuilderResult(
kotlinFile,
simpleBridgeGenerator.prepare(),
propertyAccessorBridgeBodies.toMap(),
functionBridgeBodies.toMap(),
excludedStubs.toSet()
)
}
}
| apache-2.0 | 24940a00aeca8b096223b10fc3f5643f | 49.940439 | 174 | 0.594523 | 5.894088 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/api/fixes/KtQuickFixesList.kt | 3 | 4823 | // 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.fir.api.fixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi
import org.jetbrains.kotlin.idea.quickfix.QuickFixesPsiBasedFactory
import org.jetbrains.kotlin.miniStdLib.annotations.PrivateForInline
import kotlin.reflect.KClass
class KtQuickFixesList @ForKtQuickFixesListBuilder @OptIn(PrivateForInline::class) constructor(
private val quickFixes: Map<KClass<out KtDiagnosticWithPsi<*>>, List<HLQuickFixFactory>>
) {
@OptIn(PrivateForInline::class)
fun KtAnalysisSession.getQuickFixesFor(diagnostic: KtDiagnosticWithPsi<*>): List<IntentionAction> {
val factories = quickFixes[diagnostic.diagnosticClass] ?: return emptyList()
return factories.flatMap { createQuickFixes(it, diagnostic) }
}
@OptIn(PrivateForInline::class)
private fun KtAnalysisSession.createQuickFixes(
quickFixFactory: HLQuickFixFactory,
diagnostic: KtDiagnosticWithPsi<*>
): List<IntentionAction> = when (quickFixFactory) {
is HLQuickFixFactory.HLApplicatorBasedFactory -> {
@Suppress("UNCHECKED_CAST")
val factory = quickFixFactory.applicatorFactory
as HLDiagnosticFixFactory<KtDiagnosticWithPsi<PsiElement>>
createPlatformQuickFixes(diagnostic, factory)
}
is HLQuickFixFactory.HLQuickFixesPsiBasedFactory -> quickFixFactory.psiFactory.createQuickFix(diagnostic.psi)
}
companion object {
@OptIn(ForKtQuickFixesListBuilder::class, PrivateForInline::class)
fun createCombined(registrars: List<KtQuickFixesList>): KtQuickFixesList {
val allQuickFixes = registrars.map { it.quickFixes }.merge()
return KtQuickFixesList(allQuickFixes)
}
fun createCombined(vararg registrars: KtQuickFixesList): KtQuickFixesList {
return createCombined(registrars.toList())
}
}
}
class KtQuickFixesListBuilder private constructor() {
@OptIn(PrivateForInline::class)
private val quickFixes = mutableMapOf<KClass<out KtDiagnosticWithPsi<*>>, MutableList<HLQuickFixFactory>>()
@OptIn(PrivateForInline::class)
fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> registerPsiQuickFixes(
diagnosticClass: KClass<DIAGNOSTIC>,
vararg quickFixFactories: QuickFixesPsiBasedFactory<in DIAGNOSTIC_PSI>
) {
for (quickFixFactory in quickFixFactories) {
registerPsiQuickFix(diagnosticClass, quickFixFactory)
}
}
@PrivateForInline
fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> registerPsiQuickFix(
diagnosticClass: KClass<DIAGNOSTIC>,
quickFixFactory: QuickFixesPsiBasedFactory<in DIAGNOSTIC_PSI>
) {
quickFixes.getOrPut(diagnosticClass) { mutableListOf() }.add(HLQuickFixFactory.HLQuickFixesPsiBasedFactory(quickFixFactory))
}
@OptIn(PrivateForInline::class)
fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> registerApplicators(
quickFixFactories: Collection<HLDiagnosticFixFactory<out DIAGNOSTIC>>
) {
quickFixFactories.forEach(::registerApplicator)
}
@OptIn(PrivateForInline::class)
fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> registerApplicator(
quickFixFactory: HLDiagnosticFixFactory<out DIAGNOSTIC>
) {
quickFixes.getOrPut(quickFixFactory.diagnosticClass) { mutableListOf() }
.add(HLQuickFixFactory.HLApplicatorBasedFactory(quickFixFactory))
}
@OptIn(ForKtQuickFixesListBuilder::class, PrivateForInline::class)
private fun build() = KtQuickFixesList(quickFixes)
companion object {
fun registerPsiQuickFix(init: KtQuickFixesListBuilder.() -> Unit) = KtQuickFixesListBuilder().apply(init).build()
}
}
@PrivateForInline
sealed class HLQuickFixFactory {
class HLQuickFixesPsiBasedFactory(
val psiFactory: QuickFixesPsiBasedFactory<*>
) : HLQuickFixFactory()
class HLApplicatorBasedFactory(
val applicatorFactory: HLDiagnosticFixFactory<*>
) : HLQuickFixFactory()
}
private fun <K, V> List<Map<K, List<V>>>.merge(): Map<K, List<V>> {
return flatMap { it.entries }
.groupingBy { it.key }
.aggregate<Map.Entry<K, List<V>>, K, MutableList<V>> { _, accumulator, element, _ ->
val list = accumulator ?: mutableListOf()
list.addAll(element.value)
list
}
}
@RequiresOptIn
annotation class ForKtQuickFixesListBuilder
| apache-2.0 | b0eb2cf4fd781c44cd496c420004bcb5 | 39.529412 | 158 | 0.728177 | 4.67345 | false | false | false | false |
BijoySingh/Quick-Note-Android | scarlet/src/main/java/com/bijoysingh/quicknote/firebase/support/FirebaseFolderReference.kt | 1 | 2098 | package com.bijoysingh.quicknote.firebase.support
import com.bijoysingh.quicknote.firebase.FirebaseRemoteDatabase
import com.bijoysingh.quicknote.firebase.activity.ForgetMeActivity
import com.bijoysingh.quicknote.firebase.data.FirebaseFolder
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.maubis.scarlet.base.support.utils.maybeThrow
/**
* Functions for Database Reference for Firebase Notes
*/
fun FirebaseRemoteDatabase.initFolderReference(userId: String) {
firebaseFolder = FirebaseDatabase
.getInstance()
.getReference()
.child("folders")
.child(userId)
setFolderListener()
}
fun FirebaseRemoteDatabase.setFolderListener() {
if (firebaseFolder === null) {
return
}
firebaseFolder!!.addChildEventListener(object : ChildEventListener {
override fun onCancelled(p0: DatabaseError) {
// Ignore cancelled
}
override fun onChildMoved(snapshot: DataSnapshot, p1: String?) {
// Ignore moved child
}
override fun onChildChanged(snapshot: DataSnapshot, p1: String?) {
if (ForgetMeActivity.forgettingInProcess) {
return
}
onChildAdded(snapshot, p1)
}
override fun onChildAdded(snapshot: DataSnapshot, p1: String?) {
if (ForgetMeActivity.forgettingInProcess) {
return
}
try {
val folder = snapshot.getValue(FirebaseFolder::class.java)
if (folder === null) {
return
}
onRemoteInsert(folder)
} catch (exception: Exception) {
maybeThrow(exception)
}
}
override fun onChildRemoved(snapshot: DataSnapshot) {
if (ForgetMeActivity.forgettingInProcess) {
return
}
try {
val folder = snapshot.getValue(FirebaseFolder::class.java)
if (folder === null) {
return
}
onRemoteRemove(folder)
} catch (exception: Exception) {
maybeThrow(exception)
}
}
})
} | gpl-3.0 | 487e01cfa45790f206e1337fe459783e | 26.986667 | 70 | 0.690658 | 4.541126 | false | false | false | false |
androidx/androidx | health/connect/connect-client/samples/src/main/java/androidx/health/connect/client/samples/ReadRecordsSamples.kt | 3 | 3661 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UNUSED_VARIABLE")
package androidx.health.connect.client.samples
import androidx.annotation.Sampled
import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.records.ExerciseSessionRecord
import androidx.health.connect.client.records.HeartRateRecord
import androidx.health.connect.client.records.SleepSessionRecord
import androidx.health.connect.client.records.SleepStageRecord
import androidx.health.connect.client.records.StepsRecord
import androidx.health.connect.client.request.ReadRecordsRequest
import androidx.health.connect.client.time.TimeRangeFilter
import java.time.Instant
@Sampled
suspend fun ReadStepsRange(
healthConnectClient: HealthConnectClient,
startTime: Instant,
endTime: Instant
) {
val response =
healthConnectClient.readRecords(
ReadRecordsRequest(
StepsRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
)
)
for (stepRecord in response.records) {
// Process each step record
}
}
@Sampled
suspend fun ReadExerciseSessions(
healthConnectClient: HealthConnectClient,
startTime: Instant,
endTime: Instant
) {
val response =
healthConnectClient.readRecords(
ReadRecordsRequest(
ExerciseSessionRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
)
)
for (exerciseRecord in response.records) {
// Process each exercise record
// Optionally pull in with other data sources of the same time range.
val heartRateRecords =
healthConnectClient
.readRecords(
ReadRecordsRequest(
HeartRateRecord::class,
timeRangeFilter =
TimeRangeFilter.between(
exerciseRecord.startTime,
exerciseRecord.endTime
)
)
)
.records
}
}
@Sampled
suspend fun ReadSleepSessions(
healthConnectClient: HealthConnectClient,
startTime: Instant,
endTime: Instant
) {
val response =
healthConnectClient.readRecords(
ReadRecordsRequest(
SleepSessionRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
)
)
for (sleepRecord in response.records) {
// Process each exercise record
// Optionally pull in sleep stages of the same time range
val sleepStageRecords =
healthConnectClient
.readRecords(
ReadRecordsRequest(
SleepStageRecord::class,
timeRangeFilter =
TimeRangeFilter.between(sleepRecord.startTime, sleepRecord.endTime)
)
)
.records
}
}
| apache-2.0 | 2f7713780299337ed86cfc9e12e60b6c | 32.587156 | 95 | 0.638077 | 5.580793 | false | false | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/actions/SmileAction.kt | 1 | 1460 | package totoro.yui.actions
import totoro.yui.client.Command
import totoro.yui.client.IRCClient
import totoro.yui.util.Dict
class SmileAction : SensitivityAction("smile", "sweet", "sister", "sadistic", "surprise", "service") {
@Suppress("PrivatePropertyName")
private val MaxProgressStackSize = 10
private val progress: LinkedHashMap<String, Int> = linkedMapOf()
override fun handle(client: IRCClient, command: Command): Boolean {
val playerPlace = userProgress(command.user)
val wordPlace = wordNumber(command.name ?: "smile")
if (wordPlace - playerPlace == 1) {
client.send(command.chan, sensitivities[wordPlace + 1])
// update progress, or remove it, if the end was reached
val newPlace = progress[command.user]?.plus(2) ?: 1
if (newPlace >= sensitivities.size)
progress.remove(command.user)
else
progress[command.user] = newPlace
} else {
client.send(command.chan, Dict.NotSure())
progress[command.user] = -1
}
// trim extra progress records, in order to save memory
while (progress.size > MaxProgressStackSize) {
progress.remove(progress.keys.first())
}
return true
}
private fun userProgress(name: String): Int = progress[name] ?: -1
private fun wordNumber(word: String): Int = sensitivities.indexOfFirst { it == word }
}
| mit | 2033adb51f584720ebfdba8549f969d0 | 38.459459 | 102 | 0.637671 | 4.231884 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/actions/DocumentationViewExternalAction.kt | 5 | 1081 | // 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.lang.documentation.ide.actions
import com.intellij.codeInsight.hint.HintManagerImpl.ActionToIgnore
import com.intellij.lang.documentation.ide.impl.openUrl
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
internal class DocumentationViewExternalAction : AnAction(), ActionToIgnore {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = documentationBrowser(e.dataContext)?.currentExternalUrl() != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val browser = documentationBrowser(e.dataContext) ?: return
val url = browser.currentExternalUrl() ?: return
openUrl(project, browser.targetPointer, url)
}
}
| apache-2.0 | 835ecd9f183a9d6eab801046029c7d10 | 44.041667 | 158 | 0.79926 | 4.679654 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ChangeDiffPreviewLocationActions.kt | 6 | 1446 | // 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.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.vcs.log.impl.CommonUiProperties.SHOW_DIFF_PREVIEW
import com.intellij.vcs.log.impl.MainVcsLogUiProperties.DIFF_PREVIEW_VERTICAL_SPLIT
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
class MoveDiffPreviewToBottomAction : ChangeDiffPreviewLocationAction()
class MoveDiffPreviewToRightAction : ChangeDiffPreviewLocationAction() {
override fun isSelected(e: AnActionEvent): Boolean = !super.isSelected(e)
override fun setSelected(e: AnActionEvent, state: Boolean) = super.setSelected(e, !state)
}
abstract class ChangeDiffPreviewLocationAction : BooleanPropertyToggleAction() {
override fun update(e: AnActionEvent) {
super.update(e)
val properties = e.getData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES) ?: return
e.presentation.isEnabled = properties.exists(SHOW_DIFF_PREVIEW) && properties[SHOW_DIFF_PREVIEW]
}
override fun getProperty(): VcsLogUiProperties.VcsLogUiProperty<Boolean> = DIFF_PREVIEW_VERTICAL_SPLIT
}
class DiffPreviewLocationActionGroup : DefaultActionGroup() {
init {
templatePresentation.isHideGroupIfEmpty = true
}
} | apache-2.0 | 15e487e9b59878a0d20d0d8565dfa49a | 39.194444 | 140 | 0.807746 | 4.36858 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/TrustedProjects.kt | 1 | 7921 | // 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.
@file:JvmName("TrustedProjects")
@file:ApiStatus.Experimental
package com.intellij.ide.impl
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.TrustedCheckResult.NotTrusted
import com.intellij.ide.impl.TrustedCheckResult.Trusted
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.io.FileUtil.getLocationRelativeToUserHome
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SystemProperties
import com.intellij.util.ThreeState
import com.intellij.util.messages.Topic
import com.intellij.util.xmlb.annotations.Attribute
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.nio.file.Paths
fun confirmOpeningUntrustedProject(
virtualFile: VirtualFile,
projectTypeNames: List<String>,
): OpenUntrustedProjectChoice {
val systemsPresentation: String = StringUtil.naturalJoin(projectTypeNames)
return confirmOpeningUntrustedProject(
virtualFile,
IdeBundle.message("untrusted.project.open.dialog.title", systemsPresentation, projectTypeNames.size),
IdeBundle.message("untrusted.project.open.dialog.text", systemsPresentation, projectTypeNames.size),
IdeBundle.message("untrusted.project.dialog.trust.button"),
IdeBundle.message("untrusted.project.open.dialog.distrust.button"),
IdeBundle.message("untrusted.project.open.dialog.cancel.button")
)
}
fun confirmOpeningUntrustedProject(
virtualFile: VirtualFile,
@NlsContexts.DialogTitle title: String,
@NlsContexts.DialogMessage message: String,
@NlsContexts.Button trustButtonText: String,
@NlsContexts.Button distrustButtonText: String,
@NlsContexts.Button cancelButtonText: String
): OpenUntrustedProjectChoice = invokeAndWaitIfNeeded {
val projectDir = if (virtualFile.isDirectory) virtualFile else virtualFile.parent
val trustedCheckResult = getImplicitTrustedCheckResult(projectDir.toNioPath())
if (trustedCheckResult is Trusted) {
return@invokeAndWaitIfNeeded OpenUntrustedProjectChoice.IMPORT
}
val choice = MessageDialogBuilder.Message(title, message)
.buttons(trustButtonText, distrustButtonText, cancelButtonText)
.defaultButton(trustButtonText)
.focusedButton(distrustButtonText)
.doNotAsk(createDoNotAskOptionForLocation(projectDir.parent.path))
.asWarning()
.help(TRUSTED_PROJECTS_HELP_TOPIC)
.show()
val openChoice = when (choice) {
trustButtonText -> OpenUntrustedProjectChoice.IMPORT
distrustButtonText -> OpenUntrustedProjectChoice.OPEN_WITHOUT_IMPORTING
cancelButtonText, null -> OpenUntrustedProjectChoice.CANCEL
else -> {
LOG.error("Illegal choice $choice")
return@invokeAndWaitIfNeeded OpenUntrustedProjectChoice.CANCEL
}
}
TrustedProjectsStatistics.NEW_PROJECT_OPEN_OR_IMPORT_CHOICE.log(openChoice)
return@invokeAndWaitIfNeeded openChoice
}
fun confirmLoadingUntrustedProject(
project: Project,
@NlsContexts.DialogTitle title: String,
@NlsContexts.DialogMessage message: String,
@NlsContexts.Button trustButtonText: String,
@NlsContexts.Button distrustButtonText: String
): Boolean = invokeAndWaitIfNeeded {
val trustedCheckResult = getImplicitTrustedCheckResult(project)
if (trustedCheckResult is Trusted) {
project.setTrusted(true)
return@invokeAndWaitIfNeeded true
}
val answer = MessageDialogBuilder.yesNo(title, message)
.yesText(trustButtonText)
.noText(distrustButtonText)
.asWarning()
.help(TRUSTED_PROJECTS_HELP_TOPIC)
.ask(project)
project.setTrusted(answer)
TrustedProjectsStatistics.LOAD_UNTRUSTED_PROJECT_CONFIRMATION_CHOICE.log(project, answer)
return@invokeAndWaitIfNeeded answer
}
@ApiStatus.Experimental
enum class OpenUntrustedProjectChoice {
IMPORT,
OPEN_WITHOUT_IMPORTING,
CANCEL;
}
fun Project.isTrusted() = getTrustedState() == ThreeState.YES
fun Project.getTrustedState(): ThreeState {
val explicit = this.service<TrustedProjectSettings>().trustedState
if (explicit != ThreeState.UNSURE) return explicit
return if (getImplicitTrustedCheckResult(this) is Trusted) ThreeState.YES else ThreeState.UNSURE
}
fun Project.setTrusted(value: Boolean) {
val oldValue = this.service<TrustedProjectSettings>().trustedState
this.service<TrustedProjectSettings>().trustedState = ThreeState.fromBoolean(value)
if (value && oldValue != ThreeState.YES) {
ApplicationManager.getApplication().messageBus.syncPublisher(TrustChangeNotifier.TOPIC).projectTrusted(this)
}
}
fun createDoNotAskOptionForLocation(projectLocationPath: String): DialogWrapper.DoNotAskOption {
return object : DialogWrapper.DoNotAskOption.Adapter() {
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
if (isSelected && exitCode == Messages.YES) {
TrustedProjectsStatistics.TRUST_LOCATION_CHECKBOX_SELECTED.log()
service<TrustedPathsSettings>().addTrustedPath(projectLocationPath)
}
}
override fun getDoNotShowMessage(): String {
val path = getLocationRelativeToUserHome(projectLocationPath, false)
return IdeBundle.message("untrusted.project.warning.trust.location.checkbox", path)
}
}
}
fun isProjectImplicitlyTrusted(projectDir: Path?): Boolean {
return getImplicitTrustedCheckResult(projectDir) is Trusted
}
private fun isTrustedCheckDisabled() = ApplicationManager.getApplication().isUnitTestMode ||
ApplicationManager.getApplication().isHeadlessEnvironment ||
SystemProperties.`is`("idea.is.integration.test")
private sealed class TrustedCheckResult {
object Trusted : TrustedCheckResult()
class NotTrusted(val url: String?) : TrustedCheckResult()
}
private fun getImplicitTrustedCheckResult(project: Project): TrustedCheckResult =
getImplicitTrustedCheckResult(project.basePath?.let { Paths.get(it) }, project)
private fun getImplicitTrustedCheckResult(projectDir: Path?, project: Project? = null): TrustedCheckResult {
if (isTrustedCheckDisabled()) {
return Trusted
}
if (projectDir != null && service<TrustedPathsSettings>().isPathTrusted(projectDir)) {
TrustedProjectsStatistics.PROJECT_IMPLICITLY_TRUSTED_BY_PATH.log(project)
return Trusted
}
return NotTrusted(null)
}
@State(name = "Trusted.Project.Settings", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
@Service(Service.Level.PROJECT)
@ApiStatus.Internal
class TrustedProjectSettings : SimplePersistentStateComponent<TrustedProjectSettings.State>(State()) {
class State : BaseState() {
@get:Attribute
var isTrusted by enum(ThreeState.UNSURE)
@get:Attribute
var hasCheckedIfOldProject by property(false)
}
var trustedState: ThreeState
get() = if (isTrustedCheckDisabled()) ThreeState.YES else state.isTrusted
set(value) {
state.isTrusted = value
}
var hasCheckedIfOldProject: Boolean
get() = state.hasCheckedIfOldProject
set(value) {
state.hasCheckedIfOldProject = value
}
}
@ApiStatus.Experimental
fun interface TrustChangeNotifier {
fun projectTrusted(project: Project)
companion object {
@JvmField
@Topic.AppLevel
val TOPIC = Topic.create("Trusted project status", TrustChangeNotifier::class.java)
}
}
const val TRUSTED_PROJECTS_HELP_TOPIC = "Project_security"
private val LOG = Logger.getInstance("com.intellij.ide.impl.TrustedProjects")
| apache-2.0 | 1cf1c7652ca235c18b80980bd6ec4773 | 36.540284 | 140 | 0.781972 | 4.573326 | false | false | false | false |
stefanmedack/cccTV | app/src/test-common/java/de/stefanmedack/ccctv/ModelTestUtil.kt | 1 | 3017 | package de.stefanmedack.ccctv
import de.stefanmedack.ccctv.model.ConferenceGroup
import de.stefanmedack.ccctv.persistence.entities.Conference
import de.stefanmedack.ccctv.persistence.entities.Event
import de.stefanmedack.ccctv.persistence.entities.LanguageList
import info.metadude.kotlin.library.c3media.models.AspectRatio
import info.metadude.kotlin.library.c3media.models.Language
import info.metadude.kotlin.library.c3media.models.MimeType
import info.metadude.kotlin.library.c3media.models.Recording
import info.metadude.kotlin.library.c3media.models.RelatedEvent
import org.threeten.bp.LocalDate
import org.threeten.bp.OffsetDateTime
import info.metadude.kotlin.library.c3media.models.Conference as ConferenceRemote
import info.metadude.kotlin.library.c3media.models.Event as EventRemote
val minimalConferenceEntity = Conference(
acronym = "34c3",
url = "url",
slug = "slug",
group = ConferenceGroup.OTHER,
title = "title"
)
val fullConferenceEntity = Conference(
acronym = "34c3",
url = "url",
slug = "slug",
group = ConferenceGroup.OTHER,
title = "title",
aspectRatio = AspectRatio._16_X_9,
logoUrl = "logoUrl",
updatedAt = OffsetDateTime.now()
)
val minimalEventEntity = Event(
id = "43",
conferenceAcronym = "34c3",
url = "url",
slug = "slug",
title = "title"
)
val fullEventEntity = Event(
id = "43",
conferenceAcronym = "34c3",
url = "url",
slug = "slug",
title = "title",
subtitle = "subtitle",
description = "description",
persons = listOf("Frank", "Fefe"),
thumbUrl = "thumbUrl",
posterUrl = "posterUrl",
originalLanguage = LanguageList(listOf(Language.EN, Language.DE)),
duration = 3,
viewCount = 8,
promoted = true,
tags = listOf("33c3", "fnord"),
related = listOf(
RelatedEvent(0, "8", 15),
RelatedEvent(23, "42", 3)
),
releaseDate = LocalDate.now(),
date = OffsetDateTime.now(),
updatedAt = OffsetDateTime.now()
)
val minimalConference = ConferenceRemote(
url = "url/42",
slug = "slug",
title = "title",
acronym = "acronym"
)
val minimalEvent = EventRemote(
conferenceId = 42,
url = "url/43",
slug = "slug",
guid = "guid",
title = "title",
subtitle = "subtitle",
description = "desc",
thumbUrl = "thumbUrl",
posterUrl = "poserUrl",
releaseDate = LocalDate.now(),
originalLanguage = listOf()
)
val minimalRecording = Recording(
id = 44,
url = "url",
conferenceUrl = "conferenceUrl",
eventId = 43,
eventUrl = "eventUrl",
filename = "filename",
folder = "folder",
createdAt = "createdAt",
highQuality = true,
html5 = true,
mimeType = MimeType.MP4
)
| apache-2.0 | 2b7c3c955b96f8260d91e369265cec31 | 28.578431 | 81 | 0.611866 | 4.149931 | false | false | false | false |
nonylene/PhotoLinkViewer-Core | photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/fragment/LTEFragment.kt | 1 | 4388 | package net.nonylene.photolinkviewer.core.fragment
import android.app.Activity
import android.app.Dialog
import android.app.DialogFragment
import android.content.Intent
import android.os.Bundle
import android.preference.ListPreference
import android.support.v7.app.AlertDialog
import net.nonylene.photolinkviewer.core.R
import net.nonylene.photolinkviewer.core.dialog.BatchDialogFragment
class LTEFragment : PreferenceSummaryFragment() {
internal var listener: OnWifiSwitchListener? = null
// lister when switch changed
interface OnWifiSwitchListener {
fun onChanged(checked: Boolean)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.plv_core_quality_preference_3g)
// on click batch
findPreference("quality_3g_batch").setOnPreferenceClickListener {
// batch dialog
BatchDialogFragment().apply {
setTargetFragment(this@LTEFragment, 1)
show([email protected], "batch")
}
false
}
// on notes
findPreference("quality_note").setOnPreferenceClickListener{
NoteDialogFragment().apply {
show([email protected], "batch")
}
false
}
// on switch changed
findPreference("plv_core_is_wifi_enabled").setOnPreferenceChangeListener { preference, newValue ->
listener?.onChanged(newValue.toString().toBoolean())
true
}
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
listener = activity as OnWifiSwitchListener
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// batch dialog listener
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1 -> batchSelected(resultCode)
}
}
private fun batchSelected(resultCode: Int) {
// change preferences in a lump
val flickrPreference = findPreference("plv_core_flickr_quality_3g") as ListPreference
val twitterPreference = findPreference("plv_core_twitter_quality_3g") as ListPreference
val twipplePreference = findPreference("plv_core_twipple_quality_3g") as ListPreference
val imglyPreference = findPreference("plv_core_imgly_quality_3g") as ListPreference
val instagramPreference = findPreference("plv_core_instagram_quality_3g") as ListPreference
val nicoPreference = findPreference("plv_core_nicoseiga_quality_3g") as ListPreference
val tumblrPreference = findPreference("plv_core_tumblr_quality_3g") as ListPreference
when (resultCode) {
0 -> {
flickrPreference.value = "original"
twitterPreference.value = "original"
twipplePreference.value = "original"
imglyPreference.value = "full"
instagramPreference.value = "large"
nicoPreference.value = "original"
tumblrPreference.value = "original"
}
1 -> {
flickrPreference.value = "large"
twitterPreference.value = "large"
twipplePreference.value = "large"
imglyPreference.value = "large"
instagramPreference.value = "large"
nicoPreference.value = "large"
tumblrPreference.value = "large"
}
2 -> {
flickrPreference.value = "medium"
twitterPreference.value = "medium"
twipplePreference.value = "large"
imglyPreference.value = "medium"
instagramPreference.value = "medium"
nicoPreference.value = "medium"
tumblrPreference.value = "medium"
}
}
}
class NoteDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = AlertDialog.Builder(activity)
.setTitle(getString(R.string.plv_core_notes_dialog_title))
.setMessage(getString(R.string.plv_core_notes_about_quality))
.setPositiveButton(getString(android.R.string.ok), null)
.create()
}
}
| gpl-2.0 | cb1d846bc1c300f52c30854e17a3c17e | 39.256881 | 106 | 0.6299 | 5.03211 | false | false | false | false |
jwren/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 1 | 24332 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui
import com.intellij.diagnostic.LoadingState
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.NonInjectable
import com.intellij.ui.JreHiDpiUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.xmlb.annotations.Transient
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import org.jetbrains.annotations.NonNls
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
private val LOG = logger<UISettings>()
@State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], useLoadedStateAsExisting = false, category = SettingsCategory.UI)
class UISettings @NonInjectable constructor(private val notRoamableOptions: NotRoamableUiSettings) : PersistentStateComponentWithModificationTracker<UISettingsState> {
constructor() : this(ApplicationManager.getApplication().getService(NotRoamableUiSettings::class.java))
private var state = UISettingsState()
private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
var ideAAType: AntialiasingType
get() = notRoamableOptions.state.ideAAType
set(value) {
notRoamableOptions.state.ideAAType = value
}
var editorAAType: AntialiasingType
get() = notRoamableOptions.state.editorAAType
set(value) {
notRoamableOptions.state.editorAAType = value
}
val allowMergeButtons: Boolean
get() = Registry.`is`("ide.allow.merge.buttons", true)
val animateWindows: Boolean
get() = Registry.`is`("ide.animate.toolwindows", false)
var colorBlindness: ColorBlindness?
get() = state.colorBlindness
set(value) {
state.colorBlindness = value
}
var useContrastScrollbars: Boolean
get() = state.useContrastScrollBars
set(value) {
state.useContrastScrollBars = value
}
var hideToolStripes: Boolean
get() = state.hideToolStripes
set(value) {
state.hideToolStripes = value
}
val hideNavigationOnFocusLoss: Boolean
get() = Registry.`is`("ide.hide.navigation.on.focus.loss", false)
var reuseNotModifiedTabs: Boolean
get() = state.reuseNotModifiedTabs
set(value) {
state.reuseNotModifiedTabs = value
}
var openTabsInMainWindow: Boolean
get() = state.openTabsInMainWindow
set(value) {
state.openTabsInMainWindow = value
}
var openInPreviewTabIfPossible: Boolean
get() = state.openInPreviewTabIfPossible
set(value) {
state.openInPreviewTabIfPossible = value
}
var disableMnemonics: Boolean
get() = state.disableMnemonics
set(value) {
state.disableMnemonics = value
}
var disableMnemonicsInControls: Boolean
get() = state.disableMnemonicsInControls
set(value) {
state.disableMnemonicsInControls = value
}
var dndWithPressedAltOnly: Boolean
get() = state.dndWithPressedAltOnly
set(value) {
state.dndWithPressedAltOnly = value
}
var separateMainMenu: Boolean
get() = SystemInfoRt.isWindows && state.separateMainMenu
set(value) {
state.separateMainMenu = value
state.showMainToolbar = value
}
var useSmallLabelsOnTabs: Boolean
get() = state.useSmallLabelsOnTabs
set(value) {
state.useSmallLabelsOnTabs = value
}
var smoothScrolling: Boolean
get() = state.smoothScrolling
set(value) {
state.smoothScrolling = value
}
val animatedScrolling: Boolean
get() = state.animatedScrolling
val animatedScrollingDuration: Int
get() = state.animatedScrollingDuration
val animatedScrollingCurvePoints: Int
get() = state.animatedScrollingCurvePoints
val closeTabButtonOnTheRight: Boolean
get() = state.closeTabButtonOnTheRight
val cycleScrolling: Boolean
get() = AdvancedSettings.getBoolean("ide.cycle.scrolling")
var selectedTabsLayoutInfoId: @NonNls String?
get() = state.selectedTabsLayoutInfoId
set(value) {
state.selectedTabsLayoutInfoId = value
}
val scrollTabLayoutInEditor: Boolean
get() = state.scrollTabLayoutInEditor
var showToolWindowsNumbers: Boolean
get() = state.showToolWindowsNumbers
set(value) {
state.showToolWindowsNumbers = value
}
var showEditorToolTip: Boolean
get() = state.showEditorToolTip
set(value) {
state.showEditorToolTip = value
}
var showNavigationBar: Boolean
get() = state.showNavigationBar
set(value) {
state.showNavigationBar = value
}
var navBarLocation : NavBarLocation
get() = state.navigationBarLocation
set(value) {
state.navigationBarLocation = value
}
var showMembersInNavigationBar: Boolean
get() = state.showMembersInNavigationBar
set(value) {
state.showMembersInNavigationBar = value
}
var showStatusBar: Boolean
get() = state.showStatusBar
set(value) {
state.showStatusBar = value
}
var showMainMenu: Boolean
get() = state.showMainMenu
set(value) {
state.showMainMenu = value
}
val showIconInQuickNavigation: Boolean
get() = Registry.`is`("ide.show.icons.in.quick.navigation", false)
var showTreeIndentGuides: Boolean
get() = state.showTreeIndentGuides
set(value) {
state.showTreeIndentGuides = value
}
var compactTreeIndents: Boolean
get() = state.compactTreeIndents
set(value) {
state.compactTreeIndents = value
}
var showMainToolbar: Boolean
get() = state.showMainToolbar
set(value) {
state.showMainToolbar = value
val toolbarSettingsState = ToolbarSettings.getInstance().state!!
toolbarSettingsState.showNewMainToolbar = !value && toolbarSettingsState.showNewMainToolbar
}
var showIconsInMenus: Boolean
get() = state.showIconsInMenus
set(value) {
state.showIconsInMenus = value
}
var sortLookupElementsLexicographically: Boolean
get() = state.sortLookupElementsLexicographically
set(value) {
state.sortLookupElementsLexicographically = value
}
val hideTabsIfNeeded: Boolean
get() = state.hideTabsIfNeeded || editorTabPlacement == SwingConstants.LEFT || editorTabPlacement == SwingConstants.RIGHT
var showFileIconInTabs: Boolean
get() = state.showFileIconInTabs
set(value) {
state.showFileIconInTabs = value
}
var hideKnownExtensionInTabs: Boolean
get() = state.hideKnownExtensionInTabs
set(value) {
state.hideKnownExtensionInTabs = value
}
var leftHorizontalSplit: Boolean
get() = state.leftHorizontalSplit
set(value) {
state.leftHorizontalSplit = value
}
var rightHorizontalSplit: Boolean
get() = state.rightHorizontalSplit
set(value) {
state.rightHorizontalSplit = value
}
var wideScreenSupport: Boolean
get() = state.wideScreenSupport
set(value) {
state.wideScreenSupport = value
}
var sortBookmarks: Boolean
get() = state.sortBookmarks
set(value) {
state.sortBookmarks = value
}
val showCloseButton: Boolean
get() = state.showCloseButton
var presentationMode: Boolean
get() = state.presentationMode
set(value) {
state.presentationMode = value
}
var presentationModeFontSize: Int
get() = state.presentationModeFontSize
set(value) {
state.presentationModeFontSize = value
}
var editorTabPlacement: Int
get() = state.editorTabPlacement
set(value) {
state.editorTabPlacement = value
}
var editorTabLimit: Int
get() = state.editorTabLimit
set(value) {
state.editorTabLimit = value
}
var recentFilesLimit: Int
get() = state.recentFilesLimit
set(value) {
state.recentFilesLimit = value
}
var recentLocationsLimit: Int
get() = state.recentLocationsLimit
set(value) {
state.recentLocationsLimit = value
}
var maxLookupWidth: Int
get() = state.maxLookupWidth
set(value) {
state.maxLookupWidth = value
}
var maxLookupListHeight: Int
get() = state.maxLookupListHeight
set(value) {
state.maxLookupListHeight = value
}
var overrideLafFonts: Boolean
get() = state.overrideLafFonts
set(value) {
state.overrideLafFonts = value
}
var fontFace: @NlsSafe String?
get() = notRoamableOptions.state.fontFace
set(value) {
notRoamableOptions.state.fontFace = value
}
var fontSize: Int
get() = (notRoamableOptions.state.fontSize + 0.5).toInt()
set(value) {
notRoamableOptions.state.fontSize = value.toFloat()
}
var fontSize2D: Float
get() = notRoamableOptions.state.fontSize
set(value) {
notRoamableOptions.state.fontSize = value
}
var fontScale: Float
get() = notRoamableOptions.state.fontScale
set(value) {
notRoamableOptions.state.fontScale = value
}
var showDirectoryForNonUniqueFilenames: Boolean
get() = state.showDirectoryForNonUniqueFilenames
set(value) {
state.showDirectoryForNonUniqueFilenames = value
}
var pinFindInPath: Boolean
get() = state.pinFindInPath
set(value) {
state.pinFindInPath = value
}
var activeRightEditorOnClose: Boolean
get() = state.activeRightEditorOnClose
set(value) {
state.activeRightEditorOnClose = value
}
var showTabsTooltips: Boolean
get() = state.showTabsTooltips
set(value) {
state.showTabsTooltips = value
}
var markModifiedTabsWithAsterisk: Boolean
get() = state.markModifiedTabsWithAsterisk
set(value) {
state.markModifiedTabsWithAsterisk = value
}
@Suppress("unused")
var overrideConsoleCycleBufferSize: Boolean
get() = state.overrideConsoleCycleBufferSize
set(value) {
state.overrideConsoleCycleBufferSize = value
}
var consoleCycleBufferSizeKb: Int
get() = state.consoleCycleBufferSizeKb
set(value) {
state.consoleCycleBufferSizeKb = value
}
var consoleCommandHistoryLimit: Int
get() = state.consoleCommandHistoryLimit
set(value) {
state.consoleCommandHistoryLimit = value
}
var sortTabsAlphabetically: Boolean
get() = state.sortTabsAlphabetically
set(value) {
state.sortTabsAlphabetically = value
}
var alwaysKeepTabsAlphabeticallySorted: Boolean
get() = state.alwaysKeepTabsAlphabeticallySorted
set(value) {
state.alwaysKeepTabsAlphabeticallySorted = value
}
var openTabsAtTheEnd: Boolean
get() = state.openTabsAtTheEnd
set(value) {
state.openTabsAtTheEnd = value
}
var showInplaceComments: Boolean
get() = state.showInplaceComments
set(value) {
state.showInplaceComments = value
}
val showInplaceCommentsInternal: Boolean
get() = showInplaceComments && ApplicationManager.getApplication()?.isInternal ?: false
var fullPathsInWindowHeader: Boolean
get() = state.fullPathsInWindowHeader
set(value) {
state.fullPathsInWindowHeader = value
}
var mergeMainMenuWithWindowTitle: Boolean
get() = state.mergeMainMenuWithWindowTitle
set(value) {
state.mergeMainMenuWithWindowTitle = value
}
var showVisualFormattingLayer: Boolean
get() = state.showVisualFormattingLayer
set(value) {
state.showVisualFormattingLayer = value
}
companion object {
init {
if (JBUIScale.SCALE_VERBOSE) {
LOG.info(String.format("defFontSize=%.1f, defFontScale=%.2f", defFontSize, defFontScale))
}
}
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
@Suppress("ObjectPropertyName")
@Volatile
private var cachedInstance: UISettings? = null
@JvmStatic
fun getInstance(): UISettings {
var result = cachedInstance
if (result == null) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
result = ApplicationManager.getApplication().getService(UISettings::class.java)!!
cachedInstance = result
}
return result
}
@JvmStatic
val instanceOrNull: UISettings?
get() {
val result = cachedInstance
if (result == null && LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred) {
return getInstance()
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() = instanceOrNull ?: UISettings(NotRoamableUiSettings())
private fun calcFractionalMetricsHint(registryKey: String, defaultValue: Boolean): Any {
val hint: Boolean
if (LoadingState.APP_STARTED.isOccurred) {
val registryValue = Registry.get(registryKey)
if (registryValue.isMultiValue) {
val option = registryValue.selectedOption
if (option.equals("Enabled")) hint = true
else if (option.equals("Disabled")) hint = false
else hint = defaultValue
}
else {
hint = if (registryValue.isBoolean && registryValue.asBoolean()) true else defaultValue
}
}
else hint = defaultValue
return if (hint) RenderingHints.VALUE_FRACTIONALMETRICS_ON else RenderingHints.VALUE_FRACTIONALMETRICS_OFF
}
fun getPreferredFractionalMetricsValue(): Any {
val enableByDefault = SystemInfo.isMacOSCatalina || (FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(false) ==
RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
return calcFractionalMetricsHint("ide.text.fractional.metrics", enableByDefault)
}
@JvmStatic
val editorFractionalMetricsHint: Any
get() {
val enableByDefault = FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(true) == RenderingHints.VALUE_TEXT_ANTIALIAS_ON
return calcFractionalMetricsHint("editor.text.fractional.metrics", enableByDefault)
}
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, getPreferredFractionalMetricsValue())
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
g as Graphics2D
g.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
if (LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred && ApplicationManager.getApplication() == null) {
// cannot use services while Application has not been loaded yet, so let's apply the default hints
GraphicsUtil.applyRenderingHints(g)
return
}
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
setupFractionalMetrics(g)
}
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, getInstance().editorAAType.textInfo)
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see [com.intellij.ui.scale.ScaleType]).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = when {
JreHiDpiUtil.isJreHiDPIEnabled() -> 1f
else -> JBUIScale.sysScale()
}
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Float
get() = UISettingsState.defFontSize
@Deprecated("Use {@link #restoreFontSize(Float, Float?)} instead")
@JvmStatic
fun restoreFontSize(readSize: Int, readScale: Float?): Int {
return restoreFontSize(readSize.toFloat(), readScale).toInt();
}
@JvmStatic
fun restoreFontSize(readSize: Float, readScale: Float?): Float {
var size = readSize
if (readScale == null || readScale <= 0) {
if (JBUIScale.SCALE_VERBOSE) LOG.info("Reset font to default")
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (!SystemInfoRt.isMac && JreHiDpiUtil.isJreHiDPIEnabled()) {
size = UISettingsState.defFontSize
}
}
else if (readScale != defFontScale) {
size = (readSize / readScale) * defFontScale
}
if (JBUIScale.SCALE_VERBOSE) LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
const val MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY = "ide.win.frame.decoration"
@JvmStatic
val mergeMainMenuWithWindowTitleOverrideValue = System.getProperty(MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY)?.toBoolean()
val isMergeMainMenuWithWindowTitleOverridden = mergeMainMenuWithWindowTitleOverrideValue != null
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
@ScheduledForRemoval
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
state._incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === cachedInstance) {
myTreeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
HIDE_TOOL_STRIPES = hideToolStripes
SHOW_MAIN_TOOLBAR = showMainToolbar
SHOW_CLOSE_BUTTON = showCloseButton
PRESENTATION_MODE = presentationMode
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize
CONSOLE_COMMAND_HISTORY_LIMIT = state.consoleCommandHistoryLimit
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
}
override fun getState() = state
override fun loadState(state: UISettingsState) {
this.state = state
updateDeprecatedProperties()
migrateOldSettings()
if (migrateOldFontSettings()) {
notRoamableOptions.fixFontSettings()
}
// Check tab placement in editor
val editorTabPlacement = state.editorTabPlacement
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
state.editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (state.alphaModeDelay < 0) {
state.alphaModeDelay = 1500
}
if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) {
state.alphaModeRatio = 0.5f
}
fireUISettingsChanged()
}
override fun getStateModificationCount(): Long {
return state.modificationCount
}
@Suppress("DEPRECATION")
private fun migrateOldSettings() {
if (state.ideAAType != AntialiasingType.SUBPIXEL) {
ideAAType = state.ideAAType
state.ideAAType = AntialiasingType.SUBPIXEL
}
if (state.editorAAType != AntialiasingType.SUBPIXEL) {
editorAAType = state.editorAAType
state.editorAAType = AntialiasingType.SUBPIXEL
}
if (!state.allowMergeButtons) {
Registry.get("ide.allow.merge.buttons").setValue(false)
state.allowMergeButtons = true
}
}
@Suppress("DEPRECATION")
private fun migrateOldFontSettings(): Boolean {
var migrated = false
if (state.fontSize != 0) {
fontSize2D = restoreFontSize(state.fontSize.toFloat(), state.fontScale)
state.fontSize = 0
migrated = true
}
if (state.fontScale != 0f) {
fontScale = state.fontScale
state.fontScale = 0f
migrated = true
}
if (state.fontFace != null) {
fontFace = state.fontFace
state.fontFace = null
migrated = true
}
return migrated
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("unused", "PropertyName")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
var FONT_FACE: String? = null
@Suppress("unused", "PropertyName")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
var FONT_SIZE: Int? = 0
@Suppress("unused", "PropertyName")
@Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes"))
@JvmField
@Transient
var HIDE_TOOL_STRIPES = true
@Suppress("unused", "PropertyName")
@Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit"))
@JvmField
@Transient
var CONSOLE_COMMAND_HISTORY_LIMIT = 300
@Suppress("unused", "PropertyName")
@Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"), level = DeprecationLevel.ERROR)
@JvmField
@Transient
var CYCLE_SCROLLING = true
@Suppress("unused", "PropertyName")
@Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar"))
@JvmField
@Transient
var SHOW_MAIN_TOOLBAR = false
@Suppress("unused", "PropertyName")
@Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton"))
@JvmField
@Transient
var SHOW_CLOSE_BUTTON = true
@Suppress("unused", "PropertyName")
@Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode"))
@JvmField
@Transient
var PRESENTATION_MODE = false
@Suppress("unused", "PropertyName", "SpellCheckingInspection")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("unused", "PropertyName")
@Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize"))
@JvmField
@Transient
var PRESENTATION_MODE_FONT_SIZE = 24
@Suppress("unused", "PropertyName")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
var EDITOR_TAB_LIMIT = editorTabLimit
//</editor-fold>
}
| apache-2.0 | 3f5d5a3c6522d590c2a5229876a619a5 | 29.453066 | 167 | 0.707874 | 4.935497 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/host/distros/XenServer7.kt | 2 | 462 | package com.github.kerubistan.kerub.host.distros
import com.github.kerubistan.kerub.host.packman.YumPackageManager
import com.github.kerubistan.kerub.model.Version
import org.apache.sshd.client.session.ClientSession
class XenServer7 : LsbDistribution("XenServer") {
override fun handlesVersion(version: Version) = version.major == "7"
override fun getPackageManager(session: ClientSession) = YumPackageManager(session)
override fun name() = "XenServer"
} | apache-2.0 | b15d8ff56d7e4e0ac7932e33593700df | 32.071429 | 84 | 0.809524 | 3.666667 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/operations/AlCtl_FuckAroundWithXorg.kt | 1 | 2104 | package alraune.operations
//import alraune.*
//import com.sun.jna.platform.unix.X11
//import sun.awt.X11.XBaseWindow
//import sun.awt.X11.XKeySymConstants
//import vgrechka.*
//import kotlin.concurrent.thread
//class AlCtl_FuckAroundWithXorg : AlCtlCommand() {
//
// override fun dance() {
// }
//
// fun fuckAroundXFocus() {
// thread {
// while (true) {
// Thread.sleep(1000)
// val win = X11.Window(XBaseWindow.xGetInputFocus())
// clog(String.format("focus = %d (0x%x)", win, win))
//
// }
// }
// }
//
// fun typeSomeShit() {
// thread {
// clog("Sending shit")
// Thread.sleep(500)
// X11Pile.typeKeysym(XKeySymConstants.XK_a)
// X11Pile.typeKeysym(XKeySymConstants.XK_B)
// X11Pile.typeKeysym(XKeySymConstants.XK_c)
// }
//
// }
//
// fun fuckXmodmap() {
// runProcess_bitchIfBadExit("xmodmap",
// "-e", "clear Mod3",
// "-e", "remove Mod1 = Alt_R",
// "-e", "add Mod3 = Alt_R")
//
// val out = runProcess_grabStdout__ifBadExit_printOutputAndBitch("xmodmap")
//
// fun bitchUnexpectedOutput(msg: String): Nothing {
// clogTitleUnderlined("UNEXPECTED XMODMAP OUTPUT")
// clog(out)
// bitch(msg)
// }
//
// fun checkLine(lineStart: String, shouldContainAltR: Boolean) {
// val line = out.lines().find {it.startsWith("$lineStart ")} ?: bitchUnexpectedOutput("I want a $lineStart line")
// val altr = " Alt_R "
// val contains = line.contains(altr)
// if (shouldContainAltR && !contains)
// bitchUnexpectedOutput("$lineStart line should contain `$altr`")
// if (!shouldContainAltR && contains)
// bitchUnexpectedOutput("$lineStart line should not contain `$altr`")
// }
//
// checkLine("mod1", shouldContainAltR = false)
// checkLine("mod3", shouldContainAltR = true)
// clog("Fucked xmodmap: OK")
// }
//}
| apache-2.0 | 61bbfd3465d1d5588095b6c04cbdde12 | 29.941176 | 125 | 0.54943 | 3.454844 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameModToRemFix.kt | 4 | 2000 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.refactoring.rename.RenameProcessor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.types.expressions.OperatorConventions.REM_TO_MOD_OPERATION_NAMES
class RenameModToRemFix(element: KtNamedFunction, val newName: Name) : KotlinQuickFixAction<KtNamedFunction>(element) {
override fun getText(): String = KotlinBundle.message("rename.to.0", newName)
override fun getFamilyName(): String = text
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
RenameProcessor(project, element ?: return, newName.asString(), false, false).run()
}
companion object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory != Errors.DEPRECATED_BINARY_MOD && diagnostic.factory != Errors.FORBIDDEN_BINARY_MOD) return null
val operatorMod = diagnostic.psiElement.getNonStrictParentOfType<KtNamedFunction>() ?: return null
val newName = operatorMod.nameAsName?.let { REM_TO_MOD_OPERATION_NAMES.inverse()[it] } ?: return null
return RenameModToRemFix(operatorMod, newName)
}
}
} | apache-2.0 | abba5a358185b14765f4ca8b5d8f0f57 | 50.307692 | 158 | 0.7785 | 4.597701 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/AbstractCommitWorkflow.kt | 1 | 17025 | // 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 com.intellij.vcs.commit
import com.intellij.CommonBundle.getCancelButtonText
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.EDT
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages.*
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ChangesUtil.getAffectedVcses
import com.intellij.openapi.vcs.checkin.*
import com.intellij.openapi.vcs.impl.CheckinHandlersManager
import com.intellij.openapi.vcs.impl.PartialChangesUtil
import com.intellij.openapi.vcs.impl.PartialChangesUtil.getPartialTracker
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.containers.ContainerUtil.newUnmodifiableList
import com.intellij.util.containers.ContainerUtil.unmodifiableOrEmptySet
import com.intellij.util.ui.EDT
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.*
import org.jetbrains.annotations.Nls
import java.util.*
import kotlin.coroutines.coroutineContext
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private val LOG = logger<AbstractCommitWorkflow>()
@Nls
internal fun String.removeEllipsisSuffix() = StringUtil.removeEllipsisSuffix(this)
internal fun cleanActionText(text: @Nls String): @Nls String = UIUtil.removeMnemonic(text).removeEllipsisSuffix()
fun CommitOptions.saveState() = allOptions.forEach { it.saveState() }
fun CommitOptions.restoreState() = allOptions.forEach { it.restoreState() }
private class CommitProperty<T>(private val key: Key<T>, private val defaultValue: T) : ReadWriteProperty<CommitContext, T> {
override fun getValue(thisRef: CommitContext, property: KProperty<*>): T = thisRef.getUserData(key) ?: defaultValue
override fun setValue(thisRef: CommitContext, property: KProperty<*>, value: T) = thisRef.putUserData(key, value)
}
fun commitProperty(key: Key<Boolean>): ReadWriteProperty<CommitContext, Boolean> = commitProperty(key, false)
fun <T> commitProperty(key: Key<T>, defaultValue: T): ReadWriteProperty<CommitContext, T> = CommitProperty(key, defaultValue)
val CommitInfo.isPostCommitCheck: Boolean get() = this is PostCommitInfo
private val IS_AMEND_COMMIT_MODE_KEY = Key.create<Boolean>("Vcs.Commit.IsAmendCommitMode")
var CommitContext.isAmendCommitMode: Boolean by commitProperty(IS_AMEND_COMMIT_MODE_KEY)
private val IS_CLEANUP_COMMIT_MESSAGE_KEY = Key.create<Boolean>("Vcs.Commit.IsCleanupCommitMessage")
var CommitContext.isCleanupCommitMessage: Boolean by commitProperty(IS_CLEANUP_COMMIT_MESSAGE_KEY)
interface CommitWorkflowListener : EventListener {
fun vcsesChanged() = Unit
fun executionStarted() = Unit
fun executionEnded() = Unit
fun beforeCommitChecksStarted(sessionInfo: CommitSessionInfo) = Unit
fun beforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) = Unit
}
abstract class AbstractCommitWorkflow(val project: Project) {
private val eventDispatcher = EventDispatcher.create(CommitWorkflowListener::class.java)
private val commitEventDispatcher = EventDispatcher.create(CommitterResultHandler::class.java)
private val commitCustomEventDispatcher = EventDispatcher.create(CommitterResultHandler::class.java)
var isExecuting = false
private set
var commitContext: CommitContext = CommitContext()
private set
abstract val isDefaultCommitEnabled: Boolean
private val _vcses = mutableSetOf<AbstractVcs>()
val vcses: Set<AbstractVcs> get() = unmodifiableOrEmptySet(_vcses.toSet())
private val _commitExecutors = mutableListOf<CommitExecutor>()
val commitExecutors: List<CommitExecutor> get() = newUnmodifiableList(_commitExecutors)
private val _commitHandlers = mutableListOf<CheckinHandler>()
val commitHandlers: List<CheckinHandler> get() = newUnmodifiableList(_commitHandlers)
private val _commitOptions = MutableCommitOptions()
val commitOptions: CommitOptions get() = _commitOptions.toUnmodifiableOptions()
protected fun updateVcses(vcses: Set<AbstractVcs>) {
if (_vcses != vcses) {
_vcses.clear()
_vcses += vcses
eventDispatcher.multicaster.vcsesChanged()
}
}
internal fun initCommitExecutors(executors: List<CommitExecutor>) {
_commitExecutors.clear()
_commitExecutors += executors
}
internal fun initCommitHandlers(handlers: List<CheckinHandler>) {
_commitHandlers.clear()
_commitHandlers += handlers
}
internal fun disposeCommitOptions() {
_commitOptions.allOptions.filterIsInstance<Disposable>().forEach { Disposer.dispose(it) }
_commitOptions.clear()
}
internal fun initCommitOptions(options: CommitOptions) {
disposeCommitOptions()
_commitOptions.add(options)
}
internal fun clearCommitContext() {
commitContext = CommitContext()
}
@RequiresEdt
internal fun startExecution(block: () -> Boolean) {
check(!isExecuting) { "Commit session is already started" }
isExecuting = true
continueExecution {
eventDispatcher.multicaster.executionStarted()
block()
}
}
internal fun continueExecution(block: () -> Boolean) {
check(isExecuting) { "Commit session has already finished" }
try {
val continueExecution = block()
if (!continueExecution) endExecution()
}
catch (e: ProcessCanceledException) {
endExecution()
}
catch (e: CancellationException) {
endExecution()
}
catch (e: Throwable) {
endExecution()
LOG.error(e)
}
}
@RequiresEdt
internal fun endExecution() {
check(isExecuting) { "Commit session has already finished" }
isExecuting = false
eventDispatcher.multicaster.executionEnded()
}
fun addListener(listener: CommitWorkflowListener, parent: Disposable) =
eventDispatcher.addListener(listener, parent)
fun addVcsCommitListener(listener: CommitterResultHandler, parent: Disposable) =
commitEventDispatcher.addListener(listener, parent)
fun addCommitCustomListener(listener: CommitterResultHandler, parent: Disposable) =
commitCustomEventDispatcher.addListener(listener, parent)
fun executeSession(sessionInfo: CommitSessionInfo, commitInfo: DynamicCommitInfo): Boolean {
return runBlockingModal(project, message("commit.checks.on.commit.progress.text")) {
withContext(Dispatchers.EDT) {
fireBeforeCommitChecksStarted(sessionInfo)
val result = runModalBeforeCommitChecks(commitInfo)
fireBeforeCommitChecksEnded(sessionInfo, result)
if (result.shouldCommit) {
performCommit(sessionInfo)
return@withContext true
}
else {
return@withContext false
}
}
}
}
protected abstract fun performCommit(sessionInfo: CommitSessionInfo)
protected open fun addCommonResultHandlers(sessionInfo: CommitSessionInfo, committer: Committer) {
committer.addResultHandler(CheckinHandlersNotifier(committer, commitHandlers))
if (sessionInfo.isVcsCommit) {
committer.addResultHandler(commitEventDispatcher.multicaster)
}
else {
committer.addResultHandler(commitCustomEventDispatcher.multicaster)
}
committer.addResultHandler(EndExecutionCommitResultHandler(this))
}
protected fun fireBeforeCommitChecksStarted(sessionInfo: CommitSessionInfo) =
eventDispatcher.multicaster.beforeCommitChecksStarted(sessionInfo)
protected fun fireBeforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) =
eventDispatcher.multicaster.beforeCommitChecksEnded(sessionInfo, result)
suspend fun <T> runModificationCommitChecks(modifications: suspend () -> T): T {
return PartialChangesUtil.underChangeList(project, getBeforeCommitChecksChangelist(), modifications)
}
private suspend fun runModalBeforeCommitChecks(commitInfo: DynamicCommitInfo): CommitChecksResult {
return runModificationCommitChecks {
runCommitHandlers(commitInfo)
}
}
private suspend fun runCommitHandlers(commitInfo: DynamicCommitInfo): CommitChecksResult {
try {
val handlers = commitHandlers
val commitChecks = handlers
.map { it.asCommitCheck(commitInfo) }
.filter { it.isEnabled() }
.groupBy { it.getExecutionOrder() }
if (!checkDumbMode(commitInfo, commitChecks.values.flatten())) {
return CommitChecksResult.Cancelled
}
runModalCommitChecks(commitInfo, commitChecks[CommitCheck.ExecutionOrder.EARLY])?.let { return it }
@Suppress("DEPRECATION") val metaHandlers = handlers.filterIsInstance<CheckinMetaHandler>()
runMetaHandlers(metaHandlers)
runModalCommitChecks(commitInfo, commitChecks[CommitCheck.ExecutionOrder.MODIFICATION])?.let { return it }
FileDocumentManager.getInstance().saveAllDocuments()
runModalCommitChecks(commitInfo, commitChecks[CommitCheck.ExecutionOrder.LATE])?.let { return it }
runModalCommitChecks(commitInfo, commitChecks[CommitCheck.ExecutionOrder.POST_COMMIT])?.let { return it }
return CommitChecksResult.Passed
}
catch (e: CancellationException) {
return CommitChecksResult.Cancelled
}
catch (e: Throwable) {
LOG.warn(Throwable(e))
return CommitChecksResult.ExecutionError
}
}
private fun checkDumbMode(commitInfo: DynamicCommitInfo,
commitChecks: List<CommitCheck>): Boolean {
if (!DumbService.isDumb(project)) return true
if (commitChecks.none { commitCheck -> commitCheck.isEnabled() && !DumbService.isDumbAware(commitCheck) }) return true
return !MessageDialogBuilder.yesNo(message("commit.checks.error.indexing"),
message("commit.checks.error.indexing.message", ApplicationNamesInfo.getInstance().productName))
.yesText(message("checkin.wait"))
.noText(commitInfo.commitActionText)
.ask(project)
}
private suspend fun runModalCommitChecks(commitInfo: DynamicCommitInfo,
commitChecks: List<CommitCheck>?): CommitChecksResult? {
for (commitCheck in commitChecks.orEmpty()) {
try {
val problem = runCommitCheck(project, commitCheck, commitInfo)
if (problem == null) continue
val result = blockingContext {
problem.showModalSolution(project, commitInfo)
}
return when (result) {
CheckinHandler.ReturnResult.COMMIT -> continue
CheckinHandler.ReturnResult.CANCEL -> CommitChecksResult.Failed()
CheckinHandler.ReturnResult.CLOSE_WINDOW -> CommitChecksResult.Failed(toCloseWindow = true)
}
}
catch (e: CancellationException) {
LOG.debug("CheckinHandler cancelled $commitCheck")
throw e
}
}
return null // check passed
}
protected open fun getBeforeCommitChecksChangelist(): LocalChangeList? = null
open fun canExecute(sessionInfo: CommitSessionInfo, changes: Collection<Change>): Boolean {
val executor = sessionInfo.executor
if (executor != null && !executor.supportsPartialCommit()) {
val hasPartialChanges = changes.any { getPartialTracker(project, it)?.hasPartialChangesToCommit() ?: false }
if (hasPartialChanges) {
return YES == showYesNoDialog(
project, message("commit.dialog.partial.commit.warning.body", cleanActionText(executor.actionText)),
message("commit.dialog.partial.commit.warning.title"), executor.actionText, getCancelButtonText(),
getWarningIcon())
}
}
return true
}
companion object {
@JvmStatic
fun getCommitHandlerFactories(vcses: Collection<AbstractVcs>): List<BaseCheckinHandlerFactory> =
CheckinHandlersManager.getInstance().getRegisteredCheckinHandlerFactories(vcses.toTypedArray())
@JvmStatic
fun getCommitHandlers(
vcses: Collection<AbstractVcs>,
commitPanel: CheckinProjectPanel,
commitContext: CommitContext
): List<CheckinHandler> =
getCommitHandlerFactories(vcses)
.map { it.createHandler(commitPanel, commitContext) }
.filter { it != CheckinHandler.DUMMY }
@JvmStatic
fun getCommitExecutors(project: Project, changes: Collection<Change>): List<CommitExecutor> =
getCommitExecutors(project, getAffectedVcses(changes, project))
internal fun getCommitExecutors(project: Project, vcses: Collection<AbstractVcs>): List<CommitExecutor> {
return vcses.flatMap { it.commitExecutors } +
ChangeListManager.getInstance(project).registeredExecutors +
LocalCommitExecutor.LOCAL_COMMIT_EXECUTOR.getExtensions(project)
}
suspend fun runMetaHandlers(@Suppress("DEPRECATION") metaHandlers: List<CheckinMetaHandler>) {
EDT.assertIsEdt()
// reversed to have the same order as when wrapping meta handlers into each other
for (metaHandler in metaHandlers.reversed()) {
suspendCancellableCoroutine { continuation ->
try {
withCurrentJob(continuation.context.job) {
LOG.debug("CheckinMetaHandler.runCheckinHandlers: $metaHandler")
metaHandler.runCheckinHandlers {
continuation.resume(Unit)
}
}
}
catch (e: CancellationException) {
LOG.debug("CheckinMetaHandler cancelled $metaHandler")
continuation.resumeWithException(e)
}
catch (e: Throwable) {
LOG.debug("CheckinMetaHandler failed $metaHandler")
continuation.resumeWithException(e)
}
}
}
}
suspend fun runCommitCheck(project: Project, commitCheck: CommitCheck, commitInfo: CommitInfo): CommitProblem? {
if (DumbService.isDumb(project) && !DumbService.isDumbAware(commitCheck)) {
LOG.debug("Skipped commit check in dumb mode $commitCheck")
return null
}
LOG.debug("Running commit check $commitCheck")
val ctx = coroutineContext
ctx.ensureActive()
ctx.progressSink?.update(text = "", details = "")
return commitCheck.runCheck(commitInfo)
}
}
}
private class EndExecutionCommitResultHandler(private val workflow: AbstractCommitWorkflow) : CommitterResultHandler {
override fun onAfterRefresh() {
workflow.endExecution()
}
}
sealed class CommitSessionInfo {
val isVcsCommit: Boolean get() = session === CommitSession.VCS_COMMIT
abstract val executor: CommitExecutor?
abstract val session: CommitSession
object Default : CommitSessionInfo() {
override val executor: CommitExecutor? get() = null
override val session: CommitSession get() = CommitSession.VCS_COMMIT
}
class Custom(override val executor: CommitExecutor,
override val session: CommitSession) : CommitSessionInfo()
}
internal fun CheckinHandler.asCommitCheck(commitInfo: CommitInfo): CommitCheck {
if (this is CommitCheck) return this
return ProxyCommitCheck(this, commitInfo.executor)
}
private class ProxyCommitCheck(private val checkinHandler: CheckinHandler,
private val executor: CommitExecutor?) : CommitCheck {
override fun getExecutionOrder(): CommitCheck.ExecutionOrder {
if (checkinHandler is CheckinModificationHandler) return CommitCheck.ExecutionOrder.MODIFICATION
return CommitCheck.ExecutionOrder.LATE
}
override fun isDumbAware(): Boolean {
return DumbService.isDumbAware(checkinHandler)
}
override fun isEnabled(): Boolean = checkinHandler.acceptExecutor(executor)
override suspend fun runCheck(commitInfo: CommitInfo): CommitProblem? {
val result = blockingContext {
@Suppress("DEPRECATION") checkinHandler.beforeCheckin(commitInfo.executor, commitInfo.commitContext.additionalDataConsumer)
}
if (result == null || result == CheckinHandler.ReturnResult.COMMIT) return null
return UnknownCommitProblem(result)
}
override fun toString(): String {
return "ProxyCommitCheck: $checkinHandler"
}
}
internal class UnknownCommitProblem(val result: CheckinHandler.ReturnResult) : CommitProblem {
override val text: String get() = message("before.checkin.error.unknown")
override fun showModalSolution(project: Project, commitInfo: CommitInfo): CheckinHandler.ReturnResult = result
}
| apache-2.0 | 501abb4c249a3c178fd5e06371c5ba05 | 37.869863 | 140 | 0.742614 | 4.90634 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrIndexPropertyReference.kt | 13 | 2916 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.references
import com.intellij.openapi.util.TextRange
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty
import org.jetbrains.plugins.groovy.lang.psi.util.getArgumentListArgument
import org.jetbrains.plugins.groovy.lang.psi.util.getRValue
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMethodCallReferenceBase
import org.jetbrains.plugins.groovy.lang.resolve.impl.resolveWithArguments
import org.jetbrains.plugins.groovy.lang.typing.ListLiteralType
abstract class GrIndexPropertyReference(element: GrIndexProperty) : GroovyMethodCallReferenceBase<GrIndexProperty>(element) {
/**
* Consider expression `foo[a, b, c]`.
* Its argument list is `[a, b, c]`.
* - rValue reference, i.e. reference to a getAt() method, will have range of `[`.
* - lValue reference, i.e. reference to a putAt() method, will have range of `]`.
*/
abstract override fun getRangeInElement(): TextRange
final override val receiverArgument: Argument get() = ExpressionArgument(element.invokedExpression)
override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> {
val place = element
val receiver = receiverArgument
val methodName = methodName
val arguments: Arguments? = if (incomplete) null else arguments
val candidates = resolveWithArguments(receiver, methodName, arguments, place)
val singleType = arguments?.singleOrNull()?.type as? ListLiteralType
if (singleType == null || candidates.any { it.isValidResult }) {
return candidates
}
return resolveWithArguments(receiver, methodName, singleType.expressions.map(::ExpressionArgument), place)
}
}
class GrGetAtReference(element: GrIndexProperty) : GrIndexPropertyReference(element) {
override fun getRangeInElement(): TextRange = TextRange.from(element.argumentList.startOffsetInParent, 1)
override val methodName: String get() = "getAt"
override val arguments: Arguments get() = listOf(element.getArgumentListArgument())
}
class GrPutAtReference(element: GrIndexProperty) : GrIndexPropertyReference(element) {
override fun getRangeInElement(): TextRange {
val argumentList = element.argumentList
return TextRange.from(argumentList.startOffsetInParent + argumentList.textLength - 1, 1)
}
override val methodName: String get() = "putAt"
override val arguments: Arguments get() = listOf(element.getArgumentListArgument(), requireNotNull(element.getRValue()))
}
| apache-2.0 | 1cd960321c4667b1b971640d104918ca | 45.285714 | 140 | 0.783608 | 4.458716 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-core/src/test/kotlin/org/craftsmenlabs/gareth/time/DurationExpressionParserTest.kt | 1 | 3419 | package org.craftsmenlabs.gareth.time
import mockit.Expectations
import mockit.Injectable
import mockit.Tested
import org.assertj.core.api.Assertions.assertThat
import org.craftsmenlabs.gareth.validator.time.DurationExpressionParser
import org.craftsmenlabs.gareth.validator.time.TimeService
import org.junit.Test
import java.time.Duration
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
class DurationExpressionParserTest {
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm")
@Injectable
lateinit var dateTimeService: TimeService
@Tested
lateinit var parser: DurationExpressionParser
@Test
fun testValidValues() {
object : Expectations() {
init {
dateTimeService.now()
result = LocalDateTime.parse("01-02-2016 12:00", formatter)
}
}
assertThat(parser.parse("4 seconds")).isEqualTo(Duration.of(4, ChronoUnit.SECONDS))
assertThat(parser.parse("1 SECOND")).isEqualTo(Duration.of(1, ChronoUnit.SECONDS))
assertThat(parser.parse("1 minute")).isEqualTo(Duration.of(1, ChronoUnit.MINUTES))
assertThat(parser.parse("120 MINUTES")).isEqualTo(Duration.of(120, ChronoUnit.MINUTES))
assertThat(parser.parse("1 hour")).isEqualTo(Duration.of(1, ChronoUnit.HOURS))
assertThat(parser.parse("120 HOURS")).isEqualTo(Duration.of(120, ChronoUnit.HOURS))
assertThat(parser.parse("1 day")).isEqualTo(Duration.of(1, ChronoUnit.DAYS))
assertThat(parser.parse("120 days")).isEqualTo(Duration.of(120, ChronoUnit.DAYS))
assertThat(parser.parse("1 week")).isEqualTo(Duration.of(7, ChronoUnit.DAYS))
assertThat(parser.parse("3 weeks")).isEqualTo(Duration.of(21, ChronoUnit.DAYS))
}
@Test
fun testForLeapYear() {
object : Expectations() {
init {
dateTimeService.now()
result = LocalDateTime.parse("01-02-2016 12:00", formatter)
}
}
val oneYear = parser.parse("1 year")
assertThat(oneYear!!.get(ChronoUnit.SECONDS) / 86400).isEqualTo(366);
}
@Test
fun testForEndOfMonth() {
object : Expectations() {
init {
dateTimeService.now()
returns(
LocalDateTime.parse("31-01-2016 12:00", formatter),
LocalDateTime.parse("31-03-2016 12:00", formatter),
LocalDateTime.parse("30-04-2016 12:00", formatter))
}
}
var oneMonth = parser.parse("1 month")
assertThat(oneMonth!!.get(ChronoUnit.SECONDS) / 86400).isEqualTo(29)
oneMonth = parser.parse("1 month")
assertThat(oneMonth!!.get(ChronoUnit.SECONDS) / 86400).isEqualTo(30)
oneMonth = parser.parse("1 month")
assertThat(oneMonth!!.get(ChronoUnit.SECONDS) / 86400).isEqualTo(30)
}
@Test
fun testInvalidValues() {
assertThat(parser.parse("0 day")).isNull()
assertThat(parser.parse("day")).isNull()
assertThat(parser.parse("0 days")).isNull()
assertThat(parser.parse("-1 week")).isNull()
assertThat(parser.parse("1.5 days")).isNull()
assertThat(parser.parse("1,23 day")).isNull()
assertThat(parser.parse("!@#$%")).isNull()
assertThat(parser.parse("")).isNull()
}
} | gpl-2.0 | cca7be6171dc910f37c81f30376ee20e | 36.173913 | 95 | 0.643171 | 4.394602 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinSyntheticTypeComponentProvider.kt | 2 | 6036 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.filter
import com.intellij.debugger.engine.SyntheticTypeComponentProvider
import com.sun.jdi.*
import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_IMPL_NAME_SUFFIX
import org.jetbrains.kotlin.idea.debugger.isInKotlinSources
import org.jetbrains.kotlin.idea.debugger.safeAllLineLocations
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.org.objectweb.asm.Opcodes
import kotlin.jvm.internal.FunctionReference
import kotlin.jvm.internal.PropertyReference
class KotlinSyntheticTypeComponentProvider : SyntheticTypeComponentProvider {
override fun isSynthetic(typeComponent: TypeComponent?): Boolean {
if (typeComponent !is Method) return false
val containingType = typeComponent.declaringType()
val typeName = containingType.name()
if (!FqNameUnsafe.isValid(typeName)) return false
// TODO: this is most likely not necessary since KT-28453 is fixed, but still can be useful when debugging old compiled code
if (containingType.isCallableReferenceSyntheticClass()) {
return true
}
try {
if (typeComponent.isDelegateToDefaultInterfaceImpl()) return true
if (typeComponent.location()?.lineNumber() != 1) return false
if (typeComponent.allLineLocations().any { it.lineNumber() != 1 }) {
return false
}
return !typeComponent.declaringType().safeAllLineLocations().any { it.lineNumber() != 1 }
} catch (e: AbsentInformationException) {
return false
} catch (e: UnsupportedOperationException) {
return false
}
}
override fun isNotSynthetic(typeComponent: TypeComponent?): Boolean {
if (typeComponent is Method) {
val name = typeComponent.name()
if (name.endsWith(SUSPEND_IMPL_NAME_SUFFIX)) {
if (typeComponent.location()?.isInKotlinSources() == true) {
val containingClass = typeComponent.declaringType()
if (typeComponent.argumentTypeNames().firstOrNull() == containingClass.name()) {
// Suspend wrapper for open method
return true
}
}
} else if (name.endsWith(JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX)) {
val originalName = name.dropLast(JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX.length)
return typeComponent.declaringType().methodsByName(originalName).isNotEmpty()
}
}
return super.isNotSynthetic(typeComponent)
}
private tailrec fun ReferenceType?.isCallableReferenceSyntheticClass(): Boolean {
if (this !is ClassType) return false
val superClass = this.superclass() ?: return false
val superClassName = superClass.name()
if (superClassName == PropertyReference::class.java.name || superClassName == FunctionReference::class.java.name) {
return true
}
// The direct supertype may be FunctionReferenceImpl, PropertyReference0Impl, MutablePropertyReference0, etc.
return if (superClassName.startsWith("kotlin.jvm.internal."))
superClass.isCallableReferenceSyntheticClass()
else
false
}
private fun Method.isDelegateToDefaultInterfaceImpl(): Boolean {
if (safeAllLineLocations().size != 1) return false
if (!virtualMachine().canGetBytecodes()) return false
if (!hasOnlyInvokeStatic(this)) return false
return hasInterfaceWithImplementation(this)
}
private companion object {
private val LOAD_INSTRUCTIONS_WITH_INDEX = Opcodes.ILOAD.toByte()..Opcodes.ALOAD.toByte()
private val LOAD_INSTRUCTIONS = (Opcodes.ALOAD + 1).toByte()..(Opcodes.IALOAD - 1).toByte()
private val RETURN_INSTRUCTIONS = Opcodes.IRETURN.toByte()..Opcodes.RETURN.toByte()
}
// Check that method contains only load and invokeStatic instructions. Note that if after load goes ldc instruction it could be checkParametersNotNull method invocation
private fun hasOnlyInvokeStatic(m: Method): Boolean {
val instructions = m.bytecodes()
var i = 0
var isALoad0BeforeStaticCall = false
while (i < instructions.size) {
when (val instr = instructions[i]) {
42.toByte() /* ALOAD_0 */ -> {
i += 1
isALoad0BeforeStaticCall = true
}
in LOAD_INSTRUCTIONS_WITH_INDEX, in LOAD_INSTRUCTIONS -> {
i += 1
if (instr in LOAD_INSTRUCTIONS_WITH_INDEX) i += 1
val nextInstr = instructions[i]
if (nextInstr == Opcodes.LDC.toByte()) {
i += 2
isALoad0BeforeStaticCall = false
}
}
Opcodes.INVOKESTATIC.toByte() -> {
i += 3
if (isALoad0BeforeStaticCall && i == (instructions.size - 1)) {
val nextInstr = instructions[i]
return nextInstr in RETURN_INSTRUCTIONS
}
}
else -> return false
}
}
return false
}
// TODO: class DefaultImpl can be not loaded
private fun hasInterfaceWithImplementation(method: Method): Boolean {
val declaringType = method.declaringType() as? ClassType ?: return false
val interfaces = declaringType.allInterfaces()
val vm = declaringType.virtualMachine()
val traitImpls = interfaces.flatMap { vm.classesByName(it.name() + JvmAbi.DEFAULT_IMPLS_SUFFIX) }
return traitImpls.any { it.methodsByName(method.name()).isNotEmpty() }
}
}
| apache-2.0 | ec81dc9165db904353c533a9249cfbb2 | 42.73913 | 172 | 0.631213 | 5.085088 | false | false | false | false |
mglukhikh/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/extended/ExtendedTreeFixture.kt | 2 | 6236 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.fixtures.extended
import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader
import com.intellij.testGuiFramework.cellReader.ProjectTreeCellReader
import com.intellij.testGuiFramework.cellReader.SettingsTreeCellReader
import com.intellij.testGuiFramework.driver.ExtendedJTreeDriver
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.core.MouseButton
import org.fest.swing.core.MouseClickInfo
import org.fest.swing.core.Robot
import org.fest.swing.exception.LocationUnavailableException
import org.fest.swing.fixture.JTreeFixture
import java.util.*
import javax.swing.JTree
import javax.swing.tree.TreePath
open class ExtendedTreeFixture(val robot: Robot, val tree: JTree) : JTreeFixture(robot, tree) {
val myDriver = ExtendedJTreeDriver(robot)
val myCellReader: JTreeCellReader
init {
replaceDriverWith(myDriver)
myCellReader = defineCellReader()
}
fun hasXPath(vararg pathStrings: String): Boolean{
return hasPath(pathStrings.toList())
}
fun hasPath(pathStrings: List<String>): Boolean {
try {
myDriver.checkPathExists(tree, pathStrings)
return true
}
catch (lue: LocationUnavailableException) {
return false
}
}
fun clickPath(pathStrings: List<String>, mouseClickInfo: MouseClickInfo)
= myDriver.clickPath(tree, pathStrings, mouseClickInfo)
fun clickPath(vararg pathStrings: String, mouseClickInfo: MouseClickInfo)
= myDriver.clickPath(tree, pathStrings.toList(), mouseClickInfo)
fun clickPath(pathStrings: List<String>, button: MouseButton = MouseButton.LEFT_BUTTON, times: Int = 1)
= myDriver.clickPath(tree, pathStrings, button, times)
fun clickXPath(vararg xPathStrings: String)
= myDriver.clickXPath(tree, xPathStrings.toList())
fun clickXPath(xPathStrings: List<String>) {
myDriver.clickXPath(tree, xPathStrings, MouseButton.LEFT_BUTTON, 1)
}
fun clickPath(vararg pathStrings: String, button: MouseButton = MouseButton.LEFT_BUTTON, times: Int = 1)
= myDriver.clickPath(tree, pathStrings.toList(), button, times)
fun checkPathExists(pathStrings: List<String>) = myDriver.checkPathExists(tree, pathStrings)
fun checkPathExists(vararg pathStrings: String) = myDriver.checkPathExists(tree, pathStrings.toList())
fun nodeValue(pathStrings: List<String>): String? = myDriver.nodeValue(tree, pathStrings)
fun nodeValue(vararg pathStrings: String): String? = myDriver.nodeValue(tree, pathStrings.toList())
fun doubleClickPath(pathStrings: List<String>) = myDriver.doubleClickPath(tree, pathStrings)
fun doubleClickPath(vararg pathStrings: String) = myDriver.doubleClickPath(tree, pathStrings.toList())
fun doubleClickXPath(vararg pathStrings: String) = myDriver.doubleClickXPath(tree, pathStrings.toList())
fun rightClickPath(pathStrings: List<String>) = myDriver.rightClickPath(tree, pathStrings)
fun rightClickPath(vararg pathStrings: String) = myDriver.rightClickPath(tree, pathStrings.toList())
fun rightClickXPath(vararg pathStrings: String) = myDriver.rightClickXPath(tree, pathStrings.toList())
fun expandPath(pathStrings: List<String>) = myDriver.expandPath(tree, pathStrings)
fun expandPath(vararg pathStrings: String) = myDriver.expandPath(tree, pathStrings.toList())
fun expandXPath(vararg pathStrings: String) = myDriver.expandXPath(tree, pathStrings.toList())
fun collapsePath(pathStrings: List<String>) = myDriver.collapsePath(tree, pathStrings)
fun collapsePath(vararg pathStrings: String) = myDriver.collapsePath(tree, pathStrings.toList())
fun collapseXPath(vararg pathStrings: String) = myDriver.collapseXPath(tree, pathStrings.toList())
fun selectPath(pathStrings: List<String>) = myDriver.selectPath(tree, pathStrings)
fun selectPath(vararg pathStrings: String) = myDriver.selectPath(tree, pathStrings.toList())
fun selectXPath(vararg pathStrings: String) = myDriver.selectXPath(tree, pathStrings.toList())
fun scrollToPath(pathStrings: List<String>) = myDriver.scrollToPath(tree, pathStrings)
fun scrollToPath(vararg pathStrings: String) = myDriver.scrollToPath(tree, pathStrings.toList())
fun scrollToXPath(vararg pathStrings: String) = myDriver.scrollToXPath(tree, pathStrings.toList())
fun showPopupMenu(pathStrings: List<String>) = myDriver.showPopupMenu(tree, pathStrings)
fun showPopupMenu(vararg pathStrings: String) = myDriver.showPopupMenu(tree, pathStrings.toList())
fun drag(pathStrings: List<String>) = myDriver.drag(tree, pathStrings)
fun drag(vararg pathStrings: String) = myDriver.drag(tree, pathStrings.toList())
fun drop(pathStrings: List<String>) = myDriver.drop(tree, pathStrings)
fun drop(vararg pathStrings: String) = myDriver.drop(tree, pathStrings.toList())
fun getPath(treePath: TreePath): List<String> {
var path = treePath
val result = ArrayList<String>()
while (path.pathCount != 1 || (tree.isRootVisible && path.pathCount == 1)) {
val valueAt = myCellReader.valueAt(tree, path.lastPathComponent) ?: "null"
result.add(0, valueAt)
if (path.pathCount == 1) break
else path = path.parentPath
}
return result
}
private fun defineCellReader() : JTreeCellReader {
var resultReader: JTreeCellReader
when (tree.javaClass.name) {
"com.intellij.openapi.options.newEditor.SettingsTreeView\$MyTree" -> resultReader = SettingsTreeCellReader()
"com.intellij.ide.projectView.impl.ProjectViewPane\$1" -> resultReader = ProjectTreeCellReader()
else -> resultReader = ExtendedJTreeCellReader()
}
replaceCellReader(resultReader)
return resultReader
}
} | apache-2.0 | 41bce06077fc378aed512a0a5adc5238 | 39.5 | 114 | 0.766196 | 4.067841 | false | false | false | false |
jbmlaird/DiscogsBrowser | app/src/test/java/bj/vinylbrowser/home/HomeEpxControllerTest.kt | 1 | 26385 | package bj.vinylbrowser.home
import android.content.Context
import android.os.Build.VERSION_CODES.LOLLIPOP
import bj.vinylbrowser.listing.ListingFactory
import bj.vinylbrowser.model.search.SearchResult
import bj.vinylbrowser.order.OrderFactory
import bj.vinylbrowser.utils.DateFormatter
import bj.vinylbrowser.utils.ImageViewAnimator
import bj.vinylbrowser.utils.SharedPrefsManager
import bj.vinylbrowser.utils.analytics.AnalyticsTracker
import com.nhaarman.mockito_kotlin.mock
import junit.framework.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.MockitoAnnotations.initMocks
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Created by Josh Laird on 21/05/2017.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = intArrayOf(LOLLIPOP), manifest = Config.NONE)
class HomeEpxControllerTest {
lateinit var epxController: HomeEpxController
val context: Context = mock()
val view: HomeContract.View = mock()
val sharedPrefsManager: SharedPrefsManager = mock()
val imageViewAnimator: ImageViewAnimator = mock()
val dateFormatter: DateFormatter = mock()
val tracker: AnalyticsTracker = mock()
@Before
fun setup() {
initMocks(this)
epxController = HomeEpxController(context, view, sharedPrefsManager, imageViewAnimator, dateFormatter, tracker)
epxController.requestModelBuild()
}
@Test
fun initialLoadingState_correct() {
val copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun viewedHistoryError_displaysRetryModel() {
epxController.setViewedReleasesError(true)
val copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun viewedHistoryErrorThenLoad_displaysLoad() {
epxController.setViewedReleasesError(true)
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setLoadingViewedReleases(true)
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun viewedHistoryErrorThenReload_displaysList() {
epxController.setViewedReleasesError(true)
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setViewedReleases(ViewedReleaseFactory.buildViewedReleases(1))
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "CarouselModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun recommendationError_displaysRetryModel() {
epxController.setRecommendationsError(true)
val copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun recommendationErrorThenReload_displaysList() {
epxController.setRecommendationsError(true)
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setRecommendations(listOf(SearchResult()))
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "CarouselModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun recommendationsErrorThenLoad_displaysLoad() {
epxController.setRecommendationsError(true)
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setLoadingRecommendations(true)
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun emptyLists_displaysNoOrderModels() {
epxController.setViewedReleases(emptyList())
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setRecommendations(emptyList())
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setOrders(emptyList())
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setSelling(emptyList())
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun error_displaysRetryModels() {
epxController.setOrdersError(true)
val copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun unauthorizedError_displaysVerifyEmailModels() {
epxController.setConfirmEmail(true)
val copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "InfoTextModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun errorThenRetry_displaysCorrectly() {
epxController.setOrdersError(true)
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "RetryModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setOrders(emptyList())
epxController.setSelling(emptyList())
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
@Test
fun ordersList_displaysList() {
epxController.setOrders(OrderFactory.buildListOfOrders(2))
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "OrderModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "OrderModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[9].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[10].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 11)
epxController.setSelling(listOf(ListingFactory.buildListing("1"), ListingFactory.buildListing("2")))
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "OrderModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "OrderModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[9].javaClass.simpleName, "ListingModel_")
assertEquals(copyOfModels[10].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[11].javaClass.simpleName, "ListingModel_")
assertEquals(copyOfModels[12].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 13)
}
@Test
fun overFiveItems_Concatenates() {
//Adding 6 orders
epxController.setOrders(OrderFactory.buildListOfOrders(6))
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "OrderModel_") //1
assertEquals(copyOfModels[6].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "OrderModel_") //2
assertEquals(copyOfModels[8].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[9].javaClass.simpleName, "OrderModel_") //3
assertEquals(copyOfModels[10].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[11].javaClass.simpleName, "OrderModel_") //4
assertEquals(copyOfModels[12].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[13].javaClass.simpleName, "OrderModel_") // Only 5
assertEquals(copyOfModels[14].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[15].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[16].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[17].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 18)
epxController.setSelling(ListingFactory.buildNumberOfListings(6))
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "OrderModel_") //1
assertEquals(copyOfModels[6].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "OrderModel_") //2
assertEquals(copyOfModels[8].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[9].javaClass.simpleName, "OrderModel_") //3
assertEquals(copyOfModels[10].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[11].javaClass.simpleName, "OrderModel_") //4
assertEquals(copyOfModels[12].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[13].javaClass.simpleName, "OrderModel_") // Only 5
assertEquals(copyOfModels[14].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[15].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[16].javaClass.simpleName, "ListingModel_")
assertEquals(copyOfModels[17].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[18].javaClass.simpleName, "ListingModel_")
assertEquals(copyOfModels[19].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[20].javaClass.simpleName, "ListingModel_")
assertEquals(copyOfModels[21].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[22].javaClass.simpleName, "ListingModel_")
assertEquals(copyOfModels[23].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[24].javaClass.simpleName, "ListingModel_") //Only 5
assertEquals(copyOfModels[25].javaClass.simpleName, "DividerModel_")
assertEquals(copyOfModels[26].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 27)
}
@Test
fun setLoadingTrue_loadingModelsDisplay() {
epxController.setOrders(emptyList())
epxController.setSelling(emptyList())
var copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "NoOrderModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
epxController.setLoadingMorePurchases(true)
copyOfModels = epxController.adapter.copyOfModels
assertEquals(copyOfModels[0].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[2].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[3].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[4].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[5].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[6].javaClass.simpleName, "MainTitleModel_")
assertEquals(copyOfModels[7].javaClass.simpleName, "LoadingModel_")
assertEquals(copyOfModels[8].javaClass.simpleName, "EmptySpaceModel_")
assertEquals(copyOfModels.size, 9)
}
} | mit | f7baad0c7fe61375de38ea27c682c187 | 55.866379 | 119 | 0.736706 | 4.760058 | false | false | false | false |
kbrock/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/co/there4/hexagon/Benchmark.kt | 2 | 2592 | package co.there4.hexagon
import co.there4.hexagon.serialization.convertToMap
import co.there4.hexagon.serialization.serialize
import co.there4.hexagon.web.*
import co.there4.hexagon.web.servlet.ServletServer
import java.net.InetAddress.getByName as address
import java.time.LocalDateTime.now
import java.util.concurrent.ThreadLocalRandom
import javax.servlet.annotation.WebListener
// DATA CLASSES
internal data class Message(val message: String = "Hello, World!")
internal data class Fortune(val _id: Int, val message: String)
internal data class World(val _id: Int, val id: Int = _id, val randomNumber: Int = rnd())
// CONSTANTS
private val CONTENT_TYPE_JSON = "application/json"
private val QUERIES_PARAM = "queries"
// UTILITIES
internal fun rnd() = ThreadLocalRandom.current().nextInt(DB_ROWS) + 1
private fun Exchange.returnWorlds(worlds: List<World>) {
fun World.strip(): Map<*, *> = this.convertToMap().filterKeys { it != "_id" }
val result =
if (request[QUERIES_PARAM] == null) worlds[0].strip().serialize()
else worlds.map(World::strip).serialize()
ok(result, CONTENT_TYPE_JSON)
}
private fun Exchange.getQueries() =
try {
val queries = request[QUERIES_PARAM]?.toInt() ?: 1
when {
queries < 1 -> 1
queries > 500 -> 500
else -> queries
}
}
catch (ex: NumberFormatException) {
1
}
// HANDLERS
private fun Exchange.listFortunes(store: Repository) {
val fortunes = store.findFortunes() + Fortune(0, "Additional fortune added at request time.")
template("fortunes.html", "fortunes" to fortunes.sortedBy { it.message })
}
private fun benchmarkRoutes(store: Repository, srv: Router = server) {
srv.before {
response.addHeader("Server", "Servlet/3.1")
response.addHeader("Transfer-Encoding", "chunked")
response.addHeader("Date", httpDate(now()))
}
srv.get("/plaintext") { ok("Hello, World!", "text/plain") }
srv.get("/json") { ok(Message().serialize(), CONTENT_TYPE_JSON) }
srv.get("/fortunes") { listFortunes(store) }
srv.get("/db") { returnWorlds(store.findWorlds(getQueries())) }
srv.get("/query") { returnWorlds(store.findWorlds(getQueries())) }
srv.get("/update") { returnWorlds(store.replaceWorlds(getQueries())) }
}
@WebListener class Web : ServletServer () {
override fun init() {
benchmarkRoutes(createStore("mongodb"), this)
}
}
fun main(args: Array<String>) {
val store = createStore(if (args.isEmpty()) "mongodb" else args[0])
benchmarkRoutes(store)
run()
}
| bsd-3-clause | acecc0d6e7f11a90e2ac6e078fc403b2 | 31.810127 | 97 | 0.675926 | 3.789474 | false | false | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/ui/taskcell/components/courselabel/OnCourseLabelChangeUpdater.kt | 1 | 3195 | package nl.deltadak.plep.ui.taskcell.components.courselabel
import javafx.application.Platform
import javafx.beans.InvalidationListener
import javafx.beans.Observable
import javafx.beans.value.ObservableValue
import javafx.scene.control.ComboBox
import javafx.scene.control.ProgressIndicator
import javafx.scene.control.TreeView
import javafx.scene.control.cell.TextFieldTreeCell
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.DatabaseFacade
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.InvalidationListenerWithBlocker
import nl.deltadak.plep.ui.util.converters.toHomeworkTaskList
import java.time.LocalDate
/**
* Defines what happens when a combobox (the 'courselabel') selection is updated.
*/
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class OnCourseLabelChangeUpdater(
/** For user feedback. */
val progressIndicator: ProgressIndicator,
/** The ComboBox on which to listen for changes. */
private val comboBox: ComboBox<String>) {
/**
* Add a listener to the ComboBox which listens for value changes and applies them normally with one exception: when <no label> is selected then the empty string will be shown.
*
* @param treeCell The TreeCell in which the ComboBox resides, needed to updateOrInsert the courselabel of the task.
*/
fun addValueChangeListener(treeCell: TextFieldTreeCell<HomeworkTask>) {
comboBox.valueProperty().addListener { observable: ObservableValue<out String>?, oldValue: String?, newValue: String? ->
val task = treeCell.treeItem.value
if (newValue != null && newValue == "<no label>") {
task.label = ""
// Delay removing the combobox text because we cannot change the contents of an ObservableList while a change is in progress.
// In practice the delay is unnoticable.
Platform.runLater {comboBox.value = ""}
} else {
task.label = newValue ?: ""
}
}
}
/**
* Set listener on the ComboBox to updateOrInsert the database when the
* selected index changes.
*
* @param tree TreeView which the LabelCell is in, needed for updating the database
* @param day LocalDate which we need for updating the database
*
* @return The listener with blocker, so the block can be set when needed.
*/
fun addDatabaseUpdaterChangeListener(tree: TreeView<HomeworkTask>, day: LocalDate) : InvalidationListenerWithBlocker {
// Define a standard listener.
val invalidationListener = InvalidationListener { observable: Observable ->
DatabaseFacade(progressIndicator).pushData(day, tree.toHomeworkTaskList())
// We do not need to cleanup here, as no tasks were added or deleted.
}
// Pass the invalidationlistener on to our custom listener.
val labelChangeListener = InvalidationListenerWithBlocker(invalidationListener)
// Add the listener which updates the database to the combobox.
comboBox.selectionModel.selectedIndexProperty().addListener(labelChangeListener)
return labelChangeListener
}
} | mit | 609dd27b5842973fe211aaa3e2beda6a | 40.506494 | 180 | 0.711424 | 4.992188 | false | false | false | false |
Adven27/Exam | exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/builder/DataBuilders.kt | 1 | 3861 | package io.github.adven27.concordion.extensions.exam.db.builder
import org.dbunit.dataset.Column
import org.dbunit.dataset.DataSetException
import org.dbunit.dataset.DefaultTableMetaData
import org.dbunit.dataset.ITableMetaData
import org.dbunit.dataset.datatype.DataType
import java.util.HashMap
import java.util.LinkedHashMap
class TableMetaDataBuilder(private val tableName: String, private val policy: IStringPolicy) {
private val keysToColumns = LinkedHashMap<String, Column>()
@Suppress("SpreadOperator")
fun with(metaData: ITableMetaData): TableMetaDataBuilder = with(*metaData.columns)
fun with(vararg columns: Column): TableMetaDataBuilder {
columns.forEach { with(it) }
return this
}
fun with(column: Column): TableMetaDataBuilder {
if (column.isUnknown()) {
add(column)
}
return this
}
private fun add(column: Column) {
keysToColumns[toKey(column)] = column
}
fun numberOfColumns(): Int = keysToColumns.size
fun build(): ITableMetaData = DefaultTableMetaData(tableName, columns())
private fun toKey(column: Column): String = policy.toKey(column.columnName)
private fun Column.isUnknown(): Boolean = !this.isKnown()
private fun Column.isKnown(): Boolean = keysToColumns.containsKey(toKey(this))
private fun columns(): Array<Column> = keysToColumns.values.toTypedArray()
}
class DataRowBuilder(private val dataSet: DataSetBuilder, tableName: String) : BasicDataRowBuilder(tableName) {
override fun with(columnName: String, value: Any?): DataRowBuilder {
put(columnName, value)
return this
}
fun withFields(fields: Map<String, Any?>): DataRowBuilder {
fields.forEach { (col, value) -> with(col, value) }
return this
}
@Throws(DataSetException::class)
fun add(): DataSetBuilder {
dataSet.add(this)
return dataSet
}
}
open class BasicDataRowBuilder(val tableName: String) {
private val columnNameToValue: HashMap<String, Any?> = LinkedHashMap()
private var allColumnNames = emptyArray<String>()
private val defaultValues = HashMap<String, Any?>()
/**
* Added the column to the Data.
*
* @param columnName the name of the column.
* @param value the value the column should have.
* @return the current object.
*/
open fun with(columnName: String, value: Any?): BasicDataRowBuilder {
columnNameToValue[columnName] = value
return this
}
/**
* Define all values of the table with null or the defaultvalue.
* All columns are defined with [.setAllColumnNames].
* For not null columns you must define default values via
* [.addDefaultValue].
*
* @return the current object.
* @author niels
* @since 2.4.10
*/
fun fillUndefinedColumns(): BasicDataRowBuilder {
for (column in allColumnNames) {
if (!columnNameToValue.containsKey(column)) {
columnNameToValue[column] = defaultValues[column]
}
}
return this
}
fun values(columns: Array<Column>): Array<Any?> = columns.map { getValue(it) }.toTypedArray()
fun toMetaData(): ITableMetaData = createMetaData(columnNameToValue.keys.map { createColumn(it) })
private fun createMetaData(columns: List<Column>): ITableMetaData =
DefaultTableMetaData(tableName, columns.toTypedArray())
private fun createColumn(columnName: String) = Column(columnName, DataType.UNKNOWN)
protected fun put(columnName: String, value: Any?) {
columnNameToValue[columnName] = value
}
protected fun getValue(column: Column): Any? {
return getValue(column.columnName)
}
protected fun getValue(columnName: String): Any? {
return columnNameToValue[columnName]
}
}
| mit | ab56d645cb68af690fba24db015c2440 | 31.720339 | 111 | 0.681689 | 4.367647 | false | false | false | false |
RSDT/Japp | app/src/main/java/nl/rsdt/japp/jotial/data/firebase/Location.kt | 1 | 761 | package nl.rsdt.japp.jotial.data.firebase
import com.google.android.gms.maps.model.LatLng
/**
* Created by mattijn on 30/09/17.
*/
class Location {
var createdOn: Long? = null
var lat: Double = 0.toDouble()
var lon: Double = 0.toDouble()
var createdBy: String? =null
constructor() // speciaal voor firebase
constructor(navigateTo: LatLng, createdBy: String?) {
this.lat = navigateTo.latitude
this.lon = navigateTo.longitude
this.createdBy = createdBy
createdOn = System.currentTimeMillis()
}
override fun equals(other: Any?): Boolean {
return if (other is Location) {
other.lon == this.lon && other.lat == this.lat
} else {
false
}
}
}
| apache-2.0 | 16b3bd4adf8d80795d3d017c10c2ba13 | 23.548387 | 58 | 0.61498 | 3.963542 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/korio/util/EnumExtCompat.kt | 1 | 695 | package com.soywiz.korio.util
interface NumericEnum {
val id: Int
}
interface Flags<T> : NumericEnum {
infix fun hasFlag(item: Flags<T>): Boolean = (id and item.id) == item.id
}
interface IdEnum {
val id: Int
open class SmallCompanion<T : IdEnum>(val values: Array<T>) {
private val defaultValue: T = values.first()
private val MAX_ID = values.map { it.id }.maxOrNull() ?: 0
private val valuesById = Array<Any>(MAX_ID + 1) { defaultValue }
init {
for (v in values) valuesById[v.id] = v
}
@Suppress("UNCHECKED_CAST")
operator fun invoke(id: Int): T = valuesById.getOrElse(id) { defaultValue } as T
}
}
| mit | e7134a837793be6ea959911975e21244 | 25.730769 | 88 | 0.610072 | 3.582474 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/mem/Memory.kt | 1 | 7473 | package com.soywiz.kpspemu.mem
import com.soywiz.dynarek2.*
import com.soywiz.kmem.*
import com.soywiz.korio.stream.*
private const val MEMORY_MASK = 0x0FFFFFFF
private const val MASK = MEMORY_MASK
private val LWR_MASK = intArrayOf(0x00000000, 0xFF000000.toInt(), 0xFFFF0000.toInt(), 0xFFFFFF00.toInt())
private val LWR_SHIFT = intArrayOf(0, 8, 16, 24)
private val LWL_MASK = intArrayOf(0x00FFFFFF, 0x0000FFFF, 0x000000FF, 0x00000000)
private val LWL_SHIFT = intArrayOf(24, 16, 8, 0)
private val SWL_MASK = intArrayOf(0xFFFFFF00.toInt(), 0xFFFF0000.toInt(), 0xFF000000.toInt(), 0x00000000)
private val SWL_SHIFT = intArrayOf(24, 16, 8, 0)
private val SWR_MASK = intArrayOf(0x00000000, 0x000000FF, 0x0000FFFF, 0x00FFFFFF)
private val SWR_SHIFT = intArrayOf(0, 8, 16, 24)
typealias Memory = D2Memory
object MemoryInfo {
const val MASK = MEMORY_MASK
const val HIGH_MASK = 0xf0000000.toInt()
inline val SCATCHPAD_OFFSET get() = 0x0000000
inline val VIDEO_OFFSET get() = 0x04000000
inline val MAIN_OFFSET get() = 0x08000000
inline val SCATCHPAD_SIZE get() = 64 * 1024 // 64 KB
inline val MAIN_SIZE get() = 32 * 1024 * 1024 // 32 MB
inline val VIDEO_SIZE get() = 2 * 1024 * 1024 // 2 MB
val SCRATCHPAD = MemorySegment("scatchpad", SCATCHPAD_OFFSET until (SCATCHPAD_OFFSET + SCATCHPAD_SIZE))
val VIDEOMEM = MemorySegment("videomem", VIDEO_OFFSET until (VIDEO_OFFSET + VIDEO_SIZE))
val MAINMEM = MemorySegment("mainmem", MAIN_OFFSET until (MAIN_OFFSET + MAIN_SIZE))
val DUMMY: Memory by lazy { NewD2Memory(1024).mem }
}
data class MemorySegment(val name: String, val range: IntRange) {
val start get() = range.start
val end get() = range.endInclusive + 1
val size get() = end - start
operator fun contains(index: Int) = range.contains(index and MEMORY_MASK)
}
val cachedMemory by lazy { NewD2Memory(0x10000000).mem }
fun CachedMemory(): Memory = cachedMemory
fun Memory(): Memory = NewD2Memory(0x10000000).mem
fun Memory.readBytes(srcPos: Int, count: Int): ByteArray = ByteArray(count).apply { read(srcPos, this, 0, count) }
fun Memory.write(dstPos: Int, src: ByteArray, srcPos: Int = 0, len: Int = src.size - srcPos): Unit {
for (n in 0 until len) sb(dstPos + n, src[srcPos + n].toInt())
}
fun Memory.read(srcPos: Int, dst: ByteArray, dstPos: Int = 0, len: Int = dst.size - dstPos): Unit {
for (n in 0 until len) dst[dstPos + n] = this.lb(srcPos + n).toByte()
}
fun Memory.write(dstPos: Int, src: IntArray, srcPos: Int = 0, len: Int = src.size - srcPos): Unit {
for (n in 0 until len) sw(dstPos + n * 4, src[srcPos + n].toInt())
}
fun Memory.read(srcPos: Int, dst: ShortArray, dstPos: Int = 0, len: Int = dst.size - dstPos): Unit {
for (n in 0 until len) dst[dstPos + n] = lh(srcPos + n * 4).toShort()
}
fun Memory.read(srcPos: Int, dst: IntArray, dstPos: Int = 0, len: Int = dst.size - dstPos): Unit {
for (n in 0 until len) dst[dstPos + n] = lw(srcPos + n * 4)
}
fun Memory.lwl(address: Int, value: Int): Int {
val align = address and 3
val oldvalue = this.lw(address and 3.inv())
return ((oldvalue shl LWL_SHIFT[align]) or (value and LWL_MASK[align]))
}
fun Memory.lwr(address: Int, value: Int): Int {
val align = address and 3
val oldvalue = this.lw(address and 3.inv())
return ((oldvalue ushr LWR_SHIFT[align]) or (value and LWR_MASK[align]))
}
fun Memory.swl(address: Int, value: Int): Unit {
val align = address and 3
val aadress = address and 3.inv()
val vwrite = (value ushr SWL_SHIFT[align]) or (this.lw(aadress) and SWL_MASK[align])
this.sw(aadress, vwrite)
}
fun Memory.swr(address: Int, value: Int): Unit {
val align = address and 3
val aadress = address and 3.inv()
val vwrite = (value shl SWR_SHIFT[align]) or (this.lw(aadress) and SWR_MASK[align])
this.sw(aadress, vwrite)
}
fun Memory.index(address: Int) = address and 0x0FFFFFFF
fun Memory.sb(address: Int, value: Int) = run { set8(index(address) ushr 0, value) }
fun Memory.sh(address: Int, value: Int) = run { set16(index(address) ushr 1, value) }
fun Memory.sw(address: Int, value: Int) = run { set32(index(address) ushr 2, value) }
fun Memory.lb(address: Int) = get8(index(address) ushr 0).toInt()
fun Memory.lh(address: Int) = get16(index(address) ushr 1).toInt()
fun Memory.lw(address: Int): Int = get32(index(address) ushr 2).toInt()
fun Memory.getFastMem(): KmlNativeBuffer? = null
fun Memory.getFastMemOffset(addr: Int): Int = index(addr)
fun Memory.svl_q(address: Int, read: (index: Int) -> Int) {
val k = (3 - ((address ushr 2) and 3))
var addr = address and 0xF.inv()
for (n in k until 4) {
sw(addr, read(n))
addr += 4
}
}
fun Memory.svr_q(address: Int, read: (index: Int) -> Int) {
val k = (4 - ((address ushr 2) and 3))
var addr = address
for (n in 0 until k) {
sw(addr, read(n))
addr += 4
}
}
fun Memory.lvl_q(address: Int, writer: (index: Int, value: Int) -> Unit) {
val k = (3 - ((address ushr 2) and 3))
var addr = address and 0xF.inv()
for (n in k until 4) {
writer(n, lw(addr))
addr += 4
}
}
fun Memory.lvr_q(address: Int, writer: (index: Int, value: Int) -> Unit) {
val k = (4 - ((address ushr 2) and 3))
var addr = address
for (n in 0 until k) {
writer(n, lw(addr))
addr += 4
}
}
// Unsigned
fun Memory.lbu(address: Int): Int = lb(address) and 0xFF
fun Memory.lhu(address: Int): Int = lh(address) and 0xFFFF
fun Memory.lwSafe(address: Int): Int = if (isValidAddress(address)) lw(address) else 0
fun Memory.lbuSafe(address: Int): Int = if (isValidAddress(address)) lbu(address) else 0
fun Memory.isValidAddress(address: Int): Boolean =
address in MemoryInfo.MAINMEM || address in MemoryInfo.VIDEOMEM || address in MemoryInfo.SCRATCHPAD
fun Memory.getPointerStream(address: Int, size: Int): SyncStream = openSync().sliceWithSize(address, size)
fun Memory.getPointerStream(address: Int): SyncStream = openSync().sliceStart(address.toLong())
fun Memory.readStringzOrNull(offset: Int): String? = if (offset != 0) readStringz(offset) else null
//fun Memory.readStringz(offset: Int): String = openSync().sliceStart(offset.toLong()).readStringz()
fun Memory.strlenz(offset: Int): Int {
val idx = this.index(offset)
for (n in 0 until Int.MAX_VALUE) {
val c = get8(idx + n)
if (c == 0) return n
}
return -1
}
// @TODO: UTF-8
fun Memory.readStringz(offset: Int): String {
val len = strlenz(offset)
val idx = this.index(offset)
return CharArray(len) { get8(idx + it).toChar() }.concatToString()
}
fun Memory.copy(srcPos: Int, dstPos: Int, size: Int) = run {
val srcOffset = index(srcPos)
val dstOffset = index(dstPos)
for (n in 0 until size) {
set8(dstOffset + n, get8(srcOffset + n))
}
}
fun Memory.memset(address: Int, value: Int, size: Int) = fill(value, address, size)
fun Memory.fill(value: Int, address: Int, size: Int) {
val offset = index(address)
for (n in 0 until size) {
set8(offset + n, value)
}
}
fun Memory.hash(address4: Int, nwords: Int): Int {
var hash = 0
val offset4 = index(address4 * 4) / 4
for (n in 0 until nwords) {
hash += get32(offset4 + n)
}
return hash
}
fun Memory.reset() {
for (seg in listOf(MemoryInfo.SCRATCHPAD, MemoryInfo.MAINMEM, MemoryInfo.VIDEOMEM)) {
fill(0, seg.start, seg.size)
}
}
//fun Memory.close() = close()
| mit | d65e3c855261b20ad71a86942f201143 | 33.920561 | 114 | 0.66118 | 3.07278 | false | false | false | false |
SofteamOuest/referentiel-personnes-api | src/main/kotlin/com/softeam/referentielpersonnes/domain/Personne.kt | 1 | 872 | package com.softeam.referentielpersonnes.domain
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
@Document
data class Personne(
@Id
var id: String? = null,
var nom: String? = null,
var prenom: String? = null,
var date_de_naissance: String? = null,
var photo: String? = null,
var mail_pro: String? = null,
var mail_perso: String? = null,
var role_nom: String? = null,
var tel_pro: String? = null,
var tel_perso: String? = null,
var poste: String? = null,
var mail_manager: String? = null,
var mail_commercial: String? = null,
var date_debut_contrat: String? = null,
var date_visite_medical: String? = null,
var periode_essai_valide: Boolean? = null
) | apache-2.0 | 765b0a41994293fee248b35cbbe54db2 | 31.615385 | 61 | 0.598624 | 3.559184 | false | false | false | false |
grote/Liberario | app/src/main/java/de/grobox/transportr/locations/LocationView.kt | 1 | 12334 | /*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.locations
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.content.Context.LAYOUT_INFLATER_SERVICE
import android.os.AsyncTask.Status.FINISHED
import android.os.Bundle
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.view.ViewCompat
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.google.common.base.Strings.isNullOrEmpty
import de.grobox.transportr.R
import de.grobox.transportr.data.locations.FavoriteLocation
import de.grobox.transportr.data.locations.FavoriteLocation.FavLocationType
import de.grobox.transportr.data.locations.HomeLocation
import de.grobox.transportr.data.locations.WorkLocation
import de.grobox.transportr.locations.LocationAdapter.TYPING_THRESHOLD
import de.grobox.transportr.locations.SuggestLocationsTask.SuggestLocationsTaskCallback
import de.grobox.transportr.networks.TransportNetwork
import de.schildbach.pte.dto.SuggestLocationsResult
open class LocationView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs),
SuggestLocationsTaskCallback {
companion object {
private const val LOCATION = "location"
private const val TEXT = "text"
private const val TEXT_POSITION = "textPosition"
private const val AUTO_COMPLETION_DELAY = 300
private const val SUPER_STATE = "superState"
}
private lateinit var adapter: LocationAdapter
private var task: SuggestLocationsTask? = null
private var transportNetwork: TransportNetwork? = null
private var location: WrapLocation? = null
private var suggestLocationsTaskPending = false
protected val ui: LocationViewHolder
protected var listener: LocationViewListener? = null
protected val hint: String?
var type = FavLocationType.FROM
set(type) {
field = type
adapter.setSort(type)
}
private val text: String?
get() = if (ui.location.text != null) {
ui.location.text.toString()
} else {
null
}
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.LocationView, 0, 0)
val showIcon = a.getBoolean(R.styleable.LocationView_showIcon, true)
hint = a.getString(R.styleable.LocationView_hint)
a.recycle()
orientation = HORIZONTAL
val inflater = context.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.location_view, this, true)
ui = LocationViewHolder(this)
ui.location.hint = hint
if (!isInEditMode) {
adapter = LocationAdapter(getContext())
ui.location.setAdapter<LocationAdapter>(adapter)
}
ui.location.setOnItemClickListener { _, _, position, _ ->
try {
val loc = adapter.getItem(position)
if (loc != null) onLocationItemClick(loc)
} catch (e: ArrayIndexOutOfBoundsException) {
Log.e(LocationView::class.java.simpleName, e.message, e)
}
}
ui.location.onFocusChangeListener = OnFocusChangeListener { v, hasFocus -> [email protected](v, hasFocus) }
ui.location.setOnClickListener { _ -> [email protected]() }
if (showIcon) {
ui.status.setOnClickListener { _ ->
adapter.resetDropDownLocations()
[email protected] { this.onClick() }
}
} else {
ui.status.visibility = GONE
}
// clear text button
ui.clear.setOnClickListener { _ -> clearLocationAndShowDropDown(true) }
// From text input changed
ui.location.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (count - before == 1 || before == 1 && count == 0) handleTextChanged(s)
}
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
})
}
protected class LocationViewHolder internal constructor(view: View) {
val status: ImageView = view.findViewById(R.id.statusButton)
val location: AutoCompleteTextView = view.findViewById(R.id.location)
internal val progress: ProgressBar = view.findViewById(R.id.progress)
val clear: ImageButton = view.findViewById(R.id.clearButton)
}
/* State Saving and Restoring */
public override fun onSaveInstanceState(): Parcelable? {
val bundle = Bundle()
bundle.putParcelable(SUPER_STATE, super.onSaveInstanceState())
bundle.putInt(TEXT_POSITION, ui.location.selectionStart)
bundle.putSerializable(LOCATION, location)
if (location == null && ui.location.text.isNotEmpty()) {
bundle.putString(TEXT, ui.location.text.toString())
}
return bundle
}
public override fun onRestoreInstanceState(state: Parcelable?) {
if (state is Bundle) { // implicit null check
val loc = state.getSerializable(LOCATION) as WrapLocation?
val text = state.getString(TEXT)
if (loc != null) {
setLocation(loc)
} else if (!isNullOrEmpty(text)) {
ui.location.setText(text)
ui.clear.visibility = VISIBLE
}
val position = state.getInt(TEXT_POSITION)
ui.location.setSelection(position)
// replace state by super state
super.onRestoreInstanceState(state.getParcelable(SUPER_STATE))
} else {
super.onRestoreInstanceState(state)
}
}
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
// Makes sure that the state of the child views are not saved
super.dispatchFreezeSelfOnly(container)
}
override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
// Makes sure that the state of the child views are not restored
super.dispatchThawSelfOnly(container)
}
fun setTransportNetwork(transportNetwork: TransportNetwork) {
this.transportNetwork = transportNetwork
}
fun setHomeLocation(homeLocation: HomeLocation?) {
adapter.setHomeLocation(homeLocation)
}
fun setWorkLocation(workLocation: WorkLocation?) {
adapter.setWorkLocation(workLocation)
}
fun setFavoriteLocations(favoriteLocations: List<FavoriteLocation>) {
adapter.setFavoriteLocations(favoriteLocations)
}
/* Auto-Completion */
private fun handleTextChanged(s: CharSequence) {
// show clear button
if (s.isNotEmpty()) {
ui.clear.visibility = VISIBLE
// clear location tag
setLocation(null, R.drawable.ic_location, false)
if (s.length >= TYPING_THRESHOLD) {
onContentChanged()
}
} else {
clearLocationAndShowDropDown(false)
}
}
private fun onContentChanged() {
ui.progress.visibility = VISIBLE
startSuggestLocationsTaskDelayed()
}
private fun startSuggestLocationsTaskDelayed() {
if (transportNetwork == null) {
stopSuggestLocationsTask()
return
}
if (suggestLocationsTaskPending) return
suggestLocationsTaskPending = true
postDelayed({
if (task != null && task!!.status != FINISHED) task!!.cancel(true)
task = SuggestLocationsTask(transportNetwork!!, this@LocationView)
task!!.execute(text)
suggestLocationsTaskPending = false
}, AUTO_COMPLETION_DELAY.toLong())
}
override fun onSuggestLocationsResult(suggestLocationsResult: SuggestLocationsResult?) {
ui.progress.visibility = GONE
if (suggestLocationsResult == null) return
adapter.swapSuggestedLocations(suggestLocationsResult.suggestedLocations, ui.location.text.toString())
}
private fun stopSuggestLocationsTask() {
if (task != null) task!!.cancel(true)
ui.progress.visibility = GONE
}
/* Setter and Getter */
open fun setLocation(loc: WrapLocation?, @DrawableRes icon: Int, setText: Boolean) {
location = loc
if (setText) {
if (loc != null) {
ui.location.setText(loc.getName())
ui.location.setSelection(loc.getName().length)
ui.location.dismissDropDown()
ui.clear.visibility = VISIBLE
stopSuggestLocationsTask()
} else {
if (ui.location.text.isNotEmpty()) ui.location.text = null
ui.clear.visibility = GONE
}
}
ui.status.setImageResource(icon)
}
fun setLocation(loc: WrapLocation?) {
setLocation(loc, loc?.drawable ?: R.drawable.ic_location, true)
}
fun getLocation(): WrapLocation? {
return this.location
}
fun setHint(@StringRes hint: Int) {
ui.location.setHint(hint)
}
/* Behavior */
private fun onFocusChange(v: View, hasFocus: Boolean) {
if (v is AutoCompleteTextView && ViewCompat.isAttachedToWindow(v)) {
if (hasFocus) {
v.showDropDown()
} else {
hideSoftKeyboard()
}
}
}
private fun onLocationItemClick(loc: WrapLocation) {
setLocation(loc) // TODO set via ViewModel
ui.location.requestFocus()
// hide soft-keyboard
hideSoftKeyboard()
if (listener != null) listener!!.onLocationItemClick(loc, type)
}
fun onClick() {
if (adapter.count > 0) {
ui.location.showDropDown()
}
}
fun clearLocation() {
clearLocation(true)
}
private fun clearLocation(setText: Boolean) {
setLocation(null, R.drawable.ic_location, setText)
adapter.resetSearchTerm()
}
protected open fun clearLocationAndShowDropDown(setText: Boolean) {
clearLocation(setText)
stopSuggestLocationsTask()
reset()
if (listener != null) listener!!.onLocationCleared(type)
ui.clear.visibility = GONE
if (isShown) {
showSoftKeyboard()
ui.location.requestFocus()
ui.location.post { ui.location.showDropDown() }
}
}
fun reset() {
adapter.reset()
}
private fun showSoftKeyboard() {
val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(ui.location, 0)
}
private fun hideSoftKeyboard() {
val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(ui.location.windowToken, 0)
}
/* Listener */
fun setLocationViewListener(listener: LocationViewListener) {
this.listener = listener
}
interface LocationViewListener {
fun onLocationItemClick(loc: WrapLocation, type: FavLocationType)
fun onLocationCleared(type: FavLocationType)
}
}
| gpl-3.0 | 97f53153bf00db761c10a6bdfff64e2b | 33.261111 | 129 | 0.653073 | 4.751156 | false | false | false | false |
erubit-open/platform | erubit.learning/src/main/java/a/erubit/platform/learning/lesson/PhraseLesson.kt | 1 | 1114 | package a.erubit.platform.learning.lesson
import a.erubit.platform.course.Course
import a.erubit.platform.course.lesson.BunchLesson
import u.U
import java.util.*
class PhraseLesson constructor(course: Course) : CharacterLesson(course) {
private val mRandom: Random = Random()
private val mApxSize: Int = 3 + mRandom.nextInt(3)
override val rankFamiliar: Int
get() = 1
override val rankLearned: Int
get() = 2
override val rankLearnedWell: Int
get() = 3
override fun getPresentable(problemItem: BunchLesson.Item): PresentableDescriptor {
if (problemItem !is Item)
return PresentableDescriptor.ERROR
val problem = Problem(this, problemItem)
val words = U.defurigana(problem.meaning).split("\\s+").toTypedArray()
problem.variants = arrayOfNulls(words.size + mApxSize)
System.arraycopy(words, 0, problem.variants, 0, words.size)
val variants = mNoise ?: return PresentableDescriptor.ERROR
for (k in 0 until mApxSize)
problem.variants[words.size + k] = variants[mRandom.nextInt(variants.size)]
U.shuffleStrArray(problem.variants)
return PresentableDescriptor(problem)
}
}
| gpl-3.0 | b82f8fc6b957face9451d8eb6952478d | 27.564103 | 84 | 0.756732 | 3.427692 | false | false | false | false |
hzsweers/palettehelper | palettehelper/src/main/java/io/sweers/palettehelper/ui/PaletteDetailActivity.kt | 1 | 24515 | package io.sweers.palettehelper.ui
import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.preference.PreferenceManager
import android.support.v4.app.ActivityCompat
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.support.v7.app.AppCompatActivity
import android.support.v7.graphics.Palette
import android.support.v7.graphics.Palette.Swatch
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.support.v8.renderscript.Allocation
import android.support.v8.renderscript.Element
import android.support.v8.renderscript.RenderScript
import android.support.v8.renderscript.ScriptIntrinsicBlur
import android.util.Pair
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import butterknife.bindView
import com.afollestad.materialdialogs.GravityEnum
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.Theme
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import io.sweers.palettehelper.PaletteHelperApplication
import io.sweers.palettehelper.R
import io.sweers.palettehelper.ui.widget.ElasticDragDismissFrameLayout
import io.sweers.palettehelper.util.*
import io.sweers.rxpalette.asObservable
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber
import java.util.*
@Suppress("NOTHING_TO_INLINE")
class PaletteDetailActivity : AppCompatActivity() {
val draggableFrame: ElasticDragDismissFrameLayout by bindView(R.id.draggable_frame)
val backButton: ImageView by bindView(R.id.back)
val imageViewContainer: FrameLayout by bindView(R.id.image_view_container)
val imageView: ImageView by bindView(R.id.image_view)
val imageViewBackground: ImageView by bindView(R.id.image_view_background)
val recyclerView: RecyclerView by bindView(R.id.grid_view)
companion object {
val KEY_URI = "uri_path"
val KEY_CAMERA = "camera"
val DEFAULT_NUM_COLORS = 16
}
var active = true;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_palette_detail)
Timber.d("Starting up DetailActivity")
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_ENTER, ANALYTICS_NAV_DETAIL)
backButton.setOnClickListener { finish() }
backButton.setBackgroundDrawable(createColorSelector(Color.WHITE))
draggableFrame.addListener(object: ElasticDragDismissFrameLayout.SystemChromeFader(window) {
override fun onDragDismissed() {
[email protected]()
}
})
Timber.d("Reading intent.")
val intent = intent
val action = intent.action
val type: String? = intent.type
var imageUri: String? = null
when {
Intent.ACTION_SEND == action && (type?.startsWith("image/") ?: false) -> {
Timber.d("Received via app share, trying to resolve uri")
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_SHARE, ANALYTICS_NAV_DETAIL)
imageUri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM).toString()
}
intent.hasExtra(KEY_URI) -> {
Timber.d("Uri specified, trying to decode file")
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_INTERNAL, ANALYTICS_NAV_DETAIL)
imageUri = intent.getStringExtra(KEY_URI)
}
intent.hasExtra(KEY_CAMERA) -> {
Timber.d("Path specified, trying to decode file")
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_CAMERA, ANALYTICS_NAV_DETAIL)
imageUri = "file://${intent.getStringExtra(KEY_CAMERA)}"
}
Intent.ACTION_SEND == action -> {
Timber.d("Received URL, trying to download")
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_URL, ANALYTICS_NAV_DETAIL)
imageUri = intent.getStringExtra(Intent.EXTRA_TEXT);
}
else -> {
errorOut()
}
}
if (imageUri != null) {
val dialog = MaterialDialog.Builder(this)
.content(R.string.detail_loading_image)
.theme(Theme.LIGHT)
.progress(true, 0)
.cancelListener { finish() }
.build()
val runnable: Runnable = Runnable { if (active) dialog.show() }
val handler = Handler(Looper.getMainLooper());
handler.postDelayed(runnable, 500) // Wait half a second before showing the dialog to avoid flashing effect if it loads fast
Glide.with(this)
.load(imageUri)
.listener(object : RequestListener<String, GlideDrawable> {
override fun onResourceReady(resource: GlideDrawable?, model: String?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
handler.removeCallbacks(runnable)
val loadedImage = getGlideBitmap(resource)
if (loadedImage == null) {
errorOut()
return false
}
imageViewContainer.setOnClickListener {
val photoIntent = Intent(this@PaletteDetailActivity, PhotoActivity::class.java)
photoIntent.putExtra(PhotoActivity.EXTRA_URI, imageUri)
ActivityCompat.startActivity(this@PaletteDetailActivity, photoIntent, ActivityOptionsCompat.makeSceneTransitionAnimation(this@PaletteDetailActivity).toBundle())
}
if (dialog.isShowing) {
dialog.dismiss()
}
if (PreferenceManager.getDefaultSharedPreferences(this@PaletteDetailActivity).getBoolean("pref_key_default", true)) {
display(loadedImage, DEFAULT_NUM_COLORS)
} else {
Timber.d("Prompting for number of colors first")
promptForNumColors(loadedImage)
}
return false
}
override fun onException(e: Exception?, model: String?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean {
Timber.e("Invalid imageUri: %s", e?.message)
errorOut()
return false
}
})
.fitCenter()
.crossFade()
.into(imageView)
} else {
Timber.e("Invalid imageUri")
errorOut()
}
}
override fun onResume() {
super.onResume()
active = true
}
override fun onPause() {
super.onPause()
active = false
}
/**
* Errors end up here, where we log it and let the user know before exiting the activity.
*/
private fun errorOut() {
Timber.e("Given an intent, but we can't do anything with the provided info.")
Toast.makeText(this, getString(R.string.detail_invalid_input), Toast.LENGTH_SHORT).show()
finish()
}
/**
* If the user disables the default color count, the detail activity will route to this to
* prompt the user to input the number of colors.
*
* @param bitmap the image bitmap to eventually feed into Palette.
*/
private fun promptForNumColors(bitmap: Bitmap) {
val inputView = View.inflate(this, R.layout.colors_prompt, null);
val input = inputView.findViewById(R.id.et) as EditText
MaterialDialog.Builder(this)
.title(R.string.dialog_num_colors)
.customView(inputView, true)
.positiveText(R.string.dialog_generate)
.negativeText(R.string.dialog_cancel)
.neutralText(R.string.dialog_default)
.autoDismiss(false)
.theme(Theme.LIGHT)
.onPositive { dialog, dialogAction ->
var isValid: Boolean
val inputText: String = input.text.toString()
var number = DEFAULT_NUM_COLORS
try {
number = java.lang.Integer.parseInt(inputText)
if (number < 1) {
input.error = getString(R.string.detail_must_be_greater_than_one)
isValid = false
} else {
isValid = true
}
} catch (e: Exception) {
input.error = getString(R.string.detail_invalid_input)
isValid = false
}
if (isValid) {
display(bitmap, number)
dialog.dismiss()
PaletteHelperApplication.mixPanel.trackMisc(ANALYTICS_KEY_NUMCOLORS, number.toString())
}
}
.onNegative { dialog, dialogAction ->
dialog.dismiss()
finish()
}
.onNeutral { dialog, dialogAction ->
dialog.dismiss()
display(bitmap, DEFAULT_NUM_COLORS)
}
.cancelListener({dialog ->
dialog.dismiss()
finish()
})
.show()
}
/**
*
*/
private fun display(bitmap: Bitmap, numColors: Int = 16) {
Observable
.zip(generatePalette(bitmap, numColors), blur(bitmap),
{ palette, blurredBitmap -> Pair(palette, blurredBitmap) })
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { displayData ->
// Set blurred bitmap
imageViewBackground.setImageBitmap(displayData.second)
// Set up palette data
val palette = displayData.first
Timber.d("Palette generation done with ${palette.swatches.size} colors extracted of $numColors requested")
val swatches = ArrayList(palette.primarySwatches())
swatches.addAll(palette.uniqueSwatches())
val isDark: Boolean
val lightness = isDark(palette)
if (lightness == Lightness.UNKNOWN) {
isDark = isDark(bitmap, bitmap.width / 2, 0)
} else {
isDark = lightness == Lightness.DARK
}
if (!isDark) {
// make back icon dark on light images
backButton.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// color the status bar. Set a complementary dark color on L,
// light or dark color on M (with matching status bar icons)
var statusBarColor = window.statusBarColor
val topColor = getMostPopulousSwatch(palette)
if (topColor != null && (isDark || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)) {
statusBarColor = scrimify(topColor.rgb, isDark, SCRIM_ADJUSTMENT)
// set a light status bar on M+
if (!isDark) {
setLightStatusBar(imageViewContainer)
}
}
if (statusBarColor != window.statusBarColor) {
ValueAnimator.ofArgb(window.statusBarColor, statusBarColor).apply {
addUpdateListener { animation -> window.statusBarColor = animation.animatedValue as Int }
duration = 1000
interpolator = FastOutSlowInInterpolator()
start()
}
}
}
Timber.d("Setting up adapter with swatches")
recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
recyclerView.isNestedScrollingEnabled = false
val adapter = ResultsAdapter(swatches)
recyclerView.adapter = adapter
}
}
/**
* Blurring function that returns an observable of blurring a bitmap
*/
private fun blur(srcBitmap: Bitmap): Observable<Bitmap> {
if (srcBitmap.width < 1 || srcBitmap.height < 1) {
// Bitmap exists but has no actual size, nothing to blur.
return Observable.empty();
}
var bitmap: Bitmap? = srcBitmap;
// simulate a larger blur radius by downscaling the input image, as high radii are computationally very heavy
bitmap = downscaleBitmap(bitmap, srcBitmap.width, srcBitmap.height, 250);
bitmap ?: return Observable.empty()
return Observable.create<Bitmap> { subscriber ->
val rs: RenderScript = RenderScript.create(this)
val input: Allocation = Allocation.createFromBitmap(
rs,
bitmap,
Allocation.MipmapControl.MIPMAP_NONE,
Allocation.USAGE_SCRIPT
)
val output: Allocation = Allocation.createTyped(rs, input.type)
ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)).apply {
setRadius(25f)
setInput(input)
forEach(output)
}
output.copyTo(bitmap)
subscriber.onNext(bitmap)
}
}
/**
* Consolidated downscale function for Bitmaps. Tiny bitmaps sometimes downscale to the point
* where they have a width or height less than 0, causing the whole process to barf. To avoid
* the mess, we wrap it in a try/catch.
*
* @param bitmap Source bitmap
* @param srcWidth Source width
* @param srcHeight Source height
* @param radius Initially requested blur radius
* @return Downscaled bitmap if it worked, null if cleanup on aisle 5
*/
private fun downscaleBitmap(bitmap: Bitmap?, srcWidth: Int, srcHeight: Int, radius: Int): Bitmap? {
try {
val destWidth: Int = (25f / radius * srcWidth).toInt()
val destHeight: Int = (25f / radius * srcHeight).toInt()
if (destWidth < 1 || destHeight < 1) {
// Uh oh
return null;
}
return Bitmap.createScaledBitmap(
bitmap,
(25f / radius * srcWidth).toInt(),
(25f / radius * srcHeight).toInt(),
true
);
} catch (e: RuntimeException) {
// (╯°□°)╯︵ ┻━┻
return null;
}
}
/**
* This is where the actual palette generation happens. Once the library calls back with the generated
* palette, the gridview's list adapter is updated with the standard colors prefixed to a list
* of *all* the colors.
*
* @param bitmap the image bitmap to feed into Palette
* @param numColors the number of colors to generate, defaulting to 16
*/
private fun generatePalette(bitmap: Bitmap, numColors: Int = 16): Observable<Palette> {
return Palette.Builder(bitmap)
.clearFilters()
.maximumColorCount(numColors)
.asObservable()
.doOnSubscribe { Timber.d("Generating palette") }
}
override fun onDestroy() {
PaletteHelperApplication.mixPanel.flush()
super.onDestroy()
}
private inner class ResultsAdapter(private val swatches: List<Swatch?>) : RecyclerView.Adapter<ViewHolder>() {
val VIEW_TYPE_HEADER = 0
val VIEW_TYPE_SWATCH = 1
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position == 0 || position == 7) {
// Header
val layoutParams: StaggeredGridLayoutManager.LayoutParams = holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams;
layoutParams.isFullSpan = true;
val text: String
if (position == 0) {
text = getString(R.string.detail_primary_swatches)
} else {
text = getString(R.string.detail_all_swatches)
}
(holder.itemView as TextView).text = text
} else {
if (position < swatches.size) {
val swatch = getItem(getAdjustedSwatchPosition(position))
if (swatch == null) {
holder.text?.text = getString(R.string.detail_no_swatch, swatchNames[getAdjustedSwatchPosition(position)])
holder.text?.setTextColor(Color.parseColor("#ADADAD"))
holder.itemView.setBackgroundColor(Color.parseColor("#252626"))
holder.itemView.isEnabled = false
holder.itemView.setOnClickListener(null)
} else {
var backgroundColor = swatch.rgb
if (backgroundColor == Color.TRANSPARENT) {
// Can't have transparent backgrounds apparently? I get crash reports for this
backgroundColor = Color.parseColor("#252626")
}
holder.itemView.setBackgroundColor(backgroundColor)
holder.text?.setTextColor(swatch.titleTextColor)
val hex = swatch.rgb.hex()
val adjustedPosition = getAdjustedSwatchPosition(position)
if (adjustedPosition < 6) {
holder.text?.text = "${swatchNames[adjustedPosition]}\n$hex"
} else {
holder.text?.text = hex
}
holder.itemView.isEnabled = true
holder.itemView.setOnClickListener { v -> onItemClick(adjustedPosition, swatch) }
}
holder.itemView.visibility = View.VISIBLE
} else {
holder.itemView.visibility = View.GONE
}
}
}
override fun getItemCount(): Int {
return swatches.size
}
override fun getItemViewType(position: Int): Int {
if (position == 0 || position == 7) {
return VIEW_TYPE_HEADER
} else {
return VIEW_TYPE_SWATCH
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder? {
var holder: ViewHolder
if (viewType == VIEW_TYPE_HEADER) {
val textView = layoutInflater.inflate(R.layout.header_row, parent, false) as TextView
textView.gravity = Gravity.START
holder = ViewHolder(textView)
} else {
val view = layoutInflater.inflate(R.layout.swatch_cell, parent, false)
holder = ViewHolder(view)
holder.text = view.findViewById(R.id.hex) as TextView
}
return holder
}
private val swatchNames = resources.getStringArray(R.array.swatches)
private fun getAdjustedSwatchPosition(position: Int) : Int {
when {
position > 0 && position < 7 -> return position - 1
else -> return position - 2
}
}
fun getItem(position: Int): Swatch? {
return swatches[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
fun onItemClick(position: Int, swatch: Swatch) {
Timber.d("Swatch item clicked")
val title = if (position < 6) swatchNames[position] else getString(R.string.detail_lorem)
MaterialDialog.Builder(this@PaletteDetailActivity)
.theme(if (swatch.isLightColor()) Theme.LIGHT else Theme.DARK)
.titleGravity(GravityEnum.CENTER)
.titleColor(swatch.titleTextColor)
.title(title)
.backgroundColor(swatch.rgb)
.contentColor(swatch.bodyTextColor)
.content(R.string.detail_lorem_full)
.positiveText(R.string.dialog_done)
.positiveColor(swatch.bodyTextColor)
.neutralText(R.string.dialog_values)
.neutralColor(swatch.bodyTextColor)
.onPositive { dialog, dialogAction -> dialog.dismiss() }
.onNeutral { dialog, dialogAction ->
dialog.dismiss()
showValues(swatch)
}
.show()
}
private fun showValues(swatch: Swatch) {
Timber.d("Showing values")
val items = getString(
R.string.dialog_values_list,
swatch.rgb.hex(),
swatch.titleTextColor.hex(),
swatch.bodyTextColor.hex(),
swatch.hsl[0],
swatch.hsl[1],
swatch.hsl[2],
swatch.population)
.split("\n")
MaterialDialog.Builder(this@PaletteDetailActivity)
.theme(if (swatch.isLightColor()) Theme.LIGHT else Theme.DARK)
.backgroundColor(swatch.rgb)
.contentColor(swatch.bodyTextColor)
.items(*items.toTypedArray())
.itemsCallback({ dialog, view, position, value ->
when (position) {
0 -> copyAndNotify(this@PaletteDetailActivity, swatch.rgb.hex())
1 -> copyAndNotify(this@PaletteDetailActivity, swatch.titleTextColor.hex())
2 -> copyAndNotify(this@PaletteDetailActivity, swatch.bodyTextColor.hex())
3 -> copyAndNotify(this@PaletteDetailActivity, swatch.hsl[0].toString())
4 -> copyAndNotify(this@PaletteDetailActivity, swatch.hsl[1].toString())
5 -> copyAndNotify(this@PaletteDetailActivity, swatch.hsl[2].toString())
6 -> copyAndNotify(this@PaletteDetailActivity, swatch.population.toString())
}
dialog?.dismiss()
})
.forceStacking(true)
.positiveText(R.string.dialog_copy_all)
.positiveColor(swatch.bodyTextColor)
.onPositive { dialog, dialogAction ->
copyAndNotify(this@PaletteDetailActivity, swatch.toString())
dialog.dismiss()
}
.show()
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var text: TextView? = null
}
}
| apache-2.0 | bd83aa657092e2cfdf998902fe7d14c5 | 43.218412 | 192 | 0.551945 | 5.268172 | false | false | false | false |
Legosteen11/simple-db-client | src/main/kotlin/io/github/legosteen11/simpledbclient/client/SimpleDatabaseClient.kt | 1 | 3100 | package io.github.legosteen11.simpledbclient.client
import io.github.legosteen11.simpledbclient.IDatabaseClient
import io.github.legosteen11.simpledbclient.getFirstValue
import io.github.legosteen11.simpledbclient.getJdbcUrl
import io.github.legosteen11.simpledbclient.prepareStatement
import java.sql.Connection
import java.sql.ResultSet
/**
* Simple database client that uses a plain JDBC connection.
*
* @param host The host name or ip-address of the database
* @param username The database username
* @param password The database password
* @param database The database name
* @param port The database port (default for MySQL, = 3306)
* @param driverName The driver name for creating the JDBC url (default for MySQL, = mysql)
* @param jdbcUrl The JDBC url (default with your credentials, = jdbc:[driverName]://[host]:[port]/[database])
*/
class SimpleDatabaseClient(host: String, username: String, password: String, database: String, port: String = "3306", driverName: String = "mysql", jdbcUrl: String = getJdbcUrl(host, port, database, driverName)) : IDatabaseClient {
private val connection = java.sql.DriverManager.getConnection(jdbcUrl, username, password)
override fun getConnection(): Connection = connection
override fun executeQuery(sql: String, vararg parameters: Any?): ResultSet = getConnection().prepareStatement(sql, *parameters).executeQuery()
override fun executeUpdate(sql: String, vararg parameters: Any?, returnGeneratedKeys: Int?): Int {
getConnection().prepareStatement(sql, *parameters, returnGeneratedKeys = returnGeneratedKeys).let {
val rowsChanged = it.executeUpdate()
if (returnGeneratedKeys == null) {
return rowsChanged
} else {
it.generatedKeys.let {
if(it.next()) {
return it.getInt(1)
} else
return -1
}
}
}
}
override fun getSingleValueQuery(sql: String, vararg parameters: Any?): Any? = executeQuery(sql, *parameters).getFirstValue()
override fun disconnect() {
connection.close()
}
override fun executeBatchUpdate(sql: String, vararg parameterArray: Array<Any?>, returnGeneratedKeys: Int?): Array<Int> {
val statement = (if (returnGeneratedKeys == null) getConnection().prepareStatement(sql) else getConnection().prepareStatement(sql, returnGeneratedKeys)).apply {
parameterArray.forEach {
it.forEachIndexed { index, value ->
setObject(index+1, value)
}
addBatch()
}
}
val rowsChanged = statement.executeBatch().toTypedArray()
if(returnGeneratedKeys == null) {
return rowsChanged
} else {
val genKeys = arrayListOf<Int>()
statement.generatedKeys.let {
while (it.next()) {
genKeys.add(it.getInt(1))
}
}
return genKeys.toTypedArray()
}
}
}
| mit | 4cd11f2304c9fadf79b714b9219dbdf7 | 39.25974 | 231 | 0.646452 | 4.711246 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/RPKCharacterSwitchListener.kt | 1 | 1365 | package com.rpkit.professions.bukkit.listener
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterSwitchEvent
import com.rpkit.core.service.Services
import com.rpkit.professions.bukkit.profession.RPKProfessionService
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import java.util.concurrent.CompletableFuture
class RPKCharacterSwitchListener : Listener {
@EventHandler
fun onCharacterSwitch(event: RPKBukkitCharacterSwitchEvent) {
val oldCharacter = event.fromCharacter
val newCharacter = event.character
val professionService = Services[RPKProfessionService::class.java] ?: return
if (oldCharacter != null) {
val professions = professionService.getProfessions(oldCharacter).join()
professions.forEach { profession ->
professionService.unloadProfessionExperience(oldCharacter, profession)
}
professionService.unloadProfessions(oldCharacter)
}
if (newCharacter != null) {
professionService.loadProfessions(newCharacter).thenAccept { professions ->
CompletableFuture.allOf(*professions.map { profession ->
professionService.loadProfessionExperience(newCharacter, profession)
}.toTypedArray()).join()
}.join()
}
}
} | apache-2.0 | d836f896f7bcb0c1ac8bd4248f5c3f89 | 40.393939 | 88 | 0.709158 | 5.229885 | false | false | false | false |
wayfair/gists | android/anko_blogpost/Userlist/app/src/main/java/com/wayfair/userlist/ui/HomeRecyclerAdapter.kt | 1 | 2720 | package com.wayfair.userlist.ui
import android.util.TimingLogger
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.wayfair.userlist.R
import com.wayfair.userlist.data.UsersListDataModel
import org.jetbrains.anko.find
class HomeRecyclerAdapter : RecyclerView.Adapter<HomeRecyclerAdapter.ListViewHolder>() {
private val users = UsersListDataModel(mutableListOf())
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val timings = TimingLogger(HomeRecyclerAdapter::class.java.simpleName, "onCreateViewHolder")
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.image_text_view_holder, parent, false)
timings.addSplit("onCreateViewHolder done")
timings.dumpToLog()
return ListViewHolder(itemView)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
holder.bind(users.usersList[position])
}
override fun getItemCount(): Int {
return users.usersList.size
}
fun updateList(usersListDataModel: UsersListDataModel) {
this.users.usersList.addAll(usersListDataModel.usersList)
notifyDataSetChanged()
}
class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val profileImage: ImageView = itemView.find(R.id.profile_circle_image_viewholder)
private var profileText: TextView = itemView.find(R.id.profile_text_viewholder)
private val nodeText: TextView = itemView.find(R.id.node_id_text_viewholder)
private val siteAdminText: TextView = itemView.find(R.id.site_admin_text_viewholder)
private val urlText: TextView = itemView.find(R.id.url_text_viewholder)
private val htmlUrlText: TextView = itemView.find(R.id.html_url_id_text_viewholder)
private val typeIdText: TextView = itemView.find(R.id.type_id_text_viewholder)
fun bind(user: UsersListDataModel.UserDataModel) {
profileImage.let {
Glide.with(profileImage.context)
.load(user.avatar_url)
.apply(RequestOptions.circleCropTransform())
.into(it)
}
profileText.text = "${user.login} ${user.id}"
nodeText.text = user.node_id
siteAdminText.text = "Site admin: ${user.site_admin}"
urlText.text = user.url
htmlUrlText.text = user.html_url
typeIdText.text = user.type
}
}
} | mit | 274ca67dfb326631eab0773ac471401c | 39.61194 | 114 | 0.704412 | 4.324324 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/tables/CachedDiscordUsers.kt | 1 | 317 | package net.perfectdreams.loritta.morenitta.tables
object CachedDiscordUsers : SnowflakeTable() {
val name = text("name").index()
val discriminator = text("discriminator").index()
val avatarId = text("avatar_id").nullable()
val createdAt = long("created_at").index()
val updatedAt = long("updated_at").index()
} | agpl-3.0 | 9799847a0b7ae495b7ef8ba79b250508 | 34.333333 | 50 | 0.731861 | 3.77381 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/sync/MessengerShortcuts.kt | 1 | 4041 | package me.proxer.app.chat.prv.sync
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutManager
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.Person
import androidx.core.content.getSystemService
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import me.proxer.app.MainActivity
import me.proxer.app.R
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.PrvMessengerActivity
import me.proxer.app.util.Utils
import me.proxer.app.util.extension.safeInject
import me.proxer.library.util.ProxerUrls
import kotlin.math.min
/**
* @author Ruben Gees
*/
object MessengerShortcuts {
private const val SHARE_TARGET_CATEGORY = "me.proxer.app.sharingshortcuts.category.TEXT_SHARE_TARGET"
private val messengerDao by safeInject<MessengerDao>()
fun updateShareTargets(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val componentName = ComponentName(context, MainActivity::class.java)
val shortcutsLeft = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
val shortcutManager = requireNotNull(context.getSystemService<ShortcutManager>())
val maxShortcuts = ShortcutManagerCompat.getMaxShortcutCountPerActivity(context)
val usedShortcuts = shortcutManager.dynamicShortcuts.plus(shortcutManager.manifestShortcuts)
.filterNot { it.categories == setOf(SHARE_TARGET_CATEGORY) }
.count { shortcutInfo -> shortcutInfo.activity == componentName }
min(4, maxShortcuts - usedShortcuts)
} else {
2
}
val newShortcuts = messengerDao.getMostRecentConferences(shortcutsLeft).map {
val icon = IconCompat.createWithBitmap(getConferenceIcon(context, it))
val intent = PrvMessengerActivity.getIntent(context, it.id.toString()).setAction(Intent.ACTION_DEFAULT)
ShortcutInfoCompat.Builder(context, it.id.toString())
.setShortLabel(it.topic)
.setIcon(icon)
.setIntent(intent)
.setCategories(setOf(SHARE_TARGET_CATEGORY))
.apply {
if (!it.isGroup) {
setPerson(
Person.Builder()
.setName(it.topic)
.setIcon(icon)
.setUri(ProxerUrls.webBase.newBuilder("/messages?id=${it.id}").toString())
.setKey(it.id.toString())
.build()
)
}
}
.build()
}
val needsUpdate = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
val shortcutManager = requireNotNull(context.getSystemService<ShortcutManager>())
newShortcuts.map { it.id } != shortcutManager.dynamicShortcuts.map { it.id }
} else {
true
}
if (needsUpdate) {
ShortcutManagerCompat.removeAllDynamicShortcuts(context)
ShortcutManagerCompat.addDynamicShortcuts(context, newShortcuts)
}
}
}
private fun getConferenceIcon(context: Context, conference: LocalConference) = when {
conference.image.isNotBlank() -> Utils.getCircleBitmapFromUrl(
context,
ProxerUrls.userImage(conference.image)
)
conference.isGroup -> BitmapFactory.decodeResource(context.resources, R.drawable.ic_shortcut_messenger_group)
else -> BitmapFactory.decodeResource(context.resources, R.drawable.ic_shortcut_messenger_person)
}
}
| gpl-3.0 | 0fefbf870a081a51111e3dfb695aab4a | 41.536842 | 119 | 0.620638 | 5.019876 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/callbacks/PostPerfectPaymentsCallbackRoute.kt | 1 | 12660 | package net.perfectdreams.loritta.morenitta.website.routes.api.v1.callbacks
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.long
import com.github.salomonbrys.kotson.nullLong
import com.github.salomonbrys.kotson.nullString
import com.github.salomonbrys.kotson.obj
import com.github.salomonbrys.kotson.string
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import net.perfectdreams.loritta.morenitta.dao.DonationKey
import net.perfectdreams.loritta.morenitta.utils.Constants
import io.ktor.server.application.*
import io.ktor.http.*
import io.ktor.server.request.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.cinnamon.pudding.tables.SonhosTransactionsLog
import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.SonhosBundlePurchaseSonhosTransactionsLog
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.dao.Payment
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.tables.BannedUsers
import net.perfectdreams.loritta.morenitta.tables.Payments
import net.perfectdreams.loritta.morenitta.tables.SonhosBundles
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.PaymentUtils
import net.perfectdreams.loritta.morenitta.utils.SonhosPaymentReason
import net.perfectdreams.loritta.morenitta.utils.payments.PaymentReason
import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson
import net.perfectdreams.sequins.ktor.BaseRoute
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.select
import java.awt.Color
import java.time.Instant
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import kotlin.collections.set
class PostPerfectPaymentsCallbackRoute(val loritta: LorittaBot) : BaseRoute("/api/v1/callbacks/perfect-payments") {
companion object {
private val logger = KotlinLogging.logger {}
suspend fun sendPaymentApprovedDirectMessage(loritta: LorittaBot, userId: Long, locale: BaseLocale, supportUrl: String) {
val user = loritta.lorittaShards.retrieveUserById(userId)
user?.openPrivateChannel()?.queue {
val embed = EmbedBuilder()
.setTitle("${Emotes.LORI_RICH} ${locale["economy.paymentApprovedNotification.title"]}")
.setDescription(
locale.getList(
"economy.paymentApprovedNotification.description",
supportUrl,
"${Emotes.LORI_HEART1}${Emotes.LORI_HEART2}",
Emotes.LORI_NICE,
Emotes.LORI_SMILE
).joinToString("\n")
)
.setImage("https://cdn.discordapp.com/attachments/513405772911345664/811320940335071263/economy_original.png")
.setColor(Color(47, 182, 92))
.setTimestamp(Instant.now())
.build()
it.sendMessageEmbeds(embed).queue()
}
}
private suspend fun retrieveSonhosBundleFromMetadata(loritta: LorittaBot, metadata: JsonObject): ResultRow? {
val metadataAsObj = metadata.obj
val bundleType = metadataAsObj["bundleType"].nullString
if (bundleType == "dreams") {
// LORI-BUNDLE-InternalTransactionId
val bundleId = metadataAsObj["bundleId"].long
val bundle = loritta.newSuspendedTransaction {
SonhosBundles.select {
// Before we checked if the bundle was active, but what if we want to add new bundles while taking out old bundles?
// If someone bought and the bundle was deactivated, when the payment was approved, the user wouldn't receive the bundle!
// So we don't care if the bundle is not active anymore.
SonhosBundles.id eq bundleId
}.firstOrNull()
} ?: return null
return bundle
}
return null
}
}
/**
* Stores the chargeback quantity made by the user
*/
private val chargebackedQuantity = ConcurrentHashMap<Long, AtomicLong>()
/**
* Stores the current active job of the chargeback process, used for cancellation
*/
private val jobs = ConcurrentHashMap<Long, Job>()
override suspend fun onRequest(call: ApplicationCall) {
loritta as LorittaBot
val sellerTokenHeader = call.request.header("Authorization")
if (sellerTokenHeader == null || loritta.config.loritta.perfectPayments.notificationToken != sellerTokenHeader) {
logger.warn { "Request Seller Token is different than what it is expected or null! Received Seller Token: $sellerTokenHeader"}
call.respondJson(jsonObject(), status = HttpStatusCode.Forbidden)
return
}
val body = withContext(Dispatchers.IO) { call.receiveText() }
val json = JsonParser.parseString(body).obj
val referenceId = UUID.fromString(json["referenceId"].string)
val gateway = json["gateway"].string
val status = json["status"].string
logger.info { "Received PerfectPayments callback: Reference ID: $referenceId; Gateway: $gateway; Status: $status" }
val internalPayment = loritta.newSuspendedTransaction {
Payment.find { Payments.referenceId eq referenceId }
.firstOrNull()
}
val internalTransactionId = internalPayment?.id?.value
if (internalPayment == null) {
logger.warn { "PerfectPayments Payment with Reference ID: $referenceId ($internalTransactionId) doesn't have a matching internal ID! Bug?" }
call.respondJson(jsonObject())
return
}
if (status == "CHARGED_BACK") {
// User charged back the payment, let's ban him!
logger.warn { "User ${internalPayment.userId} charged back the payment! Let's ban him >:(" }
val metadata = internalPayment.metadata
if (metadata != null) {
if (internalPayment.reason == PaymentReason.SONHOS_BUNDLE) {
val metadataAsObj = metadata.obj
val bundleType = metadataAsObj["bundleType"].nullString
if (bundleType == "dreams") {
// LORI-BUNDLE-InternalTransactionId
val bundle = retrieveSonhosBundleFromMetadata(loritta, metadataAsObj)
if (bundle != null) {
// If it is a sonhos bundle, we need to remove all the sonhos from the bundle to the user
// We are going to execute it in a separate task, to avoid hanging the request!
//
// However we need to keep in mind that users can buy multiple sonhos packages and then charging back all at once, so we need to have a delay waiting to get all the quantity and then process the sonhos removal.
jobs[internalPayment.userId]?.cancel()
// We use a AtomicLong to avoid concurrency issues
chargebackedQuantity[internalPayment.userId] = chargebackedQuantity.getOrPut(internalPayment.userId) { AtomicLong() }
.also { it.addAndGet(bundle[SonhosBundles.sonhos]) }
jobs[internalPayment.userId] = GlobalScope.launch(loritta.coroutineDispatcher) {
delay(300_000L) // Five minutes
// And then dispatch to a separate job, just to avoid any other cancellations causing issues after we already started removing the sonhos
GlobalScope.launch(loritta.coroutineDispatcher) {
val quantity = chargebackedQuantity[internalPayment.userId]
?.get()
chargebackedQuantity.remove(internalPayment.userId)
if (quantity != null) {
logger.info { "Starting a chargeback sonhos job for ${internalPayment.userId}, chargeback quantity: $quantity" }
PaymentUtils.removeSonhosDueToChargeback(
loritta,
internalPayment.userId,
quantity,
removeSonhos = true,
notifyChargebackUser = false,
notifyUsers = true
)
} else {
logger.warn { "Tried starting a chargeback sonhos job for ${internalPayment.userId}, but the chargeback quantity is null!" }
}
}
}
} else {
logger.warn { "PerfectPayments Payment with Reference ID: $referenceId ($internalTransactionId) does not have a valid bundle! We are still going to ban the user due to chargeback..." }
}
}
}
}
loritta.newSuspendedTransaction {
BannedUsers.insert {
it[userId] = internalPayment.userId
it[bannedAt] = System.currentTimeMillis()
it[bannedBy] = null
it[valid] = true
it[expiresAt] = null
it[reason] = "Chargeback/Requesting your money back after a purchase! Why do you pay for something and then chargeback your payment even though you received your product? Payment ID: $referenceId; Gateway: $gateway"
}
}
} else if (status == "APPROVED") {
if (internalPayment.paidAt != null) {
logger.warn { "PerfectPayments Payment with Reference ID: $referenceId ($internalTransactionId); Gateway: $gateway is already paid! Ignoring..." }
call.respondJson(jsonObject())
return
}
logger.info { "Setting Payment $internalTransactionId as paid! (via PerfectPayments payment $referenceId; Gateway: $gateway) - Payment made by ${internalPayment.userId}" }
loritta.newSuspendedTransaction {
// Pagamento aprovado!
internalPayment.paidAt = System.currentTimeMillis()
}
val metadata = internalPayment.metadata
if (metadata != null) {
val metadataAsObj = metadata.obj
val bundleType = metadataAsObj["bundleType"].nullString
if (bundleType == "dreams") {
// LORI-BUNDLE-InternalTransactionId
val bundle = retrieveSonhosBundleFromMetadata(loritta, metadataAsObj)
if (bundle == null) {
logger.warn { "PerfectPayments Payment with Reference ID: $referenceId ($internalTransactionId) does not have a valid bundle!" }
call.respondJson(jsonObject())
return
}
// TODO: Why not have a getOrCreateLorittaProfileAsync smh
val profile = loritta.getLorittaProfileAsync(internalPayment.userId) ?: loritta.getOrCreateLorittaProfile(internalPayment.userId)
loritta.newSuspendedTransaction {
profile.addSonhosAndAddToTransactionLogNested(
bundle[SonhosBundles.sonhos],
SonhosPaymentReason.BUNDLE_PURCHASE
)
val transactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = internalPayment.userId
it[SonhosTransactionsLog.timestamp] = Instant.now()
}
SonhosBundlePurchaseSonhosTransactionsLog.insert {
it[SonhosBundlePurchaseSonhosTransactionsLog.timestampLog] = transactionLogId
it[SonhosBundlePurchaseSonhosTransactionsLog.bundle] = bundle[SonhosBundles.id]
}
}
sendPaymentApprovedDirectMessage(loritta, internalPayment.userId, loritta.localeManager.getLocaleById("default"), "${loritta.config.loritta.website.url}support")
call.respondJson(jsonObject())
return
}
}
// Criação de nova key:
// LORI-DONATE-MP-InternalTransactionId
// Renovação de uma key
// LORI-DONATE-MP-RENEW-KEY-KeyId-InternalTransactionId
val isKeyRenewal = metadata != null && metadata.obj["renewKey"].nullLong != null
loritta.newSuspendedTransaction {
internalPayment.expiresAt = System.currentTimeMillis() + Constants.DONATION_ACTIVE_MILLIS
if (internalPayment.reason == PaymentReason.DONATION) {
if (isKeyRenewal) {
val donationKeyId = metadata!!.obj["renewKey"].long
logger.info { "Renewing key $donationKeyId with value ${internalPayment.money.toDouble()} for ${internalPayment.userId}" }
val donationKey = DonationKey.findById(donationKeyId)
if (donationKey == null) {
logger.warn { "Key renewal for key $donationKeyId for ${internalPayment.userId} failed! Key doesn't exist! Bug?" }
return@newSuspendedTransaction
}
donationKey.expiresAt += 2_764_800_000 // 32 dias
internalPayment.expiresAt = donationKey.expiresAt // Fixes bug where key renewals breaks user features due to the difference in the expiration date
} else {
if (internalPayment.money > 9.99.toBigDecimal()) {
logger.info { "Creating donation key with value ${internalPayment.money.toDouble()} for ${internalPayment.userId}" }
DonationKey.new {
this.userId = internalPayment.userId
this.expiresAt = System.currentTimeMillis() + 2_764_800_000 // 32 dias
this.value = internalPayment.money.toDouble()
}
}
}
}
}
sendPaymentApprovedDirectMessage(loritta, internalPayment.userId, loritta.localeManager.getLocaleById("default"), "${loritta.config.loritta.website.url}support")
}
call.respondJson(jsonObject())
}
} | agpl-3.0 | 4f3ccb0f8cd2781daa49305d719857ec | 39.829032 | 220 | 0.733328 | 4.150869 | false | false | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/BannedUsers.kt | 1 | 389 | package net.perfectdreams.loritta.cinnamon.pudding.tables
import org.jetbrains.exposed.dao.id.LongIdTable
object BannedUsers : LongIdTable() {
val userId = long("user").index()
val valid = bool("valid").index()
val bannedAt = long("banned_at")
val expiresAt = long("expires_at").nullable()
val reason = text("reason")
val bannedBy = long("banned_by").nullable()
} | agpl-3.0 | 20a0a5d5287ae2e8b27860c6d490b53b | 31.5 | 57 | 0.694087 | 3.740385 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterHolder.kt | 3 | 5306 | package eu.kanade.tachiyomi.ui.recent_updates
import android.view.View
import android.widget.PopupMenu
import com.bumptech.glide.load.engine.DiskCacheStrategy
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.glide.GlideApp
import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder
import eu.kanade.tachiyomi.util.getResourceColor
import eu.kanade.tachiyomi.util.setVectorCompat
import kotlinx.android.synthetic.main.recent_chapters_item.*
/**
* Holder that contains chapter item
* Uses R.layout.item_recent_chapters.
* UI related actions should be called from here.
*
* @param view the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @param listener a listener to react to single tap and long tap events.
* @constructor creates a new recent chapter holder.
*/
class RecentChapterHolder(private val view: View, private val adapter: RecentChaptersAdapter) :
BaseFlexibleViewHolder(view, adapter) {
/**
* Color of read chapter
*/
private var readColor = view.context.getResourceColor(android.R.attr.textColorHint)
/**
* Color of unread chapter
*/
private var unreadColor = view.context.getResourceColor(android.R.attr.textColorPrimary)
/**
* Currently bound item.
*/
private var item: RecentChapterItem? = null
init {
// We need to post a Runnable to show the popup to make sure that the PopupMenu is
// correctly positioned. The reason being that the view may change position before the
// PopupMenu is shown.
chapter_menu.setOnClickListener { it.post { showPopupMenu(it) } }
manga_cover.setOnClickListener {
adapter.coverClickListener.onCoverClick(adapterPosition)
}
}
/**
* Set values of view
*
* @param item item containing chapter information
*/
fun bind(item: RecentChapterItem) {
this.item = item
// Set chapter title
chapter_title.text = item.chapter.name
// Set manga title
manga_title.text = item.manga.title
// Set the correct drawable for dropdown and update the tint to match theme.
chapter_menu_icon.setVectorCompat(R.drawable.ic_more_horiz_black_24dp, view.context.getResourceColor(R.attr.icon_color))
// Set cover
GlideApp.with(itemView.context).clear(manga_cover)
if (!item.manga.thumbnail_url.isNullOrEmpty()) {
GlideApp.with(itemView.context)
.load(item.manga)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.circleCrop()
.into(manga_cover)
}
// Check if chapter is read and set correct color
if (item.chapter.read) {
chapter_title.setTextColor(readColor)
manga_title.setTextColor(readColor)
} else {
chapter_title.setTextColor(unreadColor)
manga_title.setTextColor(unreadColor)
}
// Set chapter status
notifyStatus(item.status)
}
/**
* Updates chapter status in view.
*
* @param status download status
*/
fun notifyStatus(status: Int) = with(download_text) {
when (status) {
Download.QUEUE -> setText(R.string.chapter_queued)
Download.DOWNLOADING -> setText(R.string.chapter_downloading)
Download.DOWNLOADED -> setText(R.string.chapter_downloaded)
Download.ERROR -> setText(R.string.chapter_error)
else -> text = ""
}
}
/**
* Show pop up menu
*
* @param view view containing popup menu.
*/
private fun showPopupMenu(view: View) = item?.let { item ->
// Create a PopupMenu, giving it the clicked view for an anchor
val popup = PopupMenu(view.context, view)
// Inflate our menu resource into the PopupMenu's Menu
popup.menuInflater.inflate(R.menu.chapter_recent, popup.menu)
// Hide download and show delete if the chapter is downloaded and
if (item.isDownloaded) {
popup.menu.findItem(R.id.action_download).isVisible = false
popup.menu.findItem(R.id.action_delete).isVisible = true
}
// Hide mark as unread when the chapter is unread
if (!item.chapter.read /*&& mangaChapter.chapter.last_page_read == 0*/) {
popup.menu.findItem(R.id.action_mark_as_unread).isVisible = false
}
// Hide mark as read when the chapter is read
if (item.chapter.read) {
popup.menu.findItem(R.id.action_mark_as_read).isVisible = false
}
// Set a listener so we are notified if a menu item is clicked
popup.setOnMenuItemClickListener { menuItem ->
with(adapter.controller) {
when (menuItem.itemId) {
R.id.action_download -> downloadChapter(item)
R.id.action_delete -> deleteChapter(item)
R.id.action_mark_as_read -> markAsRead(listOf(item))
R.id.action_mark_as_unread -> markAsUnread(listOf(item))
}
}
true
}
// Finally show the PopupMenu
popup.show()
}
} | apache-2.0 | 6b1e6d8f38548043dd7b8e04c6d96636 | 33.914474 | 128 | 0.635884 | 4.440167 | false | false | false | false |
sandeepraju/concurrency | kotlin/src/main/kotlin/io/github/sandeepraju/ThreadPoolServer.kt | 1 | 1833 | package io.github.sandeepraju
import io.github.sandeepraju.utils.Database
import io.github.sandeepraju.utils.Image
import java.net.InetAddress
import java.net.ServerSocket
import java.util.concurrent.Executors
/*
Active Object
- A proxy, which provides an interface towards clients with publicly accessible methods.
- An interface which defines the method request on an active object.
- A list of pending requests from clients.
- A scheduler, which decides which request to execute next.
- The implementation of the active object method.
- A callback or variable for the client to receive the result.
*/
class RequestProcessor {
// has an internal 'unbounded' queue which the pool will read off of
private val pool = Executors.newFixedThreadPool(2)
fun queryDatabase(query: String, cb: (String) -> Unit) {
pool.submit({
val result = Database.query(query)
cb(result)
})
}
fun processImage(path: String, cb: (String) -> Unit) {
pool.submit({
val response = Image.process(path)
cb(response)
})
}
}
class ThreadPoolServer : Server {
override fun listen(host: String, port: Int) {
println("[${this.javaClass.simpleName}] Server listening at $host:$port")
val socket = ServerSocket(port, 0, InetAddress.getByName(host))
val requestProcessor = RequestProcessor()
socket.use { socket ->
while (true) {
val connection = socket.accept() // accept the connection and submit it to the request processor
requestProcessor.processImage("/tmp/img.png") {
connection.close()
}
}
}
}
}
fun main(args: Array<String>) {
ThreadPoolServer().listen("0.0.0.0", 9999)
} | bsd-3-clause | d64de6470d09936cace943005716ebbe | 29.566667 | 113 | 0.642662 | 4.395683 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/RtpEncodingDesc.kt | 1 | 5693 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj
import org.jitsi.nlj.rtp.SsrcAssociationType
import org.jitsi.nlj.rtp.VideoRtpPacket
import org.jitsi.nlj.stats.NodeStatsBlock
/**
* Keeps track of information specific to an RTP encoded stream
* (and its associated secondary sources).
*
* @author Jonathan Lennox
*/
class RtpEncodingDesc
@JvmOverloads
constructor(
/**
* The primary SSRC for this encoding.
*/
val primarySSRC: Long,
/**
* The [RtpLayerDesc]s describing the encoding's layers.
*/
initialLayers: Array<RtpLayerDesc>,
/**
* The ID of this encoding.
*/
val eid: Int = requireNotNull(initialLayers.getOrNull(0)?.eid) {
"initialLayers may not be empty if no explicit EID is provided"
}
) {
constructor(primarySSRC: Long, eid: Int) : this(primarySSRC, arrayOf(), eid)
/**
* The ssrcs associated with this encoding (for example, RTX or FLEXFEC)
* Maps ssrc -> type [SsrcAssociationType] (rtx, etc.)
*/
private val secondarySsrcs: MutableMap<Long, SsrcAssociationType> = HashMap()
fun addSecondarySsrc(ssrc: Long, type: SsrcAssociationType) {
secondarySsrcs[ssrc] = type
}
/**
* All SSRCs (primary and secondary) associated with this encoding.
*/
val ssrcs: Collection<Long>
get() = HashSet<Long>().also { set ->
set.add(primarySSRC)
set.addAll(secondarySsrcs.keys)
}
private fun validateLayerEids(layers: Array<RtpLayerDesc>) {
for (layer in layers) {
require(layer.eid == eid) { "Cannot add layer with EID ${layer.eid} to encoding with EID $eid" }
}
}
init { validateLayerEids(initialLayers) }
internal var layers = initialLayers
set(newLayers) {
validateLayerEids(newLayers)
/* Copy the rate statistics objects from the old layers to the new layers
* with matching layer IDs.
*/
/* Note: because layer arrays are sorted by ID we could avoid creating this
* intermediate map object, and do this in a single pass in O(1) space.
* The number of layers is small enough that this more complicated code
* is probably unnecessary, though.
*/
val oldLayerMap = field.associateBy { it.layerId }
for (newLayer in newLayers) {
oldLayerMap[newLayer.layerId]?.let {
newLayer.inheritFrom(it)
}
}
field = newLayers
}
/**
* @return the "id" of a layer within this source, across all encodings. This is a server-side id and should
* not be confused with any encoding id defined in the client (such as the
* rid). This server-side id is used in the layer lookup table that is
* maintained in [MediaSourceDesc].
*/
fun encodingId(layer: RtpLayerDesc): Long =
calcEncodingId(primarySSRC, layer.layerId)
/**
* Get the secondary ssrc for this encoding that corresponds to the given
* type
* @param type the type of the secondary ssrc (e.g. RTX)
* @return the ssrc for the encoding that corresponds to the given type,
* if it exists; otherwise -1
*/
fun getSecondarySsrc(type: SsrcAssociationType): Long {
for ((key, value) in secondarySsrcs) {
if (value == type) {
return key
}
}
return -1
}
/**
* Clone an existing encoding desc, inheriting layer descs' statistics,
* modifying only specific values.
*/
fun copy(
primarySSRC: Long = this.primarySSRC,
layers: Array<RtpLayerDesc> = Array(this.layers.size) { i -> this.layers[i].copy() }
) = RtpEncodingDesc(primarySSRC, layers, eid).also {
this.secondarySsrcs.forEach { (ssrc, type) -> it.addSecondarySsrc(ssrc, type) }
}
/**
* {@inheritDoc}
*/
override fun toString(): String {
return "primary_ssrc=$primarySSRC,secondary_ssrcs=$secondarySsrcs," +
"layers=\n ${layers.joinToString(separator = "\n ")}"
}
/**
* Gets a boolean indicating whether or not the SSRC specified in the
* arguments matches this encoding or not.
*
* @param ssrc the SSRC to match.
*/
fun matches(ssrc: Long): Boolean {
return if (primarySSRC == ssrc) {
true
} else secondarySsrcs.containsKey(ssrc)
}
/**
* Extracts a [NodeStatsBlock] from an [RtpEncodingDesc].
*/
fun getNodeStats() = NodeStatsBlock(primarySSRC.toString()).apply {
addNumber("rtx_ssrc", getSecondarySsrc(SsrcAssociationType.RTX))
addNumber("fec_ssrc", getSecondarySsrc(SsrcAssociationType.FEC))
for (layer in layers) {
addBlock(layer.getNodeStats())
}
}
companion object {
fun calcEncodingId(ssrc: Long, layerId: Int) =
ssrc or (layerId.toLong() shl 32)
}
}
fun VideoRtpPacket.getEncodingId(): Long {
return RtpEncodingDesc.calcEncodingId(ssrc, this.layerId)
}
| apache-2.0 | 6e2c7a1e6012df5e6a08b574d126ef77 | 32.686391 | 112 | 0.629369 | 4.16155 | false | false | false | false |
MaTriXy/PermissionsDispatcher | processor/src/main/kotlin/permissions/dispatcher/processor/PermissionsProcessor.kt | 1 | 4479 | package permissions.dispatcher.processor
import permissions.dispatcher.RuntimePermissions
import permissions.dispatcher.processor.impl.javaProcessorUnits
import permissions.dispatcher.processor.impl.kotlinProcessorUnits
import permissions.dispatcher.processor.util.findAndValidateProcessorUnit
import permissions.dispatcher.processor.util.kotlinMetadataClass
import java.io.File
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.Element
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
import javax.tools.Diagnostic
import kotlin.properties.Delegates
/** Element Utilities, obtained from the processing environment */
var ELEMENT_UTILS: Elements by Delegates.notNull()
/** Type Utilities, obtained from the processing environment */
var TYPE_UTILS: Types by Delegates.notNull()
class PermissionsProcessor : AbstractProcessor() {
companion object {
// processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] returns generated/source/kaptKotlin/$sourceSetName
const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
}
/* Processing Environment helpers */
var filer: Filer by Delegates.notNull()
var messager: Messager by Delegates.notNull()
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
filer = processingEnv.filer
messager = processingEnv.messager
ELEMENT_UTILS = processingEnv.elementUtils
TYPE_UTILS = processingEnv.typeUtils
}
override fun getSupportedSourceVersion(): SourceVersion? {
return SourceVersion.latestSupported()
}
override fun getSupportedAnnotationTypes(): Set<String> {
return hashSetOf(RuntimePermissions::class.java.canonicalName)
}
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
// Create a RequestCodeProvider which guarantees unique request codes for each permission request
val requestCodeProvider = RequestCodeProvider()
// The Set of annotated elements needs to be ordered
// in order to achieve Deterministic, Reproducible Builds
roundEnv.getElementsAnnotatedWith(RuntimePermissions::class.java)
.sortedBy { it.simpleName.toString() }
.forEach {
val rpe = RuntimePermissionsElement(it as TypeElement)
val kotlinMetadata = it.getAnnotation(kotlinMetadataClass)
if (kotlinMetadata != null) {
processKotlin(it, rpe, requestCodeProvider)
} else {
processJava(it, rpe, requestCodeProvider)
}
}
return true
}
private fun processKotlin(element: Element, rpe: RuntimePermissionsElement, requestCodeProvider: RequestCodeProvider) {
// FIXME: weirdly under kaptKotlin files is not recognized as source file on AS or IntelliJ
// so as a workaround we generate .kt file in generated/source/kapt/$sourceSetName
// ref: https://github.com/hotchemi/PermissionsDispatcher/issues/320#issuecomment-316175775
val kaptGeneratedDirPath = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]?.replace("kaptKotlin", "kapt") ?: run {
processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, "Can't find the target directory for generated Kotlin files.")
return
}
val kaptGeneratedDir = File(kaptGeneratedDirPath)
if (!kaptGeneratedDir.parentFile.exists()) {
kaptGeneratedDir.parentFile.mkdirs()
}
val processorUnit = findAndValidateProcessorUnit(kotlinProcessorUnits(messager), element)
val kotlinFile = processorUnit.createFile(rpe, requestCodeProvider)
kotlinFile.writeTo(kaptGeneratedDir)
}
private fun processJava(element: Element, rpe: RuntimePermissionsElement, requestCodeProvider: RequestCodeProvider) {
val processorUnit = findAndValidateProcessorUnit(javaProcessorUnits(messager), element)
val javaFile = processorUnit.createFile(rpe, requestCodeProvider)
javaFile.writeTo(filer)
}
}
| apache-2.0 | dab024b538b9d3cae5f0de60b951e24f | 44.704082 | 133 | 0.732306 | 5.172055 | false | false | false | false |
macrat/RuuMusic | wear/src/main/java/jp/blanktar/ruumusic/wear/RuuClient.kt | 1 | 3532 | package jp.blanktar.ruumusic.wear
import kotlin.concurrent.thread
import android.content.Context
import android.os.Bundle
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.wearable.DataApi
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataMap
import com.google.android.gms.wearable.Wearable
class RuuClient(ctx: Context) : GoogleApiClient.ConnectionCallbacks, DataApi.DataListener {
val client = GoogleApiClient.Builder(ctx)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.build()!!
var status = Status()
set(x) {
field = x
onStatusUpdated?.invoke(x)
}
var onStatusUpdated: ((Status) -> Unit)? = null
var onFailedSendMessage: (() -> Unit)? = null
fun connect() {
client.connect()
}
fun disconnect() {
Wearable.DataApi.removeListener(client, this)
client.disconnect()
}
override fun onConnected(bundle: Bundle?) {
Wearable.DataApi.getDataItems(client).setResultCallback { items ->
for (item in items) {
if (item.uri.path == "/status") {
status = Status(DataMap.fromByteArray(item.data))
break
}
}
items.release()
}
Wearable.DataApi.addListener(client, this)
}
override fun onConnectionSuspended(cause: Int) {}
override fun onDataChanged(evs: DataEventBuffer) {
for (ev in evs) {
if (ev.type == DataEvent.TYPE_CHANGED && ev.dataItem.uri.path == "/status") {
status = Status(DataMap.fromByteArray(ev.dataItem.data))
break
}
}
evs.release()
}
fun getDirectory(dir: String): Directory? {
if (!client.isConnected) {
client.blockingConnect()
}
val items = Wearable.DataApi.getDataItems(client).await()
for (item in items) {
if (item.uri.path == "/musics" + dir) {
val map = DataMap.fromByteArray(item.data)
val musics = map.getStringArray("musics")
val dirs = map.getStringArray("dirs")
items.release()
return Directory(dir, dirs, musics)
}
}
return null
}
private fun sendMessage(path: String, message: String = "") {
thread {
for (node in Wearable.NodeApi.getConnectedNodes(client).await().nodes) {
Wearable.MessageApi.sendMessage(client, node.id, path, message.toByteArray()).setResultCallback { result ->
if (!result.status.isSuccess && !result.status.isCanceled) {
onFailedSendMessage?.invoke()
}
}
}
}
}
fun play() {
sendMessage("/control/play")
}
fun play(path: String) {
sendMessage("/control/play", path)
}
fun pause() {
sendMessage("/control/pause")
}
fun next() {
sendMessage("/control/next")
}
fun prev() {
sendMessage("/control/prev")
}
fun repeat(mode: RepeatModeType) {
sendMessage("/control/repeat", mode.name)
}
fun shuffle(mode: Boolean) {
sendMessage("/control/shuffle", if (mode) "ON" else "OFF")
}
}
| mit | afd9ec9f02879c7d939c45e292d1d66c | 26.811024 | 123 | 0.562288 | 4.545689 | false | false | false | false |
facebook/litho | litho-core-kotlin/src/main/kotlin/com/facebook/litho/animated/SequenceAnimation.kt | 1 | 2832 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.animated
import com.facebook.infer.annotation.ThreadConfined
/**
* Creates collection of animators that will run one after another in sequence when
* [SequenceAnimation.start] is triggered
*/
class SequenceAnimation(private val animators: Array<out AnimatedAnimation>) : AnimatedAnimation {
private val sequenceAnimatorListeners = mutableListOf<AnimationFinishListener>()
private var currentIndex = 0
private var _isActive: Boolean = false
init {
animators.forEach {
it.addListener(
object : AnimationFinishListener {
override fun onFinish(cancelled: Boolean) {
if (cancelled && _isActive) {
// child was cancelled, main animation is still active
cancel()
return
}
animatorFinished(cancelled)
}
})
}
}
@ThreadConfined(ThreadConfined.UI) override fun isActive(): Boolean = _isActive
@ThreadConfined(ThreadConfined.UI)
override fun start() {
check(!_isActive) { "start() called more than once" }
if (animators.isEmpty()) {
throw IllegalArgumentException("Empty animators collection")
}
_isActive = true
startAnimator()
}
@ThreadConfined(ThreadConfined.UI)
override fun cancel() {
if (!_isActive) {
// ignore multiple cancel calls
return
}
_isActive = false
if (animators[currentIndex].isActive()) {
animators[currentIndex].cancel()
}
sequenceAnimatorListeners.forEach { it.onFinish(true) }
finish()
}
override fun addListener(finishListener: AnimationFinishListener) {
if (!sequenceAnimatorListeners.contains(finishListener)) {
sequenceAnimatorListeners.add(finishListener)
}
}
private fun animatorFinished(cancelled: Boolean) {
if (!_isActive || cancelled) {
return
}
currentIndex++
if (currentIndex == animators.size) {
finish()
sequenceAnimatorListeners.forEach { it.onFinish(false) }
return
}
startAnimator()
}
private fun startAnimator() {
animators[currentIndex].start()
}
private fun finish() {
_isActive = false
currentIndex = 0
}
}
| apache-2.0 | 023c46c72068468d15cb49ba71c31309 | 27.897959 | 98 | 0.673729 | 4.673267 | false | false | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/log/Loggers.kt | 1 | 1112 | package cn.thens.kdroid.core.log
import android.util.Log
import java.io.PrintStream
import java.text.SimpleDateFormat
import java.util.*
object Loggers {
private var logcatTagPrefix = 0
fun logcat(): LineLogger {
return LineLogger { priority, tag, message ->
logcatTagPrefix = (logcatTagPrefix + 1) % 10
Log.println(priority, "$logcatTagPrefix.$tag", message)
}
}
fun from(printer: LinePrinter): LineLogger {
return object : LineLogger {
private val dateFormat = SimpleDateFormat("MM.dd HH:mm:ss.SSS", Locale.UK)
private val date = Date()
override fun log(priority: Int, tag: String, message: String) {
date.time = System.currentTimeMillis()
val time = dateFormat.format(date)
val level = LoggerUtils.getPriorityText(priority)
printer.print("[$time] $level/$tag: $message")
}
}
}
fun out(output: PrintStream = System.out): LineLogger {
return from(LinePrinter { message -> output.println(message) })
}
} | apache-2.0 | 43d0ce3c3732cb3df4cea8616809d96b | 31.735294 | 86 | 0.613309 | 4.310078 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/reportings/textIllustration.kt | 1 | 3040 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.reportings
import compiler.lexer.SourceContentAwareSourceDescriptor
import kotlin.math.min
fun SourceContentAwareSourceDescriptor.getIllustrationForHighlightedLines(desiredLineNumbers: Collection<Int>): String {
val lineContext = 0 // +- X lines of context
if (desiredLineNumbers.isEmpty()) {
throw IllegalArgumentException("No source lines given.")
}
if (desiredLineNumbers.any { it < 1 || it > sourceLines.size }) {
throw IllegalArgumentException("Source lines out of range.")
}
val desiredLineNumbersSorted = desiredLineNumbers.sorted()
val lineNumbersToOutput = mutableSetOf<Int>()
for (desiredLine in desiredLineNumbersSorted) {
lineNumbersToOutput.add(desiredLine)
for (i in 1 .. lineContext) {
lineNumbersToOutput.add(desiredLine - i)
lineNumbersToOutput.add(desiredLine + i)
}
}
val lineNumbersToOutputSorted = lineNumbersToOutput.sorted()
val lineCounterLength = min(3, lineNumbersToOutputSorted.maxOrNull()!!.toString(10).length)
val linesToOutputWithNormalizedTabs: Map<Int, String> = lineNumbersToOutputSorted.map {
it to sourceLines[it - 1].replace("\t", " ")
}.toMap()
val commonNumberOfLeadingSpaces =
linesToOutputWithNormalizedTabs.values.map { it.takeWhile { it == ' ' }.length }.minOrNull()!!
val out = StringBuilder()
out.append(" ".repeat(lineCounterLength + 1))
out.append("|\n")
val lineSkippingIndicatorLine = "...".padStart(lineCounterLength, ' ') + "\n"
for (index in 0 .. lineNumbersToOutputSorted.lastIndex) {
val lineNumber = lineNumbersToOutputSorted[index]
out.append(lineNumber.toString(10).padStart(lineCounterLength, ' '))
out.append(" | ")
out.append(linesToOutputWithNormalizedTabs[lineNumber]!!.substring(commonNumberOfLeadingSpaces))
out.append("\n")
if (index != lineNumbersToOutputSorted.lastIndex) {
val nextLineNumber = lineNumbersToOutputSorted[index + 1]
if (lineNumber + 1 != nextLineNumber) {
// we are skipping some lines
out.append(lineSkippingIndicatorLine)
}
}
}
return out.toString()
}
| lgpl-3.0 | abfd0886b88049cd62bf44b83c339121 | 37.974359 | 120 | 0.696053 | 4.380403 | false | false | false | false |
gravidence/gravifon | lastfm4k/src/main/kotlin/org/gravidence/lastfm4k/api/track/Track.kt | 1 | 780 | package org.gravidence.lastfm4k.api.track
data class Track(
val artist: String,
val track: String,
val album: String? = null,
val albumArtist: String? = null,
val trackNumber: String? = null,
/**
* The MusicBrainz Track ID.
*/
val mbId: String? = null,
/**
* The length of the track in seconds.
*/
val duration: Long? = null
)
val VARIOUS_ARTISTS_VARIATIONS = setOf("VA", "V/A", "V.A.")
const val VARIOUS_ARTISTS_STANDARD = "Various Artists"
/**
* Apply workarounds to make track data comply to Last.fm (sometimes controversial) limitations.
*/
fun Track.comply(): Track {
return if (albumArtist in VARIOUS_ARTISTS_VARIATIONS) {
copy(albumArtist = VARIOUS_ARTISTS_STANDARD)
} else {
this
}
} | mit | 6dfa0fe4336b54fc19eb00edfc6a3b11 | 24.193548 | 96 | 0.639744 | 3.577982 | false | false | false | false |
google/horologist | media-ui/src/debug/java/com/google/android/horologist/media/ui/components/MediaControlButtonsPreview.kt | 1 | 1921 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
@Preview(
"Enabled - Playing - With progress",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun MediaControlButtonsPreview() {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = true,
percent = 0.25F,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true
)
}
@Preview(
"Disabled - Not playing - Without progress",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun MediaControlButtonsPreviewNoProgress() {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = false,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = false
)
}
| apache-2.0 | b9203a836fa34b0071b81a8760c116c2 | 29.983871 | 78 | 0.711088 | 4.85101 | false | false | false | false |
inv3rse/ProxerTv | app/src/test/java/com/inverse/unofficial/proxertv/base/UserSettingsMemory.kt | 1 | 777 | package com.inverse.unofficial.proxertv.base
/**
* In memory implementation of the [UserSettings] for testing
*/
class UserSettingsMemory : UserSettings() {
private var username: String? = null
private var password: String? = null
private var userToken: String? = null
override fun setUser(username: String?, password: String?) {
this.username = username
this.password = password
}
override fun setUserToken(userToken: String?) {
this.userToken = userToken
}
override fun getUser(): User? {
if (username != null && password != null) {
return User(username!!, password!!, userToken)
}
return null
}
override fun getUserToken(): String? {
return userToken
}
} | mit | 926f2189aa12ef0ba3640e1acc8f83ea | 24.096774 | 64 | 0.631918 | 4.680723 | false | false | false | false |
xfournet/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/Generator.kt | 1 | 10381 | package org.jetbrains.protocolModelGenerator
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.isNullOrEmpty
import gnu.trove.THashMap
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.jsonProtocol.*
import org.jetbrains.protocolReader.TextOutput
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.URL
import java.nio.file.FileSystems
import java.nio.file.Files
import java.util.*
fun main(args: Array<String>) {
val outputDir = args[0]
val roots = IntRange(3, args.size - 1).map {
val schemaUrl = args[it]
val bytes: ByteArray
if (schemaUrl.startsWith("http")) {
bytes = loadBytes(URL(schemaUrl).openStream())
}
else {
bytes = Files.readAllBytes(FileSystems.getDefault().getPath(schemaUrl))
}
val reader = JsonReaderEx(bytes.toString(Charsets.UTF_8))
reader.isLenient = true
ProtocolSchemaReaderImpl().parseRoot(reader)
}
val mergedRoot = if (roots.size == 1) roots[0] else object : ProtocolMetaModel.Root {
override val version: ProtocolMetaModel.Version?
get() = roots[0].version
override fun domains(): List<ProtocolMetaModel.Domain> {
return ContainerUtil.concat(roots.map { it.domains() })
}
}
Generator(outputDir, args[1], args[2], mergedRoot)
}
private fun loadBytes(stream: InputStream): ByteArray {
val buffer = ByteArrayOutputStream(Math.max(stream.available(), 16 * 1024))
val bytes = ByteArray(1024 * 20)
while (true) {
val n = stream.read(bytes, 0, bytes.size)
if (n <= 0) {
break
}
buffer.write(bytes, 0, n)
}
buffer.close()
return buffer.toByteArray()
}
internal class Naming(val inputPackage: String, val requestClassName: String) {
val params = ClassNameScheme.Output("", inputPackage)
val additionalParam = ClassNameScheme.Output("", inputPackage)
val outputTypedef: ClassNameScheme = ClassNameScheme.Output("Typedef", inputPackage)
val commandResult = ClassNameScheme.Input("Result", inputPackage)
val eventData = ClassNameScheme.Input("EventData", inputPackage)
val inputValue = ClassNameScheme.Input("Value", inputPackage)
val inputEnum = ClassNameScheme.Input("", inputPackage)
val inputTypedef = ClassNameScheme.Input("Typedef", inputPackage)
val commonTypedef = ClassNameScheme.Common("Typedef", inputPackage)
}
/**
* Read metamodel and generates set of files with Java classes/interfaces for the protocol.
*/
internal class Generator(outputDir: String, private val rootPackage: String, requestClassName: String, metamodel: ProtocolMetaModel.Root) {
val jsonProtocolParserClassNames = ArrayList<String>()
val parserRootInterfaceItems = ArrayList<ParserRootInterfaceItem>()
val typeMap = TypeMap()
val nestedTypeMap = THashMap<NamePath, StandaloneType>()
val fileSet = FileSet(FileSystems.getDefault().getPath(outputDir))
val naming = Naming(rootPackage, requestClassName)
init {
val domainList = metamodel.domains()
val domainGeneratorMap = THashMap<String, DomainGenerator>()
for (domain in domainList) {
if (!INCLUDED_DOMAINS.contains(domain.domain())) {
System.out.println("Domain skipped: ${domain.domain()}")
continue
}
val fileUpdater = fileSet.createFileUpdater("${StringUtil.nullize(domain.domain()) ?: "protocol"}.kt")
val out = fileUpdater.out
out.append("// Generated source").newLine().append("package ").append(getPackageName(rootPackage, domain.domain())).newLine().newLine()
out.append("import org.jetbrains.jsonProtocol.*").newLine()
out.append("import org.jetbrains.io.JsonReaderEx").newLine()
val domainGenerator = DomainGenerator(this, domain, fileUpdater)
domainGeneratorMap.put(domain.domain(), domainGenerator)
domainGenerator.registerTypes()
out.newLine()
System.out.println("Domain generated: ${domain.domain()}")
}
typeMap.domainGeneratorMap = domainGeneratorMap
for (domainGenerator in domainGeneratorMap.values) {
domainGenerator.generateCommandsAndEvents()
}
val sharedFileUpdater = if (domainGeneratorMap.size == 1) {
domainGeneratorMap.values.first().fileUpdater
}
else {
val fileUpdater = fileSet.createFileUpdater("protocol.kt")
val out = fileUpdater.out
out.append("// Generated source").newLine().append("package ").append(rootPackage).newLine().newLine()
out.append("import org.jetbrains.jsonProtocol.*").newLine()
out.append("import org.jetbrains.io.JsonReaderEx").newLine()
fileUpdater
}
typeMap.generateRequestedTypes()
generateParserInterfaceList(sharedFileUpdater.out)
generateParserRoot(parserRootInterfaceItems, sharedFileUpdater.out)
fileSet.deleteOtherFiles()
for (domainGenerator in domainGeneratorMap.values) {
domainGenerator.fileUpdater.update()
}
if (domainGeneratorMap.size != 1) {
sharedFileUpdater.update()
}
}
fun resolveType(itemDescriptor: ItemDescriptor, scope: ResolveAndGenerateScope): TypeDescriptor {
return switchByType(itemDescriptor, object : TypeVisitor<TypeDescriptor> {
override fun visitRef(refName: String) = TypeDescriptor(resolveRefType(scope.getDomainName(), refName, scope.getTypeDirection()), itemDescriptor)
override fun visitBoolean() = TypeDescriptor(BoxableType.BOOLEAN, itemDescriptor)
override fun visitEnum(enumConstants: List<String>): TypeDescriptor {
assert(scope is MemberScope)
return TypeDescriptor((scope as MemberScope).generateEnum(itemDescriptor.description, enumConstants), itemDescriptor)
}
override fun visitString() = TypeDescriptor(BoxableType.STRING, itemDescriptor)
override fun visitInteger() = TypeDescriptor(BoxableType.INT, itemDescriptor)
override fun visitNumber() = TypeDescriptor(BoxableType.NUMBER, itemDescriptor)
override fun visitMap() = TypeDescriptor(BoxableType.MAP, itemDescriptor)
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): TypeDescriptor {
val type = scope.resolveType(items).type
return TypeDescriptor(ListType(type), itemDescriptor, type == BoxableType.ANY_STRING)
}
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?) = TypeDescriptor(scope.generateNestedObject(itemDescriptor.description, properties), itemDescriptor)
override fun visitUnknown() = TypeDescriptor(BoxableType.STRING, itemDescriptor, true)
})
}
private fun generateParserInterfaceList(out: TextOutput) {
// write classes in stable order
Collections.sort(jsonProtocolParserClassNames)
out.newLine().newLine().append("val PARSER_CLASSES = arrayOf(").newLine()
for (name in jsonProtocolParserClassNames) {
out.append(" ").append(name).append("::class.java")
if (name != jsonProtocolParserClassNames.last()) {
out.append(',')
}
out.newLine()
}
out.append(')')
}
private fun generateParserRoot(parserRootInterfaceItems: List<ParserRootInterfaceItem>, out: TextOutput) {
// write classes in stable order
Collections.sort<ParserRootInterfaceItem>(parserRootInterfaceItems)
out.newLine().newLine().append("interface ").append(READER_INTERFACE_NAME).append(" : org.jetbrains.jsonProtocol.ResponseResultReader").openBlock()
for (item in parserRootInterfaceItems) {
item.writeCode(out)
out.newLine()
}
out.append("override fun readResult(methodName: String, reader: org.jetbrains.io.JsonReaderEx): Any? = ")
out.append("when (methodName)").block {
for (item in parserRootInterfaceItems) {
out.append('"')
if (!item.domain.isEmpty()) {
out.append(item.domain).append('.')
}
out.append(item.name).append('"').append(" -> ")
item.appendReadMethodName(out)
out.append("(reader)").newLine()
}
out.append("else -> null")
}
out.closeBlock()
}
/**
* Resolve absolute (DOMAIN.TYPE) or relative (TYPE) type name
*/
private fun resolveRefType(scopeDomainName: String, refName: String, direction: TypeData.Direction): BoxableType {
val pos = refName.indexOf('.')
val domainName: String
val shortName: String
if (pos == -1) {
domainName = scopeDomainName
shortName = refName
}
else {
domainName = refName.substring(0, pos)
shortName = refName.substring(pos + 1)
}
return typeMap.resolve(domainName, shortName, direction)!!
}
}
val READER_INTERFACE_NAME = "ProtocolResponseReader"
private val INCLUDED_DOMAINS = arrayOf("CSS", "Debugger", "DOM", "Inspector", "Log", "Network", "Page", "Runtime", "ServiceWorker",
"Tracing", "Target", "Overlay", "Console", "DOMDebugger")
fun generateMethodNameSubstitute(originalName: String, out: TextOutput): String {
if (originalName != "this") {
return originalName
}
out.append("@org.jetbrains.jsonProtocol.ProtocolName(\"").append(originalName).append("\")").newLine()
return "get${Character.toUpperCase(originalName.get(0))}${originalName.substring(1)}"
}
fun capitalizeFirstChar(s: String): String {
if (!s.isEmpty() && s.get(0).isLowerCase()) {
return s.get(0).toUpperCase() + s.substring(1)
}
return s
}
fun <R> switchByType(typedObject: ItemDescriptor, visitor: TypeVisitor<R>): R {
val refName = if (typedObject is ItemDescriptor.Referenceable) typedObject.ref else null
if (refName != null) {
return visitor.visitRef(refName)
}
val typeName = typedObject.type
return when (typeName) {
BOOLEAN_TYPE -> visitor.visitBoolean()
STRING_TYPE -> if (typedObject.enum == null) visitor.visitString() else visitor.visitEnum(typedObject.enum!!)
INTEGER_TYPE, "int" -> visitor.visitInteger()
NUMBER_TYPE -> visitor.visitNumber()
ARRAY_TYPE -> visitor.visitArray(typedObject.items!!)
OBJECT_TYPE -> {
if (typedObject !is ItemDescriptor.Type) {
visitor.visitObject(null)
}
else {
val properties = typedObject.properties
return if (properties.isNullOrEmpty()) visitor.visitMap() else visitor.visitObject(properties)
}
}
ANY_TYPE, UNKNOWN_TYPE -> return visitor.visitUnknown()
else -> throw RuntimeException("Unrecognized type $typeName")
}
} | apache-2.0 | 6c47931a12dfcb9ff1c0e975eec2a4e8 | 36.752727 | 184 | 0.710047 | 4.383868 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/modules/AccessModule.kt | 1 | 1453 | package me.mrkirby153.KirBot.modules
import me.mrkirby153.KirBot.module.Module
import me.mrkirby153.KirBot.module.ModuleManager
import net.dv8tion.jda.api.entities.Guild
import javax.inject.Inject
class AccessModule @Inject constructor(private val redis: Redis): Module("access") {
private val REDIS_KEY = "guilds"
init {
dependencies.add(Redis::class.java)
}
override fun onLoad() {
}
fun onList(guild: Guild, list: WhitelistMode): Boolean {
redis.getConnection().use {
return WhitelistMode.getMode(it.zscore(REDIS_KEY, guild.id)?.toInt() ?: 0) == list
}
}
fun addToList(guild: String, mode: WhitelistMode) {
redis.getConnection().use {
it.zadd(REDIS_KEY, mode.score.toDouble(), guild)
}
}
fun removeFromList(guild: String, mode: WhitelistMode) {
redis.getConnection().use {
it.zrem(REDIS_KEY, guild)
}
}
fun getList(mode: WhitelistMode): Set<String> {
redis.getConnection().use {
return it.zrangeByScore(REDIS_KEY, mode.score.toDouble(), mode.score.toDouble())
}
}
enum class WhitelistMode(val score: Int) {
NEUTRAL(0),
WHITELIST(1),
BLACKLIST(2);
companion object {
fun getMode(score: Int): WhitelistMode {
return values().firstOrNull { it.score == score } ?: NEUTRAL
}
}
}
} | mit | 1f9e11d897422b7df40dcc0fe0a22f9d | 24.068966 | 94 | 0.607708 | 3.959128 | false | false | false | false |
tonyklawrence/funk | src/main/kotlin/funk/ToOption.kt | 1 | 340 | package funk
fun Double.toIntOption(): Int? = if (this == toInt().toDouble()) toInt() else null
fun String.toIntOption(): Int? = Try { toInt() }.toOption()
fun String.toDoubleOption(): Double? = Try { toDouble() }.toOption()
private class Try<out T>(val ƒ: () -> T) {
fun toOption(): T? = try { ƒ() } catch (t: Throwable) { null }
} | apache-2.0 | e39390a07e03b3df38dee70547a64faa | 36.666667 | 82 | 0.627219 | 3.219048 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/ExtractInlineModuleIntention.kt | 2 | 1651 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsModDeclItem
import org.rust.lang.core.psi.RsModItem
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.getOrCreateModuleFile
import org.rust.lang.core.psi.ext.parentOfType
//TODO: make context more precise here
class ExtractInlineModuleIntention : RsElementBaseIntentionAction<RsModItem>() {
override fun getFamilyName() = "Extract inline module structure"
override fun getText() = "Extract inline module"
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsModItem? {
val mod = element.parentOfType<RsModItem>() ?: return null
if (mod.`super`?.ownsDirectory != true) return null
return mod
}
override fun invoke(project: Project, editor: Editor, ctx: RsModItem) {
val modName = ctx.name ?: return
var decl = RsPsiFactory(project).createModDeclItem(modName)
decl = ctx.parent?.addBefore(decl, ctx) as? RsModDeclItem ?: return
val modFile = decl.getOrCreateModuleFile() ?: return
val startElement = ctx.lbrace.nextSibling ?: return
val endElement = ctx.rbrace?.prevSibling ?: return
modFile.addRange(startElement, endElement)
ReformatCodeProcessor(project, modFile, null, false).run()
ctx.delete()
}
}
| mit | f1afbca528ddb5977c93994ed1ab691d | 36.522727 | 107 | 0.732283 | 4.37931 | false | false | false | false |
quarkusio/quarkus | integration-tests/hibernate-reactive-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/reactive/kotlin/Bug7721Entity.kt | 1 | 673 | package io.quarkus.it.panache.reactive.kotlin
import javax.persistence.Column
import javax.persistence.Entity
@Entity
class Bug7721Entity : Bug7721EntitySuperClass() {
@Column(nullable = false)
var foo: String = "default"
init {
foo = "default" // same as init
foo = "default" // qualify
superField = "default"
superField = "default"
super.superField = "default"
val otherEntity = Bug7721OtherEntity()
otherEntity.foo = "bar" // we want to make sure the setter gets called because it's not our hierarchy
if (otherEntity.foo != "BAR") throw AssertionError("setter was not called", null)
}
}
| apache-2.0 | 5b55067f4b7ab020e9804f9bfa26ac90 | 31.047619 | 109 | 0.662704 | 4.005952 | false | false | false | false |
opentok/opentok-android-sdk-samples | Multiparty-Constraint-Layout-Kotlin/app/src/main/java/com/tokbox/sample/multipartyconstraintlayout/MainActivity.kt | 1 | 12236 | package com.tokbox.sample.multipartyconstraintlayout
import android.Manifest
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.opentok.android.BaseVideoRenderer
import com.opentok.android.OpentokError
import com.opentok.android.Publisher
import com.opentok.android.PublisherKit
import com.opentok.android.PublisherKit.PublisherListener
import com.opentok.android.Session
import com.opentok.android.Session.SessionListener
import com.opentok.android.Session.SessionOptions
import com.opentok.android.Stream
import com.opentok.android.Subscriber
import com.tokbox.sample.multipartyconstraintlayout.MainActivity
import com.tokbox.sample.multipartyconstraintlayout.OpenTokConfig.description
import com.tokbox.sample.multipartyconstraintlayout.OpenTokConfig.isValid
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
import java.util.ArrayList
import java.util.HashMap
class MainActivity : AppCompatActivity(), PermissionCallbacks {
private var session: Session? = null
private var publisher: Publisher? = null
private val subscribers = ArrayList<Subscriber>()
private val subscriberStreams = HashMap<Stream, Subscriber>()
private lateinit var container: ConstraintLayout
private val publisherListener: PublisherListener = object : PublisherListener {
override fun onStreamCreated(publisherKit: PublisherKit, stream: Stream) {
Log.d(TAG, "onStreamCreated: Own stream ${stream.streamId} created")
}
override fun onStreamDestroyed(publisherKit: PublisherKit, stream: Stream) {
Log.d(TAG, "onStreamDestroyed: Own stream ${stream.streamId} destroyed")
}
override fun onError(publisherKit: PublisherKit, opentokError: OpentokError) {
finishWithMessage("PublisherKit error: ${opentokError.message}")
}
}
private val sessionListener: SessionListener = object : SessionListener {
override fun onConnected(session: Session) {
Log.d(TAG, "onConnected: Connected to session ${session.sessionId}")
session.publish(publisher)
}
override fun onDisconnected(session: Session) {
Log.d(TAG, "onDisconnected: disconnected from session ${session.sessionId}")
[email protected] = null
}
override fun onError(session: Session, opentokError: OpentokError) {
finishWithMessage("Session error: ${opentokError.message}")
}
override fun onStreamReceived(session: Session, stream: Stream) {
Log.d(TAG, "onStreamReceived: New stream ${stream.streamId} in session ${session.sessionId}")
val subscriber = Subscriber.Builder(this@MainActivity, stream).build()
session.subscribe(subscriber)
subscribers.add(subscriber)
subscriberStreams[stream] = subscriber
val subId = getResIdForSubscriberIndex(subscribers.size - 1)
subscriber.view.id = subId
container.addView(subscriber.view)
calculateLayout()
}
override fun onStreamDropped(session: Session, stream: Stream) {
Log.d(TAG, "onStreamDropped: Stream ${stream.streamId} dropped from session ${session.sessionId}")
val subscriber = subscriberStreams[stream] ?: return
subscribers.remove(subscriber)
subscriberStreams.remove(stream)
container.removeView(subscriber.view)
// Recalculate view Ids
for (i in subscribers.indices) {
subscribers[i].view.id = getResIdForSubscriberIndex(i)
}
calculateLayout()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (!isValid) {
finishWithMessage("Invalid OpenTokConfig. $description")
return
}
container = findViewById(R.id.main_container)
requestPermissions()
}
override fun onResume() {
super.onResume()
if (session == null) {
return
}
session?.onResume()
}
override fun onPause() {
super.onPause()
if (session == null) {
return
}
session?.onPause()
if (isFinishing) {
disconnectSession()
}
}
override fun onDestroy() {
disconnectSession()
super.onDestroy()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
Log.d(TAG, "onPermissionsGranted:$requestCode: $perms")
}
override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
finishWithMessage("onPermissionsDenied: $requestCode: $perms")
}
private fun getResIdForSubscriberIndex(index: Int): Int {
val arr = resources.obtainTypedArray(R.array.subscriber_view_ids)
val subId = arr.getResourceId(index, 0)
arr.recycle()
return subId
}
private fun startPublisherPreview() {
publisher = Publisher.Builder(this).build()
publisher?.setPublisherListener(publisherListener)
publisher?.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL)
publisher?.startPreview()
}
@AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
private fun requestPermissions() {
val perms = arrayOf(Manifest.permission.INTERNET, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
if (EasyPermissions.hasPermissions(this, *perms)) {
session = Session.Builder(this, OpenTokConfig.API_KEY, OpenTokConfig.SESSION_ID)
.sessionOptions(object : SessionOptions() {
override fun useTextureViews(): Boolean {
return true
}
}).build()
session?.setSessionListener(sessionListener)
session?.connect(OpenTokConfig.TOKEN)
startPublisherPreview()
publisher?.view?.id = R.id.publisher_view_id
container.addView(publisher?.view)
calculateLayout()
} else {
EasyPermissions.requestPermissions(
this,
getString(R.string.rationale_video_app),
PERMISSIONS_REQUEST_CODE,
*perms
)
}
}
private fun calculateLayout() {
val set = ConstraintSetHelper(R.id.main_container)
val size = subscribers.size
if (size == 0) {
// Publisher full screen
set.layoutViewFullScreen(R.id.publisher_view_id)
} else if (size == 1) {
// Publisher
// Subscriber
set.layoutViewAboveView(R.id.publisher_view_id, getResIdForSubscriberIndex(0))
set.layoutViewWithTopBound(R.id.publisher_view_id, R.id.main_container)
set.layoutViewWithBottomBound(getResIdForSubscriberIndex(0), R.id.main_container)
set.layoutViewAllContainerWide(R.id.publisher_view_id, R.id.main_container)
set.layoutViewAllContainerWide(getResIdForSubscriberIndex(0), R.id.main_container)
set.layoutViewHeightPercent(R.id.publisher_view_id, .5f)
set.layoutViewHeightPercent(getResIdForSubscriberIndex(0), .5f)
} else if (size > 1 && size % 2 == 0) {
// Publisher
// Sub1 | Sub2
// Sub3 | Sub4
// .....
val rows = size / 2 + 1
val heightPercent = 1f / rows
set.layoutViewWithTopBound(R.id.publisher_view_id, R.id.main_container)
set.layoutViewAllContainerWide(R.id.publisher_view_id, R.id.main_container)
set.layoutViewHeightPercent(R.id.publisher_view_id, heightPercent)
var i = 0
while (i < size) {
if (i == 0) {
set.layoutViewAboveView(R.id.publisher_view_id, getResIdForSubscriberIndex(i))
set.layoutViewAboveView(R.id.publisher_view_id, getResIdForSubscriberIndex(i + 1))
} else {
set.layoutViewAboveView(getResIdForSubscriberIndex(i - 2), getResIdForSubscriberIndex(i))
set.layoutViewAboveView(getResIdForSubscriberIndex(i - 1), getResIdForSubscriberIndex(i + 1))
}
set.layoutTwoViewsOccupyingAllRow(getResIdForSubscriberIndex(i), getResIdForSubscriberIndex(i + 1))
set.layoutViewHeightPercent(getResIdForSubscriberIndex(i), heightPercent)
set.layoutViewHeightPercent(getResIdForSubscriberIndex(i + 1), heightPercent)
i += 2
}
set.layoutViewWithBottomBound(getResIdForSubscriberIndex(size - 2), R.id.main_container)
set.layoutViewWithBottomBound(getResIdForSubscriberIndex(size - 1), R.id.main_container)
} else if (size > 1) {
// Pub | Sub1
// Sub2 | Sub3
// Sub3 | Sub4
// .....
val rows = (size + 1) / 2
val heightPercent = 1f / rows
set.layoutViewWithTopBound(R.id.publisher_view_id, R.id.main_container)
set.layoutViewHeightPercent(R.id.publisher_view_id, heightPercent)
set.layoutViewWithTopBound(getResIdForSubscriberIndex(0), R.id.main_container)
set.layoutViewHeightPercent(getResIdForSubscriberIndex(0), heightPercent)
set.layoutTwoViewsOccupyingAllRow(R.id.publisher_view_id, getResIdForSubscriberIndex(0))
var i = 1
while (i < size) {
if (i == 1) {
set.layoutViewAboveView(R.id.publisher_view_id, getResIdForSubscriberIndex(i))
set.layoutViewHeightPercent(R.id.publisher_view_id, heightPercent)
set.layoutViewAboveView(getResIdForSubscriberIndex(0), getResIdForSubscriberIndex(i + 1))
set.layoutViewHeightPercent(getResIdForSubscriberIndex(0), heightPercent)
} else {
set.layoutViewAboveView(getResIdForSubscriberIndex(i - 2), getResIdForSubscriberIndex(i))
set.layoutViewHeightPercent(getResIdForSubscriberIndex(i - 2), heightPercent)
set.layoutViewAboveView(getResIdForSubscriberIndex(i - 1), getResIdForSubscriberIndex(i + 1))
set.layoutViewHeightPercent(getResIdForSubscriberIndex(i - 1), heightPercent)
}
set.layoutTwoViewsOccupyingAllRow(getResIdForSubscriberIndex(i), getResIdForSubscriberIndex(i + 1))
i += 2
}
set.layoutViewWithBottomBound(getResIdForSubscriberIndex(size - 2), R.id.main_container)
set.layoutViewWithBottomBound(getResIdForSubscriberIndex(size - 1), R.id.main_container)
}
set.applyToLayout(container, true)
}
private fun disconnectSession() {
if (session == null) {
return
}
if (subscribers.size > 0) {
for (subscriber in subscribers) {
session?.unsubscribe(subscriber)
}
}
if (publisher != null) {
session?.unpublish(publisher)
container.removeView(publisher?.view)
publisher = null
}
session?.disconnect()
}
private fun finishWithMessage(message: String) {
Log.e(TAG, message)
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
finish()
}
companion object {
private val TAG = MainActivity::class.java.simpleName
private const val PERMISSIONS_REQUEST_CODE = 124
}
} | mit | c22ec2b45e3739ee385a7e266b47def0 | 41.342561 | 119 | 0.64678 | 4.594818 | false | false | false | false |
JimSeker/ui | Advanced/BotNavGuiDemo_kt/app/src/main/java/edu/cs4730/botnavguidemo_kt/Button_Fragment.kt | 1 | 2183 | package edu.cs4730.botnavguidemo_kt
import android.content.Context
import android.widget.TextView
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
class Button_Fragment : Fragment(), View.OnClickListener {
var TAG = "Button_Fragment"
lateinit var myContext: Context
lateinit var output: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myView = inflater.inflate(R.layout.button_fragment, container, false)
output = myView.findViewById(R.id.output)
//setup the listeners. Each one setup a different way.
//"standard" way
val btn1 = myView.findViewById<Button>(R.id.button01)
btn1.setOnClickListener { output.setText("Output:\nButton1") }
//using the implements methods, ie this
val btn2 = myView.findViewById<Button>(R.id.button02)
btn2.setOnClickListener(this)
//shortest version, no variable created.
myView.findViewById<View>(R.id.button03).setOnClickListener(this)
//note setting the listener in the xml android:onclick= will call the MainActivity, not the fragment!
return myView
}
/*
* This on is the for the implements View.OnClickListener
*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
override fun onClick(v: View) {
if (v.id == R.id.button02) { //it's button 2
Toast.makeText(myContext, "Button 2 was clicked", Toast.LENGTH_SHORT).show()
} else if (v.id == R.id.button03) { //it's button 3
output!!.text = "Output:\nButton3"
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
myContext = context
Log.d(TAG, "onAttach")
}
} | apache-2.0 | 1bf1c0de5fcd6c3aaff912f839201d28 | 32.6 | 109 | 0.674301 | 4.214286 | false | false | false | false |
jpmoreto/play-with-robots | android/testsApp/src/test/java/jpm/lib/simulator/robotsubsystems/MeasureTimeMicros.kt | 1 | 931 | package jpm.lib.simulator.robotsubsystems
/**
* Created by jm on 27/04/17.
*
*/
class MeasureTimeMicros(val sleepTimeMicro: Long) {
fun setup() {
getDeltaTime(System.nanoTime() / 1000L)
}
fun getDeltaTime(actualTimeMicro: Long): Long {
val delta =
if(actualTimeMicro > previousTime) actualTimeMicro - previousTime
else Long.MAX_VALUE - previousTime + actualTimeMicro
if(isFirstTime == false) {
sleepTimeError = delta - sleepTimeMicro;
}
previousTime = actualTimeMicro;
isFirstTime = false;
return delta;
}
fun sleep() {
val mili = (sleepTimeMicro - sleepTimeError) / 1000
val nano = ((sleepTimeMicro - sleepTimeError) - mili * 1000) * 1000
Thread.sleep(mili,nano.toInt())
}
private var previousTime = 0L
private var sleepTimeError = 0L
private var isFirstTime = true
} | mit | 2a0702fefab99f65bb327ff87ed79ea7 | 24.189189 | 77 | 0.62406 | 4.193694 | false | false | false | false |
http4k/http4k | http4k-testing/approval/src/test/kotlin/org/http4k/testing/NamedSourceApproverTest.kt | 1 | 2084 | package org.http4k.testing
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.junit.jupiter.api.Test
import java.io.File
import java.nio.file.Files
import kotlin.random.Random
class NamedSourceApproverTest {
private val body = "content"
private val baseFile = Files.createTempDirectory(javaClass.name).toFile()
private val testName = "somename" + Random.nextLong()
private val actualFile = File(baseFile, "$testName.actual")
private val approvedFile = File(baseFile, "$testName.approved")
private val approver = NamedResourceApprover(testName, ApprovalContent.HttpBodyOnly(), FileSystemApprovalSource(baseFile))
@Test
fun `when no approval recorded, create actual and throw`() {
assertThat({ approver.assertApproved(Response(OK).body(body)) }, throws<ApprovalFailed>())
assertThat(actualFile.exists(), equalTo(true))
assertThat(actualFile.readText(), equalTo(body))
assertThat(approvedFile.exists(), equalTo(false))
}
@Test
fun `when mismatch, overwrite actual`() {
approvedFile.writeText("some other value")
actualFile.writeText("previous content")
assertThat({ approver.assertApproved(Response(OK).body(body)) }, throws<AssertionError>())
assertThat(actualFile.readText(), equalTo(body))
assertThat(approvedFile.readText(), equalTo("some other value"))
}
@Test
fun `when no approval recorded and no actual content, don't write actual or approved`() {
approver.assertApproved(Response(OK))
assertThat(actualFile.exists(), equalTo(false))
assertThat(approvedFile.exists(), equalTo(false))
}
@Test
fun `when match, don't write actual`() {
approvedFile.writeText(body)
approver.assertApproved(Response(OK).body(body))
assertThat(actualFile.exists(), equalTo(false))
assertThat(approvedFile.readText(), equalTo(body))
}
}
| apache-2.0 | 474a50051b85776483ac0fcd5e0f77f4 | 38.320755 | 126 | 0.714971 | 4.296907 | false | true | false | false |
http4k/http4k | http4k-incubator/src/test/kotlin/org/http4k/events/MyCustomTracer.kt | 1 | 1239 | package org.http4k.events
import org.http4k.filter.ZipkinTraces
import java.time.Instant
data class MyCustomEvent(val serviceIdentifier: String, val myTime: Instant) : Event
object MyCustomTracer : Tracer<MyTraceTree> {
override fun invoke(parent: MetadataEvent, rest: List<MetadataEvent>, tracer: Tracer<TraceTree>) =
parent.takeIf { it.event is MyCustomEvent }
?.let { listOf(it.toTraceTree(rest - it, tracer)) } ?: emptyList()
private fun MetadataEvent.toTraceTree(rest: List<MetadataEvent>, tracer: Tracer<TraceTree>): MyTraceTree {
val parentEvent = event as MyCustomEvent
return MyTraceTree(
service(this),
parentEvent.myTime,
rest
.filter { traces().spanId == it.traces().parentSpanId }
.filter { parentEvent.serviceIdentifier == service(it) }
.flatMap { tracer(it, rest - it, tracer) })
}
private fun service(event: MetadataEvent) = event.metadata["service"].toString()
private fun MetadataEvent.traces() = (metadata["traces"] as ZipkinTraces)
}
data class MyTraceTree(
override val origin: String,
val myTime: Instant,
override val children: List<TraceTree>
) : TraceTree
| apache-2.0 | df23c495071ee521c675901729cdbe59 | 37.71875 | 110 | 0.673931 | 4.228669 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/home/more/base/ListAppsAdapter.kt | 1 | 1283 | package cm.aptoide.pt.home.more.base
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cm.aptoide.pt.view.app.Application
import rx.subjects.PublishSubject
class ListAppsAdapter<T : Application, V : ListAppsViewHolder<T>>(
val viewHolderBuilder: (ViewGroup, Int) -> V) : RecyclerView.Adapter<V>() {
private var clickListener = PublishSubject.create<ListAppsClickEvent<T>>()
private var appList: ArrayList<T> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): V {
val vh = viewHolderBuilder(parent, viewType)
vh.itemView.setOnClickListener {
clickListener.onNext(
ListAppsClickEvent(appList[vh.adapterPosition],
vh.adapterPosition))
}
return vh
}
override fun onBindViewHolder(holder: V, position: Int) {
holder.bindApp(appList[position])
}
override fun getItemCount(): Int {
return appList.size
}
fun setData(objs: List<T>) {
appList = ArrayList(objs)
notifyDataSetChanged()
}
fun getClickListener(): PublishSubject<ListAppsClickEvent<T>> {
return clickListener
}
fun addData(apps: List<T>) {
val adapterSize = appList.size
appList.addAll(apps)
notifyItemRangeInserted(adapterSize, apps.size)
}
} | gpl-3.0 | 9335ec8c0463334a4c340e4d49be4dd8 | 25.75 | 79 | 0.719408 | 4.165584 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/agenda/AgendaItemsAdapter.kt | 1 | 5636 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.agenda
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.model.Assignment
import co.timetableapp.model.Color
import co.timetableapp.model.Event
import co.timetableapp.model.Subject
import co.timetableapp.model.agenda.AgendaHeader
import co.timetableapp.model.agenda.AgendaItem
import co.timetableapp.model.agenda.AgendaListItem
import co.timetableapp.ui.OnItemClick
import co.timetableapp.util.DateUtils
/**
* A RecyclerView adapter to be used for items being displayed on the "Agenda" page.
*/
class AgendaItemsAdapter(
private val context: Context,
private val items: List<AgendaListItem>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val VIEW_TYPE_HEADER = 1
private const val VIEW_TYPE_ITEM = 2
}
private var onItemClick: OnItemClick? = null
fun onItemClick(action: OnItemClick) {
onItemClick = action
}
class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.text) as TextView
}
inner class AgendaViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val colorView: View
val title: TextView
val subtitle: TextView
val info1: TextView
val info2: TextView
init {
itemView.setOnClickListener { onItemClick?.invoke(it, layoutPosition) }
colorView = itemView.findViewById(R.id.color)
title = itemView.findViewById(R.id.text1) as TextView
subtitle = itemView.findViewById(R.id.text2) as TextView
info1 = itemView.findViewById(R.id.text3) as TextView
info2 = itemView.findViewById(R.id.text4) as TextView
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_HEADER -> {
val headerView = LayoutInflater.from(parent!!.context)
.inflate(R.layout.subheader, parent, false)
HeaderViewHolder(headerView)
}
VIEW_TYPE_ITEM -> {
val itemView = LayoutInflater.from(parent!!.context)
.inflate(R.layout.item_general, parent, false)
AgendaViewHolder(itemView)
}
else -> throw IllegalArgumentException("invalid view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
when (getItemViewType(position)) {
VIEW_TYPE_HEADER -> setupHeaderLayout(holder as HeaderViewHolder, position)
VIEW_TYPE_ITEM -> setupItemLayout(holder as AgendaViewHolder, position)
}
}
private fun setupHeaderLayout(holder: HeaderViewHolder, position: Int) {
holder.textView.text = (items[position] as AgendaHeader).getName(context)
}
private fun setupItemLayout(holder: AgendaViewHolder, position: Int) {
val agendaItem = items[position] as AgendaItem
val relatedSubject = agendaItem.getRelatedSubject(context)
with(holder) {
title.text = agendaItem.getDisplayedTitle()
subtitle.text = makeSubtitleText(agendaItem, relatedSubject)
info1.text = agendaItem.getDateTime().toLocalDate()
.format(DateUtils.FORMATTER_FULL_DATE) // TODO display start **and end** dates
if (agendaItem is Assignment) {
// Has no time to display, but has completion progress
info2.text = "${agendaItem.completionProgress}%"
} else {
info2.text = agendaItem.getDateTime().toLocalTime().format(DateUtils.FORMATTER_TIME)
}
val color = if (relatedSubject == null) {
Event.DEFAULT_COLOR
} else {
Color(relatedSubject.colorId)
}
colorView.setBackgroundColor(
ContextCompat.getColor(context, color.getPrimaryColorResId(context)))
}
}
/**
* @return a string to be used as a subtitle on the agenda list item
*/
private fun makeSubtitleText(agendaItem: AgendaItem, relatedSubject: Subject?): String {
var subtitleText = ""
relatedSubject?.let { subtitleText += "${it.name} " }
subtitleText += context.getString(agendaItem.getTypeNameRes())
return subtitleText
}
override fun getItemCount() = items.size
override fun getItemViewType(position: Int) = when (items[position]) {
is AgendaHeader -> VIEW_TYPE_HEADER
is AgendaItem -> VIEW_TYPE_ITEM
else -> throw IllegalArgumentException("invalid item type at position: $position")
}
}
| apache-2.0 | 5dc95b75d5079f3d001be3cda1840df7 | 35.597403 | 100 | 0.667317 | 4.684954 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/ui/ViewHelper.kt | 1 | 1964 | package me.shkschneider.skeleton.ui
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.annotation.UiThread
import me.shkschneider.skeleton.SkeletonReceiver
object ViewHelper {
val ANDROIDXML = "http://schemas.android.com/apk/res/android"
val RESAUTOXML = "http://schemas.android.com/apk/res-auto"
val CONTENT = Window.ID_ANDROID_CONTENT
val NO_ID = View.NO_ID
val RESULT_VISIBILITY = "VISIBILITY"
fun <T: View> content(activity: Activity): T {
return activity.findViewById(CONTENT)
}
fun children(view: View): List<View> {
val viewGroup = view as ViewGroup
return (0 until viewGroup.childCount).mapTo(ArrayList<View>()) { viewGroup.getChildAt(it) }
}
@UiThread
fun show(view: View): Boolean {
if (view.visibility != View.VISIBLE) {
view.visibility = View.VISIBLE
return true
}
return false
}
@UiThread
fun hide(view: View): Boolean {
if (view.visibility != View.GONE) {
view.visibility = View.GONE
return true
}
return false
}
@UiThread
fun block(activity: Activity) {
activity.window?.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
}
@UiThread
fun unblock(activity: Activity) {
activity.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
}
// <https://stackoverflow.com/a/32778292>
fun visibilityListener(view: View, skeletonReceiver: SkeletonReceiver) {
view.tag = view.visibility
view.viewTreeObserver.addOnGlobalLayoutListener {
if (view.tag != view.visibility) {
view.tag = view.visibility
skeletonReceiver.post(RESULT_VISIBILITY, view.visibility)
}
}
}
}
| apache-2.0 | 4f9aaf3b4d03268fb00bdd8930b2049c | 28.313433 | 127 | 0.656314 | 4.278867 | false | false | false | false |
KDatabases/Kuery | src/main/kotlin/com/sxtanna/database/task/KueryTask.kt | 1 | 7838 | package com.sxtanna.database.task
import com.sxtanna.database.Kuery
import com.sxtanna.database.ext.*
import com.sxtanna.database.struct.base.Duo
import com.sxtanna.database.struct.obj.Duplicate
import com.sxtanna.database.struct.obj.Duplicate.Ignore
import com.sxtanna.database.struct.obj.Sort
import com.sxtanna.database.struct.obj.SqlType
import com.sxtanna.database.struct.obj.Target
import com.sxtanna.database.task.builder.*
import com.sxtanna.database.type.base.SqlObject
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.util.function.Consumer
import kotlin.reflect.KProperty1
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
@Suppress("UNCHECKED_CAST")
class KueryTask(private val kuery : Kuery, override val resource : Connection) : DatabaseTask<Connection>() {
private lateinit var resultSet : ResultSet
private lateinit var preparedStatement : PreparedStatement
@JvmSynthetic
fun query(query : String, vararg values : Any?, block : ResultSet.() -> Unit) {
if (kuery.debug) kuery.logger.info("Query '$query'")
preparedStatement = resource.prepareStatement(query)
values.forEachIndexed { index, any -> preparedStatement.setObject(index + 1, any) }
resultSet = preparedStatement.executeQuery()
resultSet.block()
}
@JvmOverloads
fun query(query : String, vararg values : Any? = emptyArray(), block : Consumer<ResultSet>) = query(query, *values) { block.accept(this) }
fun execute(query : String, vararg values : Any?) {
if (kuery.debug) kuery.logger.info("Statement '$query'")
preparedStatement = resource.prepareStatement(query)
if (values.isNotEmpty()) values.forEachIndexed { index, any -> preparedStatement.setObject(index + 1, any) }
preparedStatement.execute()
}
@SafeVarargs
@Deprecated("Use Create", ReplaceWith("Create.table(name).cos(*columns)", "com.sxtanna.database.task.builder.Create"))
fun create(name : String, vararg columns : Duo<SqlType>) {
execute("CREATE TABLE IF NOT EXISTS $name ${columns.map { "${it.name} ${it.value}" }.joinToString(prefix = "(", postfix = ")")}")
}
@JvmSynthetic
@Deprecated("Use Select")
fun select(table : String, columns : Array<out String> = ALL_ROWS, target : Array<out Target> = NO_WHERE, order : Array<out Sort> = NO_SORTS, block : ResultSet.() -> Unit) {
val statement = "SELECT ${columns.joinToString()} FROM $table${target.isNotEmpty().value(" WHERE ${target.joinToString(" AND ")}")}${order.isNotEmpty().value(" ORDER BY ${order.joinToString()}")}"
if (kuery.debug) kuery.logger.info("Select '$statement'")
preparedStatement = resource.prepareStatement(statement)
var offSet = 0
target.forEachIndexed { i, data -> offSet += data.prep(preparedStatement, i + 1 + offSet) }
resultSet = preparedStatement.executeQuery()
if (resultSet.isBeforeFirst.not()) return resultSet.close()
block(resultSet)
}
@JvmOverloads
@Deprecated("Use Select")
fun select(table : String, columns : Array<out String> = ALL_ROWS, target : Array<out Target> = NO_WHERE, order : Array<out Sort> = NO_SORTS, block : Consumer<ResultSet>) {
select(table, columns, target, order) { block.accept(this) }
}
@JvmSynthetic
@Deprecated("Use Select")
fun select(table : String, order : Array<out Sort>, block : ResultSet.() -> Unit) = select(table, ALL_ROWS, NO_WHERE, order, block)
@JvmSynthetic
@Deprecated("Use Select")
fun select(table : String, target : Array<out Target>, block : ResultSet.() -> Unit) = select(table, ALL_ROWS, target, NO_SORTS, block)
@Deprecated("Use Select")
fun select(table : String, order : Array<out Sort>, block : Consumer<ResultSet>) = select(table, ALL_ROWS, NO_WHERE, order, block)
@Deprecated("Use Select")
fun select(table : String, target : Array<out Target>, block : Consumer<ResultSet>) = select(table, ALL_ROWS, target, NO_SORTS, block)
@JvmOverloads
@Deprecated("Use Insert")
fun insert(table : String, vararg columns : Duo<Any?>, duplicateKey : Duplicate? = null) {
val ignore = duplicateKey is Ignore
val insertStatement = "INSERT ${ignore.value("IGNORE ")}INTO $table (${columns.map { it.name }.joinToString()}) VALUES ${values(columns.size)}${ignore.not().value(" ${duplicateKey?.invoke(columns[0].name)}")}"
execute(insertStatement, *columns.map { it.value }.toTypedArray())
}
@JvmOverloads
@Deprecated("Use Update")
fun update(table : String, columns : Array<Duo<Any?>>, vararg where : Target = emptyArray()) : Int {
val updateStatement = "UPDATE $table SET ${columns.joinToString { "${it.name}=?" }}${where.isNotEmpty().value(" WHERE ${where.joinToString(" AND ")}")}"
if (kuery.debug) kuery.logger.info("Update '$updateStatement'")
preparedStatement = resource.prepareStatement(updateStatement)
columns.forEachIndexed { i, data -> preparedStatement.setObject(i + 1, data.value) }
var offSet = columns.size
where.forEachIndexed { i, data -> offSet += data.prep(preparedStatement, i + 1 + offSet) }
return preparedStatement.executeUpdate()
}
@JvmOverloads
@Deprecated("Use Delete")
fun delete(table : String, vararg where : Target = emptyArray()) {
val deleteStatement = "DELETE FROM $table ${where.isNotEmpty().value("WHERE ${where.joinToString(" AND ")}")}"
if (kuery.debug) kuery.logger.info("Delete '$deleteStatement'")
preparedStatement = resource.prepareStatement(deleteStatement)
where.forEachIndexed { i, data -> data.prep(preparedStatement, i + 1) }
preparedStatement.execute()
}
//region Building Functions
@JvmSynthetic
operator fun Create.invoke() = create(table, *columns.toTypedArray())
fun execute(create : Create) = create.invoke()
@JvmSynthetic
operator fun <T : SqlObject> Select<T>.invoke(handler : T.() -> Unit) {
select(table, ALL_ROWS, where.toTypedArray(), sorts.toTypedArray()) {
val creator = checkNotNull(kuery.creators[clazz] as? ResultSet.() -> T) { "Creator for type $clazz doesn't exist" }
mapWhileNext(creator).forEach(handler)
}
}
fun <T : SqlObject> execute(select : Select<T>, handler : Consumer<T>) = select.invoke { handler.accept(this) }
@JvmSynthetic
operator fun <T : SqlObject> Insert<T>.invoke(obj : T) {
val columns = clazz.declaredMemberProperties.map { it.name co obj.retrieve(it) }.toTypedArray()
insert(table, *columns, duplicateKey = if (ignore) Ignore() else if (update.isNotEmpty()) Duplicate.Update(*update) else null)
}
fun <T : SqlObject> execute(insert : Insert<T>, obj : T) = insert.invoke(obj)
@JvmSynthetic
operator fun <T : SqlObject> Update<T>.invoke(obj : T) : Int {
val columns = clazz.declaredMemberProperties.filterNot { it.name.toLowerCase() in ignoring }.map { it.name co obj.retrieve(it) }.toTypedArray()
return update(table, columns, *where.toTypedArray())
}
fun <T : SqlObject> execute(update : Update<T>, obj : T) = update.invoke(obj)
@JvmSynthetic
operator fun <T : SqlObject> Delete<T>.invoke(obj : T? = null) {
val where = obj?.let { o -> clazz.declaredMemberProperties.map { Target.equals(it.name, o.retrieve(it)) } } ?: where
return delete(table, *where.toTypedArray())
}
/**
* If an object is supplied, it will use the data from that object,
* if not, it will fallback to the clauses specified in the statement
* If no conditions are supplied, it will delete every row
*/
@JvmOverloads
fun <T : SqlObject> execute(delete : Delete<T>, obj : T? = null) = delete.invoke(obj)
//endregion
private fun values(count : Int) = Array(count, { "?" }).joinToString(prefix = "(", postfix = ")")
private fun <T, R> T.retrieve(property : KProperty1<T, R>) : R {
val state = property.isAccessible
property.isAccessible = true
val obj = property.get(this)
property.isAccessible = state
return obj
}
} | apache-2.0 | ef24294e63aa41924c5ce7d86eea8c3f | 37.615764 | 211 | 0.708982 | 3.707663 | false | false | false | false |
deadpixelsociety/passport | core/src/main/kotlin/com/thedeadpixelsociety/passport/Functions.kt | 1 | 3184 | package com.thedeadpixelsociety.passport
object Functions {
fun matches(regex: Regex): Predicate<String?> = { it?.let { regex.matches(it) } ?: false }
fun matches(pattern: String) = matches(Regex(pattern))
fun doesNotMatch(regex: Regex): Predicate<String?> = { !matches(regex)(it) }
fun doesNotMatch(pattern: String) = doesNotMatch(Regex(pattern))
val notEmpty: Predicate<String?> = { !it.isNullOrEmpty() }
val notBlank: Predicate<String?> = { !it.isNullOrBlank() }
val alpha = matches("[a-zA-Z]+")
val numeric = matches("[0-9]+")
val alphanumeric = matches("[a-zA-Z0-9]+")
val email = matches("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$")
fun length(min: Int = 0, max: Int = Int.MAX_VALUE): Predicate<String?> = {
(it?.length ?: 0) in min..max
}
}
fun <T : String?> RuleCollection<T>.matches(pattern: String, message: String? = null): RuleCollection<T> {
rule(Functions.matches(pattern), { message ?: "Invalid value." })
return this
}
fun <T : String?> RuleCollection<T>.matches(regex: Regex, message: String? = null): RuleCollection<T> {
rule(Functions.matches(regex), { message ?: "Invalid value." })
return this
}
fun <T : String?> RuleCollection<T>.doesNotMatch(pattern: String, message: String? = null): RuleCollection<T> {
rule(Functions.doesNotMatch(pattern), { message ?: "Invalid value." })
return this
}
fun <T : String?> RuleCollection<T>.doesNotMatch(regex: Regex, message: String? = null): RuleCollection<T> {
rule(Functions.doesNotMatch(regex), { message ?: "Invalid value." })
return this
}
fun <T : String?> RuleCollection<T>.notEmpty(message: String? = null): RuleCollection<T> {
rule(Functions.notEmpty, { message ?: "Value cannot be empty." })
return this
}
fun <T : String?> RuleCollection<T>.notBlank(message: String? = null): RuleCollection<T> {
rule(Functions.notBlank, { message ?: "Value cannot be blank." })
return this
}
fun <T : String?> RuleCollection<T>.required(message: String? = null): RuleCollection<T> {
rule(Functions.notBlank, { message ?: "A value is required." })
return this
}
fun <T : String?> RuleCollection<T>.alpha(message: String? = null): RuleCollection<T> {
rule(Functions.alpha, { message ?: "Value must contain only alpha characters." })
return this
}
fun <T : String?> RuleCollection<T>.numeric(message: String? = null): RuleCollection<T> {
rule(Functions.numeric, { message ?: "Value must contain only numeric characters." })
return this
}
fun <T : String?> RuleCollection<T>.alphanumeric(message: String? = null): RuleCollection<T> {
rule(Functions.alphanumeric, { message ?: "Value must contain only alphanumeric characters." })
return this
}
fun <T : String?> RuleCollection<T>.email(message: String? = null): RuleCollection<T> {
rule(Functions.email, { message ?: "Value must be a valid email address." })
return this
}
fun <T : String?> RuleCollection<T>.length(min: Int, max: Int, message: String? = null): RuleCollection<T> {
rule(Functions.length(min, max), { message ?: "The value must be between $min and $max characters long." })
return this
} | mit | 0e0478c385b7a58d279b88f30d8ec7b8 | 37.841463 | 111 | 0.665201 | 3.526024 | false | false | false | false |
SpartaHack/SpartaHack-Android | app/src/main/java/com/spartahack/spartahack_android/tools/Timer.kt | 1 | 1244 | package com.spartahack.spartahack_android.tools
import android.os.CountDownTimer
import android.widget.TextView
class Timer(endTimeMills:Long, interval:Long, val timerView:TextView):CountDownTimer(endTimeMills, interval) {
override fun onTick(millsUntilFinished: Long) {
var months = (millsUntilFinished / 2628000000).toString()
var days = (millsUntilFinished % 2628000000 / 86400000).toString()
var hours = (millsUntilFinished % 2628000000 % 86400000 / 3600000).toString()
var minutes = (millsUntilFinished % 2628000000 % 86400000 % 3600000 / 60000).toString()
var seconds = (millsUntilFinished % 2628000000 % 86400000 % 3600000 % 60000 / 1000).toString()
if(months.length != 2){
months = "0" + months
}
if(days.length != 2){
days = "0" + days
}
if(hours.length != 2){
hours = "0" + hours
}
if(minutes.length != 2){
minutes = "0" + minutes
}
if(seconds.length != 2){
seconds = "0" + seconds
}
timerView.text = months + ":" + days + ":" + hours + ":" + minutes + ":" + seconds
}
override fun onFinish(){
timerView.text = ""
}
} | mit | 14320c1e656229e1ad2d4dc35a93952d | 33.583333 | 110 | 0.587621 | 4.174497 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.